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:52 UTC

[03/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/utils/src/com/cloud/utils/db/GenericSearchBuilder.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/db/GenericSearchBuilder.java b/utils/src/com/cloud/utils/db/GenericSearchBuilder.java
deleted file mode 100755
index bf28144..0000000
--- a/utils/src/com/cloud/utils/db/GenericSearchBuilder.java
+++ /dev/null
@@ -1,548 +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.db;
-
-import java.lang.reflect.Field;
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
-
-import javax.persistence.Column;
-import javax.persistence.Transient;
-
-import net.sf.cglib.proxy.Factory;
-import net.sf.cglib.proxy.MethodInterceptor;
-import net.sf.cglib.proxy.MethodProxy;
-
-import com.cloud.utils.db.SearchCriteria.Func;
-import com.cloud.utils.db.SearchCriteria.Op;
-import com.cloud.utils.db.SearchCriteria.SelectType;
-
-/**
- * GenericSearchBuilder is used to build a search based on a VO object
- * a convenience class provided called SearchBuilder that provides
- * exactly that functionality.
- *
- * @param <T> VO object this Search is build for.
- * @param <K> Result object that should contain the results.
- */
-public class GenericSearchBuilder<T, K> implements MethodInterceptor {
-    final protected Map<String, Attribute> _attrs;
-    
-    protected ArrayList<Condition> _conditions;
-    protected HashMap<String, JoinBuilder<GenericSearchBuilder<?, ?>>> _joins;
-    protected ArrayList<Select> _selects;
-    protected GroupBy<T, K> _groupBy = null;
-    protected Class<T> _entityBeanType;
-    protected Class<K> _resultType;
-    protected SelectType _selectType;
-    
-    protected T _entity;
-    protected ArrayList<Attribute> _specifiedAttrs;
-    
-    @SuppressWarnings("unchecked")
-    protected GenericSearchBuilder(T entity, Class<K> clazz, Map<String, Attribute> attrs) {
-        _entityBeanType = (Class<T>)entity.getClass();
-        _resultType = clazz;
-        
-        _attrs = attrs;
-        _entity = entity;
-        _conditions = new ArrayList<Condition>();
-        _joins = null;
-        _specifiedAttrs = new ArrayList<Attribute>();
-    }
-    
-    public T entity() {
-        return _entity;
-    }
-    
-    protected Attribute getSpecifiedAttribute() {
-        if (_entity == null || _specifiedAttrs == null || _specifiedAttrs.size() != 1) {
-            throw new RuntimeException("Now now, better specify an attribute or else we can't help you");
-        }
-        return _specifiedAttrs.get(0);
-    }
-
-    public GenericSearchBuilder<T, K> selectField(Object... useless) {
-        if (_entity == null) {
-            throw new RuntimeException("SearchBuilder cannot be modified once it has been setup");
-        }
-        if (_specifiedAttrs.size() <= 0) {
-            throw new RuntimeException("You didn't specify any attributes");
-        }
-   
-        if (_selects == null) {
-            _selects = new ArrayList<Select>();
-        }
-        
-        for (Attribute attr : _specifiedAttrs) {
-            Field field = null;
-            try {
-                field = _resultType.getDeclaredField(attr.field.getName());
-                field.setAccessible(true);
-            } catch (SecurityException e) {
-            } catch (NoSuchFieldException e) {
-            }
-            _selects.add(new Select(Func.NATIVE, attr, field, null));
-        }
-        
-        _specifiedAttrs.clear();
-        
-        return this;
-    }
-    
-//    public GenericSearchBuilder<T, K> selectField(String joinName, Object... entityFields) {
-//        JoinBuilder<GenericSearchBuilder<?, ?>> jb = _joins.get(joinName);
-//
-//    }
-    
-    /**
-     * Specifies the field to select.
-     * 
-     * @param fieldName The field name of the result object to put the value of the field selected.  This can be null if you're selecting only one field and the result is not a complex object.
-     * @param func function to place.
-     * @param useless column to select.  Call this with this.entity() method.
-     * @param params parameters to the function.
-     * @return a SearchBuilder to build more search parts.
-     */
-    public GenericSearchBuilder<T, K> select(String fieldName, Func func, Object useless, Object... params) {
-        if (_entity == null) {
-            throw new RuntimeException("SearchBuilder cannot be modified once it has been setup");
-        }
-        if (_specifiedAttrs.size() > 1) {
-            throw new RuntimeException("You can't specify more than one field to search on");
-        }
-        if (func.getCount() != -1 && (func.getCount() != (params.length + 1))) {
-            throw new RuntimeException("The number of parameters does not match the function param count for " + func);
-        }
-        
-        if (_selects == null) {
-            _selects = new ArrayList<Select>();
-        }
-        
-        Field field = null;
-        if (fieldName != null) {
-            try {
-                field = _resultType.getDeclaredField(fieldName);
-                field.setAccessible(true);
-            } catch (SecurityException e) {
-                throw new RuntimeException("Unable to find " + fieldName, e);
-            } catch (NoSuchFieldException e) {
-                throw new RuntimeException("Unable to find " + fieldName, e);
-            }
-        } else {
-            if (_selects.size() != 0) {
-                throw new RuntimeException(
-                        "You're selecting more than one item and yet is not providing a container class to put these items in.  So what do you expect me to do.  Spin magic?");
-            }
-        }
-        
-        Select select = new Select(func, _specifiedAttrs.size() == 0 ? null : _specifiedAttrs.get(0), field, params);
-        _selects.add(select);
-        
-        _specifiedAttrs.clear();
-        
-        return this;
-    }
-    
-    @Override
-    public Object intercept(Object object, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
-        String name = method.getName();
-		if (method.getAnnotation(Transient.class) == null) {
-			if (name.startsWith("get")) {
-				String fieldName = Character.toLowerCase(name.charAt(3)) + name.substring(4);
-				set(fieldName);
-				return null;
-			} else if (name.startsWith("is")) {
-				String fieldName = Character.toLowerCase(name.charAt(2)) + name.substring(3);
-				set(fieldName);
-				return null;
-			} else {
-			    Column ann = method.getAnnotation(Column.class);
-			    if (ann != null) {
-			        String colName = ann.name();
-			        for (Map.Entry<String, Attribute> attr : _attrs.entrySet()) {
-			            if (colName.equals(attr.getValue().columnName)) {
-			                set(attr.getKey());
-			                return null;
-			            }
-			        }
-			    }
-                throw new RuntimeException("Perhaps you need to make the method start with get or is: " + method);
-			}
-		}
-        return methodProxy.invokeSuper(object, args);
-    }
-    
-    protected void set(String name) {
-        Attribute attr = _attrs.get(name);
-        assert (attr != null) : "Searching for a field that's not there: " + name;
-        _specifiedAttrs.add(attr);
-    }
-   
-    /**
-     * Adds an AND condition to the SearchBuilder.
-     * 
-     * @param name param name you will use later to set the values in this search condition.
-     * @param useless SearchBuilder.entity().get*() which refers to the field that you're searching on.
-     * @param op operation to apply to the field.
-     * @return this
-     */
-    public GenericSearchBuilder<T, K> and(String name, Object useless, Op op) {
-        constructCondition(name, " AND ", _specifiedAttrs.get(0), op);
-        return this;
-    }
-    
-    public GenericSearchBuilder<T, K> and(Object useless, Op op, String name) {
-        constructCondition(name, " AND ", _specifiedAttrs.get(0), op);
-        return this;
-    }
-
-    public Preset and(Object useless, Op op) {
-        Condition condition = constructCondition(UUID.randomUUID().toString(), " AND ", _specifiedAttrs.get(0), op);
-        return new Preset(this, condition);
-    }
-
-    public GenericSearchBuilder<T, K> and() {
-        constructCondition(null, " AND ", null, null);
-        return this;
-    }
-    
-    public GenericSearchBuilder<T, K> where() {
-        return and();
-    }
-    
-    public GenericSearchBuilder<T, K> or() {
-        constructCondition(null, " OR ", null, null);
-        return this;
-    }
-    
-    public GenericSearchBuilder<T, K> where(String name, Object useless, Op op) {
-        return and(name, useless, op);
-    }
-    
-    public GenericSearchBuilder<T, K> where(Object useless, Op op, String name) {
-        return and(name, useless, op);
-    }
-
-    public Preset where(Object useless, Op op) {
-        return and(useless, op);
-    }
-
-    public GenericSearchBuilder<T, K> left(String name, Object useless, Op op) {
-        constructCondition(name, " ( ", _specifiedAttrs.get(0), op);
-        return this;
-    }
-    
-    public GenericSearchBuilder<T, K> left(Object useless, Op op, String name) {
-        constructCondition(name, " ( ", _specifiedAttrs.get(0), op);
-        return this;
-    }
-
-    public Preset left(Object useless, Op op) {
-        Condition condition = constructCondition(UUID.randomUUID().toString(), " ( ", _specifiedAttrs.get(0), op);
-        return new Preset(this, condition);
-    }
-
-    public GenericSearchBuilder<T, K> op(Object useless, Op op, String name) {
-        return left(useless, op, name);
-    }
-
-    public Preset op(Object useless, Op op) {
-        return left(useless, op);
-    }
-
-    public GenericSearchBuilder<T, K> op(String name, Object useless, Op op) {
-        return left(name, useless, op);
-    }
-    
-    public GenericSearchBuilder<T, K> openParen(Object useless, Op op, String name) {
-        return left(name, useless, op);
-    }
-
-    public GenericSearchBuilder<T, K> openParen(String name, Object useless, Op op) {
-        return left(name, useless, op);
-    }
-    
-    public Preset openParen(Object useless, Op op) {
-        return left(useless, op);
-    }
-
-    public GroupBy<T, K> groupBy(Object... useless) {
-        assert _groupBy == null : "Can't do more than one group bys";
-        _groupBy = new GroupBy<T, K>(this);
-        
-        return _groupBy;
-    }
-    
-    protected List<Attribute> getSpecifiedAttributes() {
-        return _specifiedAttrs;
-    }
-    
-    /**
-     * Adds an OR condition to the SearchBuilder.
-     * 
-     * @param name param name you will use later to set the values in this search condition.
-     * @param useless SearchBuilder.entity().get*() which refers to the field that you're searching on.
-     * @param op operation to apply to the field.
-     * @return this
-     */
-    public GenericSearchBuilder<T, K> or(String name, Object useless, Op op) {
-        constructCondition(name, " OR ", _specifiedAttrs.get(0), op);
-        return this;
-    }
-    
-    public GenericSearchBuilder<T, K> or(Object useless, Op op, String name) {
-        constructCondition(name, " OR ", _specifiedAttrs.get(0), op);
-        return this;
-    }
-
-    public Preset or(Object useless, Op op) {
-        Condition condition = constructCondition(UUID.randomUUID().toString(), " OR ", _specifiedAttrs.get(0), op);
-        return new Preset(this, condition);
-    }
-
-    public GenericSearchBuilder<T, K> join(String name, GenericSearchBuilder<?, ?> builder, Object useless, Object useless2, JoinBuilder.JoinType joinType) {
-        assert _entity != null : "SearchBuilder cannot be modified once it has been setup";
-        assert _specifiedAttrs.size() == 1 : "You didn't select the attribute.";
-        assert builder._entity != null : "SearchBuilder cannot be modified once it has been setup";
-        assert builder._specifiedAttrs.size() == 1 : "You didn't select the attribute.";
-        assert builder != this : "You can't add yourself, can you?  Really think about it!";
-        
-        JoinBuilder<GenericSearchBuilder<?, ?>> t = new JoinBuilder<GenericSearchBuilder<?, ?>>(builder, _specifiedAttrs.get(0), builder._specifiedAttrs.get(0), joinType);
-        if (_joins == null) {
-        	_joins = new HashMap<String, JoinBuilder<GenericSearchBuilder<?, ?>>>();
-        }
-        _joins.put(name, t);
-        
-        builder._specifiedAttrs.clear();
-        _specifiedAttrs.clear();
-        return this;
-    }
-    
-    protected Condition constructCondition(String conditionName, String cond, Attribute attr, Op op) {
-        assert _entity != null : "SearchBuilder cannot be modified once it has been setup";
-        assert op == null || _specifiedAttrs.size() == 1 : "You didn't select the attribute.";
-        assert op != Op.SC : "Call join";
-        
-        Condition condition = new Condition(conditionName, cond, attr, op);
-        _conditions.add(condition);
-        _specifiedAttrs.clear();
-        return condition;
-    }
-
-    /**
-     * creates the SearchCriteria so the actual values can be filled in.
-     * 
-     * @return SearchCriteria
-     */
-    public SearchCriteria<K> create() {
-        if (_entity != null) {
-            done();
-        }
-        return new SearchCriteria<K>(this);
-    }
-    
-    public SearchCriteria<K> create(String name, Object... values) {
-        SearchCriteria<K> sc = create();
-        sc.setParameters(name, values);
-        return sc;
-    }
-    
-    public GenericSearchBuilder<T, K> right() {
-        Condition condition = new Condition("rp", " ) ", null, Op.RP);
-        _conditions.add(condition);
-        return this;
-    }
-    
-    public GenericSearchBuilder<T, K> cp() {
-        return right();
-    }
-    
-    public GenericSearchBuilder<T, K> closeParen() {
-        return right();
-    }
-    
-    public SelectType getSelectType() {
-        return _selectType;
-    }
-    
-    /**
-     * Marks the SearchBuilder as completed in building the search conditions.
-     */
-    public synchronized void done() {
-        if (_entity != null) {
-            Factory factory = (Factory)_entity;
-            factory.setCallback(0, null);
-            _entity = null;
-        }
-        
-        if (_joins != null) {
-        	for (JoinBuilder<GenericSearchBuilder<?, ?>> join : _joins.values()) {
-        		join.getT().done();
-            }
-        }
-        
-        if (_selects == null || _selects.size() == 0) {
-            _selectType = SelectType.Entity;
-            assert _entityBeanType.equals(_resultType) : "Expecting " + _entityBeanType + " because you didn't specify any selects but instead got " + _resultType;
-            return;
-        }
-        
-        for (Select select : _selects) {
-            if (select.field == null) {
-                assert (_selects.size() == 1) : "You didn't specify any fields to put the result in but you're specifying more than one select so where should I put the selects?";
-                _selectType = SelectType.Single;
-                return;
-            }
-            if (select.func != null) {
-                _selectType = SelectType.Result;
-                return;
-            }
-        }
-        
-        _selectType = SelectType.Fields;
-    }
-    
-    protected static class Condition {
-        protected final String name;
-        protected final String cond;
-        protected final Op op;
-        protected final Attribute attr;
-        protected Object[] presets;
-        
-        protected Condition(String name) {
-            this(name, null, null, null);
-        }
-        
-        public Condition(String name, String cond, Attribute attr, Op op) {
-            this.name = name;
-            this.attr = attr;
-            this.cond = cond;
-            this.op = op;
-            this.presets = null;
-        }
-        
-        public boolean isPreset() {
-            return presets != null;
-        }
-
-        public void setPresets(Object... presets) {
-            this.presets = presets;
-        }
-
-        public Object[] getPresets() {
-            return presets;
-        }
-
-        public void toSql(StringBuilder sql, Object[] params, int count) {
-            if (count > 0) {
-                sql.append(cond);
-            }
-            
-            if (op == null) {
-                return;
-            }
-            
-            if (op == Op.SC) {
-                sql.append(" (").append(((SearchCriteria<?>)params[0]).getWhereClause()).append(") ");
-                return;
-            }
-            
-            if (attr == null) {
-                return;
-            }
-            
-            sql.append(attr.table).append(".").append(attr.columnName).append(op.toString());
-            if (op == Op.IN && params.length == 1) {
-                sql.delete(sql.length() - op.toString().length(), sql.length());
-                sql.append("=?");
-            } else if (op == Op.NIN && params.length == 1) {
-                sql.delete(sql.length() - op.toString().length(), sql.length());
-                sql.append("!=?");
-            } else if (op.getParams() == -1) {
-                for (int i = 0; i < params.length; i++) {
-                    sql.insert(sql.length() - 2, "?,");
-                }
-                sql.delete(sql.length() - 3, sql.length() - 2); // remove the last ,
-            } else if (op  == Op.EQ && (params == null || params.length == 0 || params[0] == null)) {
-                sql.delete(sql.length() - 4, sql.length());
-                sql.append(" IS NULL ");
-            } else if (op == Op.NEQ && (params == null || params.length == 0 || params[0] == null)) {
-                sql.delete(sql.length() - 5, sql.length());
-                sql.append(" IS NOT NULL ");
-            } else {
-                if ((op.getParams() != 0 || params != null) && (params.length != op.getParams())) {
-                    throw new RuntimeException("Problem with condition: " + name);
-                }
-            }
-        }
-        
-        @Override
-        public int hashCode() {
-            return name.hashCode();
-        }
-        
-        @Override
-        public boolean equals(Object obj) {
-            if (!(obj instanceof Condition)) {
-                return false;
-            }
-            
-            Condition condition = (Condition)obj;
-            return name.equals(condition.name);
-        }
-    }
-    
-    protected static class Select {
-        public Func func;
-        public Attribute attr;
-        public Object[] params;
-        public Field field;
-        
-        protected Select() {
-        }
-        
-        public Select(Func func, Attribute attr, Field field, Object[] params) {
-            this.func = func;
-            this.attr = attr;
-            this.params = params;
-            this.field = field;
-        }
-    }
-    
-    public class Preset {
-        GenericSearchBuilder<T, K> builder;
-        Condition condition;
-
-        protected Preset(GenericSearchBuilder<T, K> builder, Condition condition) {
-            this.builder = builder;
-            this.condition = condition;
-        }
-
-        public GenericSearchBuilder<T, K> values(Object... params) {
-            if (condition.op.getParams() > 0 && condition.op.params != params.length) {
-                throw new RuntimeException("The # of parameters set " + params.length + " does not match # of parameters required by " + condition.op);
-            }
-            condition.setPresets(params);
-            return builder;
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f5e5b39c/utils/src/com/cloud/utils/db/GlobalLock.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/db/GlobalLock.java b/utils/src/com/cloud/utils/db/GlobalLock.java
deleted file mode 100644
index c956bbf..0000000
--- a/utils/src/com/cloud/utils/db/GlobalLock.java
+++ /dev/null
@@ -1,244 +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.db;
-
-import static java.lang.String.format;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.concurrent.Callable;
-
-import org.apache.log4j.Logger;
-
-import com.cloud.utils.Profiler;
-
-//
-// Wrapper class for global database lock to reduce contention for database connections from within process
-//
-// Example of using dynamic named locks
-//
-//		GlobalLock lock = GlobalLock.getInternLock("some table name" + rowId);
-//		
-//		if(lock.lock()) {
-//			try {
-//				do something
-//			} finally {
-//				lock.unlock();
-//			}
-//		}
-//		lock.releaseRef();
-//
-public class GlobalLock {
-    protected final static Logger s_logger = Logger.getLogger(GlobalLock.class);
-
-	private String name;
-	private int lockCount = 0;
-	private Thread ownerThread = null;
-	
-	private int referenceCount = 0;
-	private long holdingStartTick = 0;
-	
-	private static Map<String, GlobalLock> s_lockMap = new HashMap<String, GlobalLock>();
-	
-	private GlobalLock(String name) {
-		this.name = name;
-	}
-	
-	public int addRef() {
-		synchronized(this) {
-			referenceCount++;
-			return referenceCount;
-		}
-	}
-	
-	public int releaseRef() {
-		int refCount;
-		
-		boolean needToRemove = false;
-		synchronized(this) {
-			referenceCount--;
-			refCount = referenceCount;
-			
-			if(referenceCount < 0)
-				s_logger.warn("Unmatched Global lock " + name + " reference usage detected, check your code!");
-			
-			if(referenceCount == 0)
-				needToRemove = true;
-		}
-		
-		if(needToRemove)
-			releaseInternLock(name);
-		
-		return refCount;
-	}
-
-	public static GlobalLock getInternLock(String name) {
-		synchronized(s_lockMap) {
-			if(s_lockMap.containsKey(name)) {
-				GlobalLock lock = s_lockMap.get(name);
-				lock.addRef();
-				return lock;
-			} else {
-				GlobalLock lock = new GlobalLock(name);
-				lock.addRef();
-				s_lockMap.put(name, lock);
-				return lock;
-			}
-		}
-	}
-	
-	private static void releaseInternLock(String name) {
-		synchronized(s_lockMap) {
-			GlobalLock lock = s_lockMap.get(name);
-			if(lock != null) {
-				if(lock.referenceCount == 0)
-					s_lockMap.remove(name);
-			} else {
-				s_logger.warn("Releasing " + name + ", but it is already released.");
-			}
-		}
-	}
-	
-	public boolean lock(int timeoutSeconds) {
-		int remainingMilliSeconds = timeoutSeconds*1000;
-		Profiler profiler = new Profiler();
-		boolean interrupted = false;
-		try {
-			while(true) {
-				synchronized(this) {
-					if(ownerThread != null && ownerThread == Thread.currentThread()) {
-						s_logger.warn("Global lock re-entrance detected");
-						
-						lockCount++;
-	
-						if(s_logger.isTraceEnabled())
-							s_logger.trace("lock " + name + " is acquired, lock count :" + lockCount);
-						return true;
-					}
-					
-					if(ownerThread != null) {
-						profiler.start();
-						try {
-							wait(((long)timeoutSeconds)*1000L);
-						} catch (InterruptedException e) {
-							interrupted = true;
-						}
-						profiler.stop();
-						
-						remainingMilliSeconds -= profiler.getDuration();
-						if(remainingMilliSeconds < 0)
-							return false;
-						
-						continue;
-					} else {
-						// take ownership temporarily to prevent others enter into stage of acquiring DB lock
-						ownerThread = Thread.currentThread();
-						addRef();
-					}
-				}
-
-				if(DbUtil.getGlobalLock(name, remainingMilliSeconds / 1000)) {
-					synchronized(this) {
-						lockCount++;
-						holdingStartTick = System.currentTimeMillis();
-						
-						if(s_logger.isTraceEnabled())
-							s_logger.trace("lock " + name + " is acquired, lock count :" + lockCount);
-						return true;
-					}
-				} else {
-					synchronized(this) {
-						ownerThread = null;
-						releaseRef();
-						return false;
-					}
-				}
-			}
-		} finally {
-			if(interrupted) {
-				Thread.currentThread().interrupt();
-			}
-		}
-	}
-	
-	public boolean unlock() {
-		synchronized(this) {
-			if(ownerThread != null && ownerThread == Thread.currentThread()) {
-				lockCount--;
-				if(lockCount == 0) {
-					ownerThread = null;
-					DbUtil.releaseGlobalLock(name);
-					
-					if(s_logger.isTraceEnabled())
-						s_logger.trace("lock " + name + " is returned to free state, total holding time :" + 
-							(System.currentTimeMillis() - holdingStartTick));
-					holdingStartTick = 0;
-					
-					// release holding position in intern map when we released the DB connection
-					releaseRef();
-					notifyAll();
-				}
-				
-				if(s_logger.isTraceEnabled())
-					s_logger.trace("lock " + name + " is released, lock count :" + lockCount);
-				return true;
-			}
-			return false;
-		}
-	}
-	
-	public String getName() {
-		return name;
-	}
-
-    public static <T> T executeWithLock(final String operationId,
-            final int lockAcquisitionTimeout, final Callable<T> operation)
-            throws Exception {
-
-        final GlobalLock lock = GlobalLock.getInternLock(operationId);
-
-        try {
-
-            if (!lock.lock(lockAcquisitionTimeout)) {
-                if (s_logger.isDebugEnabled()) {
-                    s_logger.debug(format(
-                            "Failed to acquire lock for operation id %1$s",
-                            operationId));
-                }
-                return null;
-            }
-
-            return operation.call();
-
-        } finally {
-
-            if (lock != null) {
-                lock.unlock();
-            }
-
-        }
-
-    }
-
-    public static <T> T executeWithNoWaitLock(final String operationId,
-            final Callable<T> operation) throws Exception {
-
-        return executeWithLock(operationId, 0, operation);
-
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f5e5b39c/utils/src/com/cloud/utils/db/GroupBy.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/db/GroupBy.java b/utils/src/com/cloud/utils/db/GroupBy.java
deleted file mode 100644
index 3b9cd19..0000000
--- a/utils/src/com/cloud/utils/db/GroupBy.java
+++ /dev/null
@@ -1,108 +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.db;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import com.cloud.utils.Pair;
-import com.cloud.utils.db.SearchCriteria.Func;
-import com.cloud.utils.db.SearchCriteria.Op;
-
-public class GroupBy<T, R> {
-    GenericSearchBuilder<T, R> _builder;
-    List<Pair<Func, Attribute>> _groupBys;
-    Having _having;
-    
-    public GroupBy(GenericSearchBuilder<T, R> builder) {
-        _builder = builder;
-        _groupBys = new ArrayList<Pair<Func, Attribute>>();
-        _having = null;
-        for (Attribute attr : _builder.getSpecifiedAttributes()) {
-            _groupBys.add(new Pair<Func, Attribute>(null, attr));
-        }
-        _builder.getSpecifiedAttributes().clear();
-    }
-    
-    public GroupBy<T, R> group(Object useless) {
-        _groupBys.add(new Pair<Func, Attribute>(null, _builder.getSpecifiedAttributes().get(0)));
-        _builder.getSpecifiedAttributes().clear();
-        return this; 
-    }
-    
-    public GroupBy<T, R> group(Func func, Object useless) {
-        _groupBys.add(new Pair<Func, Attribute>(func, _builder.getSpecifiedAttributes().get(0)));
-        _builder.getSpecifiedAttributes().clear();
-        return this;
-    }
-    
-    public GenericSearchBuilder<T, R> having(Func func, Object obj, Op op, Object value) {
-        assert(_having == null) : "You can only specify one having in a group by";
-        List<Attribute> attrs = _builder.getSpecifiedAttributes();
-        assert attrs.size() == 1 : "You didn't specified an attribute";
-        
-        _having = new Having(func, attrs.get(0), op, value);
-        _builder.getSpecifiedAttributes().clear();
-        return _builder;
-    }
-    
-    public void toSql(StringBuilder builder) {
-        builder.append(" GROUP BY ");
-        for (Pair<Func, Attribute> groupBy : _groupBys) {
-            if (groupBy.first() != null) {
-                String func = groupBy.first().toString();
-                func.replaceFirst("@", groupBy.second().table + "." + groupBy.second().columnName);
-                builder.append(func);
-            } else {
-                builder.append(groupBy.second().table + "." + groupBy.second().columnName);
-            }
-            
-            builder.append(", ");
-        }
-        
-        builder.delete(builder.length() - 2, builder.length());
-        if (_having != null) {
-            _having.toSql(builder);
-        }
-    }
-    
-    protected class Having {
-        public Func func;
-        public Attribute attr;
-        public Op op;
-        public Object value;
-        
-        public Having(Func func, Attribute attr, Op op, Object value) {
-            this.func = func;
-            this.attr = attr;
-            this.op = op;
-            this.value = value;
-        }
-        
-        public void toSql(StringBuilder builder) {
-            if (func != null) {
-                String f = func.toString();
-                f.replaceFirst("@", attr.toString());
-                builder.append(func);
-            } else {
-                builder.append(attr.toString());
-            }
-            
-            builder.append(op.toString());
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f5e5b39c/utils/src/com/cloud/utils/db/JoinBuilder.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/db/JoinBuilder.java b/utils/src/com/cloud/utils/db/JoinBuilder.java
deleted file mode 100644
index c4920c4..0000000
--- a/utils/src/com/cloud/utils/db/JoinBuilder.java
+++ /dev/null
@@ -1,79 +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.db;
-
-
-public class JoinBuilder<T> {
-	
-	public enum JoinType {
-	     INNER ("INNER JOIN"),
-	     LEFT ("LEFT JOIN"),
-	     RIGHT ("RIGHT JOIN"),
-	     RIGHTOUTER ("RIGHT OUTER JOIN"),
-	     LEFTOUTER ("LEFT OUTER JOIN");
-	     
-	     private final String _name;
-	     
-	     JoinType(String name) {
-	            _name = name;
-	     }
-	     
-	     public String getName() { return _name; }
-	}
-
-	
-	private T t;
-	private JoinType type;
-	private Attribute firstAttribute;
-	private Attribute secondAttribute;
-	
-	public JoinBuilder(T t, Attribute firstAttribute,
-			Attribute secondAttribute, JoinType type) {
-		this.t = t;
-		this.firstAttribute = firstAttribute;
-		this.secondAttribute = secondAttribute;
-		this.type = type;
-	}
-	
-	public T getT() {
-		return t;
-	}
-	public void setT(T t) {
-		this.t = t;
-	}
-	public JoinType getType() {
-		return type;
-	}
-	public void setType(JoinType type) {
-		this.type = type;
-	}
-	public Attribute getFirstAttribute() {
-		return firstAttribute;
-	}
-	public void setFirstAttribute(Attribute firstAttribute) {
-		this.firstAttribute = firstAttribute;
-	}
-	public Attribute getSecondAttribute() {
-		return secondAttribute;
-	}
-	public void setSecondAttribute(Attribute secondAttribute) {
-		this.secondAttribute = secondAttribute;
-	}
-
-}
-
-

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f5e5b39c/utils/src/com/cloud/utils/db/JoinType.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/db/JoinType.java b/utils/src/com/cloud/utils/db/JoinType.java
deleted file mode 100755
index 6861925..0000000
--- a/utils/src/com/cloud/utils/db/JoinType.java
+++ /dev/null
@@ -1,32 +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.db;
-
-import static java.lang.annotation.ElementType.TYPE;
-import static java.lang.annotation.RetentionPolicy.RUNTIME;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-
-/**
- * JoinType is only used with SecondaryTable.  Temporary solution.   
- */
-@Target(TYPE)
-@Retention(RUNTIME)
-public @interface JoinType {
-    String type() default "inner";
-}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f5e5b39c/utils/src/com/cloud/utils/db/Merovingian2.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/db/Merovingian2.java b/utils/src/com/cloud/utils/db/Merovingian2.java
deleted file mode 100644
index 0e0e8f2..0000000
--- a/utils/src/com/cloud/utils/db/Merovingian2.java
+++ /dev/null
@@ -1,461 +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.db;
-
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.TimeZone;
-
-import javax.management.StandardMBean;
-
-import org.apache.log4j.Logger;
-
-import com.cloud.utils.DateUtil;
-import com.cloud.utils.exception.CloudRuntimeException;
-import com.cloud.utils.mgmt.JmxUtil;
-import com.cloud.utils.time.InaccurateClock;
-
-
-public class Merovingian2 extends StandardMBean implements MerovingianMBean {
-    private static final Logger s_logger = Logger.getLogger(Merovingian2.class);
-
-    private static final String ACQUIRE_SQL = "INSERT INTO op_lock (op_lock.key, op_lock.mac, op_lock.ip, op_lock.thread, op_lock.acquired_on, waiters) VALUES (?, ?, ?, ?, ?, 1)";
-    private static final String INCREMENT_SQL = "UPDATE op_lock SET waiters=waiters+1 where op_lock.key=? AND op_lock.mac=? AND op_lock.ip=? AND op_lock.thread=?";
-    private static final String SELECT_SQL = "SELECT op_lock.key, mac, ip, thread, acquired_on, waiters FROM op_lock";
-    private static final String INQUIRE_SQL = SELECT_SQL + " WHERE op_lock.key=?";
-    private static final String DECREMENT_SQL = "UPDATE op_lock SET waiters=waiters-1 where op_lock.key=? AND op_lock.mac=? AND op_lock.ip=? AND op_lock.thread=?";
-    private static final String RELEASE_LOCK_SQL = "DELETE FROM op_lock WHERE op_lock.key = ?";
-    private static final String RELEASE_SQL = RELEASE_LOCK_SQL + " AND op_lock.mac=? AND waiters=0";
-    private static final String CLEANUP_MGMT_LOCKS_SQL = "DELETE FROM op_lock WHERE op_lock.mac = ?";
-    private static final String SELECT_MGMT_LOCKS_SQL = SELECT_SQL + " WHERE mac=?";
-    private static final String SELECT_THREAD_LOCKS_SQL = SELECT_SQL + " WHERE mac=? AND ip=?";
-    private static final String CLEANUP_THREAD_LOCKS_SQL = "DELETE FROM op_lock WHERE mac=? AND ip=? AND thread=?";
-
-    TimeZone s_gmtTimeZone = TimeZone.getTimeZone("GMT");
-
-    private final long _msId;
-
-    private static Merovingian2 s_instance = null;
-    private ConnectionConcierge _concierge = null;
-    private static ThreadLocal<Count> s_tls = new ThreadLocal<Count>();
-
-    private Merovingian2(long msId) {
-        super(MerovingianMBean.class, false);
-        _msId = msId;
-        Connection conn = null;
-        try {
-            conn = Transaction.getStandaloneConnectionWithException();
-            conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
-            conn.setAutoCommit(true);
-            _concierge = new ConnectionConcierge("LockMaster", conn, true);
-        } catch (SQLException e) {
-            s_logger.error("Unable to get a new db connection", e);
-            throw new CloudRuntimeException("Unable to initialize a connection to the database for locking purposes: ", e);
-        }
-    }
-
-    public static synchronized Merovingian2 createLockMaster(long msId) {
-        assert s_instance == null : "No lock can serve two masters.  Either he will hate the one and love the other, or he will be devoted to the one and despise the other.";
-        s_instance = new Merovingian2(msId);
-        s_instance.cleanupThisServer();
-        try {
-            JmxUtil.registerMBean("Locks", "Locks", s_instance);
-        } catch (Exception e) {
-            s_logger.error("Unable to register for JMX", e);
-        }
-        return s_instance;
-    }
-
-    public static Merovingian2 getLockMaster() {
-        return s_instance;
-    }
-
-
-    protected void incrCount() {
-        Count count = s_tls.get();
-        if (count == null) {
-            count = new Count();
-            s_tls.set(count);
-        }
-
-        count.count++;
-    }
-
-    protected void decrCount() {
-        Count count = s_tls.get();
-        if (count == null) {
-            return;
-        }
-
-        count.count--;
-    }
-
-
-    public boolean acquire(String key, int timeInSeconds) {
-        Thread th = Thread.currentThread();
-        String threadName = th.getName();
-        int threadId = System.identityHashCode(th);
-
-        if (s_logger.isTraceEnabled()) {
-            s_logger.trace("Acquiring lck-" + key + " with wait time of " + timeInSeconds);
-        }
-        long startTime = InaccurateClock.getTime();
-
-        while ((InaccurateClock.getTime() - startTime) < (timeInSeconds * 1000)) {
-            int count = owns(key);
-
-            if (count >= 1) {
-                return increment(key, threadName, threadId);
-            } else if (count == 0) {
-                if (doAcquire(key, threadName, threadId)) {
-                    return true;
-                }
-            }
-            try {
-                if (s_logger.isTraceEnabled()) {
-                    s_logger.trace("Sleeping more time while waiting for lck-" + key);
-                }
-                Thread.sleep(5000);
-            } catch (InterruptedException e) {
-            }
-        }
-        if (s_logger.isTraceEnabled()) {
-            s_logger.trace("Timed out on acquiring lock " + key + ".  Waited for " + (InaccurateClock.getTime() - startTime));
-        }
-        return false;
-    }
-
-    protected boolean increment(String key, String threadName, int threadId) {
-        PreparedStatement pstmt = null;
-        try {
-            pstmt = _concierge.conn().prepareStatement(INCREMENT_SQL);
-            pstmt.setString(1, key);
-            pstmt.setLong(2, _msId);
-            pstmt.setString(3, threadName);
-            pstmt.setInt(4, threadId);
-            int rows = pstmt.executeUpdate();
-            assert (rows <= 1) : "hmm...non unique key? " + pstmt;
-            if (s_logger.isTraceEnabled()) {
-                s_logger.trace("lck-" + key + (rows == 1 ? " acquired again" : " failed to acquire again"));
-            }
-            if (rows == 1) {
-                incrCount();
-                return true;
-            }
-            return false;
-        } catch (SQLException e) {
-            throw new CloudRuntimeException("Unable to increment " + key, e);
-        } finally {
-            try {
-                if (pstmt != null) {
-                    pstmt.close();
-                }
-            } catch (SQLException e) {
-            }
-        }
-    }
-
-    protected boolean doAcquire(String key, String threadName, int threadId) {
-        PreparedStatement pstmt = null;
-
-        long startTime = InaccurateClock.getTime();
-        try {
-            pstmt = _concierge.conn().prepareStatement(ACQUIRE_SQL);
-            pstmt.setString(1, key);
-            pstmt.setLong(2, _msId);
-            pstmt.setString(3, threadName);
-            pstmt.setInt(4, threadId);
-            pstmt.setString(5, DateUtil.getDateDisplayString(s_gmtTimeZone, new Date()));
-            try {
-                int rows = pstmt.executeUpdate();
-                if (rows == 1) {
-                    if (s_logger.isTraceEnabled()) {
-                        s_logger.trace("Acquired for lck-" + key);
-                    }
-                    incrCount();
-                    return true;
-                }
-            } catch(SQLException e) {
-                if (!(e.getSQLState().equals("23000") && e.getErrorCode() == 1062)) {
-                    throw new CloudRuntimeException("Unable to lock " + key + ".  Waited " + (InaccurateClock.getTime() - startTime), e);
-                }
-            }
-        } catch(SQLException e) {
-            throw new CloudRuntimeException("Unable to lock " + key + ".  Waited " + (InaccurateClock.getTime() - startTime), e);
-        } finally {
-            try {
-                if (pstmt != null) {
-                    pstmt.close();
-                }
-            } catch (SQLException e) {
-            }
-        }
-
-        s_logger.trace("Unable to acquire lck-" + key);
-        return false;
-    }
-
-    protected Map<String, String> isLocked(String key) {
-        PreparedStatement pstmt = null;
-        ResultSet rs = null;
-        try {
-            pstmt = _concierge.conn().prepareStatement(INQUIRE_SQL);
-            pstmt.setString(1, key);
-            rs = pstmt.executeQuery();
-            if (!rs.next()) {
-                return null;
-            }
-
-            return toLock(rs);
-        } catch (SQLException e) {
-            throw new CloudRuntimeException("SQL Exception on inquiry", e);
-        } finally {
-            try {
-                if (rs != null) {
-                    rs.close();
-                }
-                if (pstmt != null) {
-                    pstmt.close();
-                }
-            } catch (SQLException e) {
-                s_logger.warn("Unexpected SQL exception " + e.getMessage(), e);
-            }
-        }
-    }
-
-    public void cleanupThisServer() {
-        cleanupForServer(_msId);
-    }
-
-    @Override
-    public void cleanupForServer(long msId) {
-        s_logger.info("Cleaning up locks for " + msId);
-        PreparedStatement pstmt = null;
-        try {
-            pstmt = _concierge.conn().prepareStatement(CLEANUP_MGMT_LOCKS_SQL);
-            pstmt.setLong(1, msId);
-            int rows = pstmt.executeUpdate();
-            s_logger.info("Released " + rows + " locks for " + msId);
-        } catch (SQLException e) {
-            throw new CloudRuntimeException("Unable to clear the locks", e);
-        } finally {
-            try {
-                if (pstmt != null) {
-                    pstmt.close();
-                }
-            } catch (SQLException e) {
-            }
-        }
-    }
-
-    public boolean release(String key) {
-        PreparedStatement pstmt = null;
-        Thread th = Thread.currentThread();
-        String threadName = th.getName();
-        int threadId = System.identityHashCode(th);
-        try {
-            pstmt = _concierge.conn().prepareStatement(DECREMENT_SQL);
-            pstmt.setString(1, key);
-            pstmt.setLong(2, _msId);
-            pstmt.setString(3, threadName);
-            pstmt.setLong(4, threadId);
-            int rows = pstmt.executeUpdate();
-            assert (rows <= 1) : "hmmm....keys not unique? " + pstmt;
-           
-            
-            if (s_logger.isTraceEnabled()) {
-                s_logger.trace("lck-" + key + " released");
-            }
-            if (rows == 1) {
-                pstmt.close();
-                pstmt = _concierge.conn().prepareStatement(RELEASE_SQL);
-                pstmt.setString(1, key);
-                pstmt.setLong(2, _msId);
-                int result = pstmt.executeUpdate();
-                if (result == 1 && s_logger.isTraceEnabled()) {
-                    s_logger.trace("lck-" + key + " removed");
-                }
-                decrCount();
-            } else  if (rows < 1) {
-                s_logger.warn("Was unable to find lock for the key " + key + " and thread id " + threadId);
-            }
-            
-            return rows == 1;
-        } catch (SQLException e) {
-            throw new CloudRuntimeException("Unable to release " + key, e);
-        } finally {
-            try {
-                if (pstmt != null) {
-                    pstmt.close();
-                }
-            } catch (SQLException e) {
-            }
-        }
-    }
-
-    protected Map<String, String> toLock(ResultSet rs) throws SQLException {
-        Map<String, String> map = new HashMap<String, String>();
-        map.put("key", rs.getString(1));
-        map.put("mgmt", rs.getString(2));
-        map.put("name", rs.getString(3));
-        map.put("tid", Integer.toString(rs.getInt(4)));
-        map.put("date", rs.getString(5));
-        map.put("count", Integer.toString(rs.getInt(6)));
-        return map;
-
-    }
-
-    protected List<Map<String, String>> toLocks(ResultSet rs) throws SQLException {
-        LinkedList<Map<String, String>> results = new LinkedList<Map<String, String>>();
-        while (rs.next()) {
-            results.add(toLock(rs));
-        }
-        return results;
-    }
-
-    protected List<Map<String, String>> getLocks(String sql, Long msId) {
-        PreparedStatement pstmt = null;
-        ResultSet rs = null;
-        try {
-            pstmt = _concierge.conn().prepareStatement(sql);
-            if (msId != null) {
-                pstmt.setLong(1, msId);
-            }
-            rs = pstmt.executeQuery();
-            return toLocks(rs);
-        } catch (SQLException e) {
-            throw new CloudRuntimeException("Unable to retrieve locks ", e);
-        } finally {
-            try {
-                if (rs != null) {
-                    rs.close();
-                }
-                if (pstmt != null) {
-                    pstmt.close();
-                }
-            } catch(SQLException e) {
-            }
-        }
-    }
-
-    @Override
-    public List<Map<String, String>> getAllLocks() {
-        return getLocks(SELECT_SQL, null);
-    }
-
-    @Override
-    public List<Map<String, String>> getLocksAcquiredByThisServer() {
-        return getLocks(SELECT_MGMT_LOCKS_SQL, _msId);
-    }
-
-    public int owns(String key) {
-        Thread th = Thread.currentThread();
-        int threadId = System.identityHashCode(th);
-        Map<String, String> owner = isLocked(key);
-        if (owner == null) {
-            return 0;
-        }
-        if (owner.get("mgmt").equals(Long.toString(_msId)) && owner.get("tid").equals(Integer.toString(threadId))) {
-            return Integer.parseInt(owner.get("count"));
-        }
-        return -1;
-    }
-
-    public List<Map<String, String>> getLocksAcquiredBy(long msId, String threadName) {
-        PreparedStatement pstmt = null;
-        ResultSet rs = null;
-        try {
-            pstmt = _concierge.conn().prepareStatement(SELECT_THREAD_LOCKS_SQL);
-            pstmt.setLong(1, msId);
-            pstmt.setString(2, threadName);
-            rs = pstmt.executeQuery();
-            return toLocks(rs);
-        } catch (SQLException e) {
-            throw new CloudRuntimeException("Can't get locks " + pstmt, e);
-        } finally {
-            try {
-                if (rs != null) {
-                    rs.close();
-                }
-                if (pstmt != null) {
-                    pstmt.close();
-                }
-            } catch (SQLException e) {
-            }
-        }
-    }
-
-    public void cleanupThread() {
-
-        Count count = s_tls.get();
-        if (count == null || count.count == 0) {
-            return;
-        }
-
-        int c = count.count;
-
-        count.count = 0;
-
-        Thread th = Thread.currentThread();
-        String threadName = th.getName();
-        int threadId = System.identityHashCode(th);
-
-        PreparedStatement pstmt = null;
-        try {
-            pstmt = _concierge.conn().prepareStatement(CLEANUP_THREAD_LOCKS_SQL);
-            pstmt.setLong(1, _msId);
-            pstmt.setString(2, threadName);
-            pstmt.setInt(3, threadId);
-            int rows = pstmt.executeUpdate();
-            assert (false) : "Abandon hope, all ye who enter here....There were still " + rows + ":" + c + " locks not released when the transaction ended, check for lock not released or @DB is not added to the code that using the locks!";
-        } catch (SQLException e) {
-            throw new CloudRuntimeException("Can't clear locks " + pstmt, e);
-        } finally {
-            try {
-                if (pstmt != null) {
-                    pstmt.close();
-                }
-            } catch (SQLException e) {
-            }
-        }
-    }
-
-    @Override
-    public boolean releaseLockAsLastResortAndIReallyKnowWhatIAmDoing(String key) {
-        s_logger.info("Releasing a lock from JMX lck-" + key);
-        PreparedStatement pstmt = null;
-        try {
-            pstmt = _concierge.conn().prepareStatement(RELEASE_LOCK_SQL);
-            pstmt.setString(1, key);
-            int rows = pstmt.executeUpdate();
-            return rows > 0;
-        } catch (SQLException e) {
-            s_logger.error("Unable to release lock " + key, e);
-            return false;
-        }
-    }
-    protected static class Count {
-        public int count = 0;
-    }
-}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f5e5b39c/utils/src/com/cloud/utils/db/MerovingianMBean.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/db/MerovingianMBean.java b/utils/src/com/cloud/utils/db/MerovingianMBean.java
deleted file mode 100644
index e9ee955..0000000
--- a/utils/src/com/cloud/utils/db/MerovingianMBean.java
+++ /dev/null
@@ -1,32 +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.db;
-
-import java.util.List;
-import java.util.Map;
-
-
-public interface MerovingianMBean {
-    
-    List<Map<String, String>> getAllLocks();
-    
-    List<Map<String, String>> getLocksAcquiredByThisServer();
-    
-    boolean releaseLockAsLastResortAndIReallyKnowWhatIAmDoing(String key);
-    
-    void cleanupForServer(long msId);
-}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f5e5b39c/utils/src/com/cloud/utils/db/ScriptRunner.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/db/ScriptRunner.java b/utils/src/com/cloud/utils/db/ScriptRunner.java
deleted file mode 100644
index d579de7..0000000
--- a/utils/src/com/cloud/utils/db/ScriptRunner.java
+++ /dev/null
@@ -1,233 +0,0 @@
-/*
- * Slightly modified version of the com.ibatis.common.jdbc.ScriptRunner class
- * from the iBATIS Apache project. Only removed dependency on Resource class
- * and a constructor 
- */
-/*
- *  Copyright 2004 Clinton Begin
- *
- *  Licensed 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 java.io.IOException;
-import java.io.LineNumberReader;
-import java.io.Reader;
-import java.sql.Connection;
-import java.sql.ResultSet;
-import java.sql.ResultSetMetaData;
-import java.sql.SQLException;
-import java.sql.Statement;
-
-import org.apache.log4j.Logger;
-
-/**
- * Tool to run database scripts
- */
-public class ScriptRunner {
-    private static Logger s_logger = Logger.getLogger(ScriptRunner.class); 
-
-    private static final String DEFAULT_DELIMITER = ";";
-
-    private Connection connection;
-
-    private boolean stopOnError;
-    private boolean autoCommit;
-    private boolean verbosity = true;
-
-    private String delimiter = DEFAULT_DELIMITER;
-    private boolean fullLineDelimiter = false;
-
-    private StringBuffer _logBuffer = new StringBuffer();
-
-    /**
-     * Default constructor
-     */
-    public ScriptRunner(Connection connection, boolean autoCommit, boolean stopOnError) {
-        this.connection = connection;
-        this.autoCommit = autoCommit;
-        this.stopOnError = stopOnError;
-    }
-
-    public ScriptRunner(Connection connection, boolean autoCommit, boolean stopOnError, boolean verbosity) {
-        this.connection = connection;
-        this.autoCommit = autoCommit;
-        this.stopOnError = stopOnError;
-        this.verbosity = verbosity;
-    }
-
-    public void setDelimiter(String delimiter, boolean fullLineDelimiter) {
-        this.delimiter = delimiter;
-        this.fullLineDelimiter = fullLineDelimiter;
-    }
-
-    /**
-     * Runs an SQL script (read in using the Reader parameter)
-     * 
-     * @param reader
-     *            - the source of the script
-     */
-    public void runScript(Reader reader) throws IOException, SQLException {
-        try {
-            boolean originalAutoCommit = connection.getAutoCommit();
-            try {
-                if (originalAutoCommit != this.autoCommit) {
-                    connection.setAutoCommit(this.autoCommit);
-                }
-                runScript(connection, reader);
-            } finally {
-                connection.setAutoCommit(originalAutoCommit);
-            }
-        } catch (IOException e) {
-            throw e;
-        } catch (SQLException e) {
-            throw e;
-        } catch (Exception e) {
-            throw new RuntimeException("Error running script.  Cause: " + e, e);
-        }
-    }
-
-    /**
-     * Runs an SQL script (read in using the Reader parameter) using the
-     * connection passed in
-     * 
-     * @param conn
-     *            - the connection to use for the script
-     * @param reader
-     *            - the source of the script
-     * @throws SQLException
-     *             if any SQL errors occur
-     * @throws IOException
-     *             if there is an error reading from the Reader
-     */
-    private void runScript(Connection conn, Reader reader) throws IOException, SQLException {
-        StringBuffer command = null;
-        try {
-            LineNumberReader lineReader = new LineNumberReader(reader);
-            String line = null;
-            while ((line = lineReader.readLine()) != null) {
-                if (command == null) {
-                    command = new StringBuffer();
-                }
-                String trimmedLine = line.trim();
-                if (trimmedLine.startsWith("--")) {
-                    println(trimmedLine);
-                } else if (trimmedLine.length() < 1 || trimmedLine.startsWith("//")) {
-                    // Do nothing
-                } else if (trimmedLine.length() < 1 || trimmedLine.startsWith("--")) {
-                    // Do nothing
-                } else if (trimmedLine.length() < 1 || trimmedLine.startsWith("#")) { 
-                    // Do nothing  
-                } else if (!fullLineDelimiter && trimmedLine.endsWith(getDelimiter()) || fullLineDelimiter && trimmedLine.equals(getDelimiter())) {
-                    command.append(line.substring(0, line.lastIndexOf(getDelimiter())));
-                    command.append(" ");
-                    Statement statement = conn.createStatement();
-
-                    println(command);
-
-                    boolean hasResults = false;
-                    if (stopOnError) {
-                        hasResults = statement.execute(command.toString());
-                    } else {
-                        try {
-                            statement.execute(command.toString());
-                        } catch (SQLException e) {
-                            e.fillInStackTrace();
-                            printlnError("Error executing: " + command);
-                            printlnError(e);
-                        }
-                    }
-
-                    if (autoCommit && !conn.getAutoCommit()) {
-                        conn.commit();
-                    }
-
-                    ResultSet rs = statement.getResultSet();
-                    if (hasResults && rs != null) {
-                        ResultSetMetaData md = rs.getMetaData();
-                        int cols = md.getColumnCount();
-                        for (int i = 0; i < cols; i++) {
-                            String name = md.getColumnLabel(i);
-                            print(name + "\t");
-                        }
-                        println("");
-                        while (rs.next()) {
-                            for (int i = 0; i < cols; i++) {
-                                String value = rs.getString(i);
-                                print(value + "\t");
-                            }
-                            println("");
-                        }
-                    }
-
-                    command = null;
-                    try {
-                        statement.close();
-                    } catch (Exception e) {
-                        // Ignore to workaround a bug in Jakarta DBCP
-                    }
-                    Thread.yield();
-                } else {
-                    int idx = line.indexOf("--");
-                    if (idx != -1)
-                        command.append(line.substring(0, idx));
-                    else
-                        command.append(line);
-                    command.append(" ");
-                }
-            }
-            if (!autoCommit) {
-                conn.commit();
-            }
-        } catch (SQLException e) {
-            e.fillInStackTrace();
-            printlnError("Error executing: " + command);
-            printlnError(e);
-            throw e;
-        } catch (IOException e) {
-            e.fillInStackTrace();
-            printlnError("Error executing: " + command);
-            printlnError(e);
-            throw e;
-        } finally {
-            conn.rollback();
-            flush();
-        }
-    }
-
-    private String getDelimiter() {
-        return delimiter;
-    }
-
-    private void print(Object o) {
-        _logBuffer.append(o);
-    }
-
-    private void println(Object o) {
-        _logBuffer.append(o);
-        if (verbosity)
-            s_logger.debug(_logBuffer.toString());
-        _logBuffer = new StringBuffer();
-    }
-
-    private void printlnError(Object o) {
-        s_logger.error("" + o);
-    }
-
-    private void flush() {
-        if (_logBuffer.length() > 0) {
-            s_logger.debug(_logBuffer.toString());
-            _logBuffer = new StringBuffer();
-        }
-    }
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f5e5b39c/utils/src/com/cloud/utils/db/SearchBuilder.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/db/SearchBuilder.java b/utils/src/com/cloud/utils/db/SearchBuilder.java
deleted file mode 100755
index c177e20..0000000
--- a/utils/src/com/cloud/utils/db/SearchBuilder.java
+++ /dev/null
@@ -1,64 +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.db;
-
-import java.util.Map;
-
-/**
- * SearchBuilder is meant as a static query construct.  Often times in DAO code,
- * we write static sql that just assumes the database table does not change.
- * change by hand.  SearchBuilder is meant to replace that.  It provides load-time
- * 
- *   1. SearchBuilder is declared as final because it should not change after load time.
- *   2. search.entity().getHostId() allows you to declare which field you are searching
- *      on.  By doing this, we take advantage of the compiler to check that we
- *      are not searching on obsolete fields.  You should try to use this
- *      as much as possible as oppose to the addAndByField() and addOrByField() methods.
- *   3. Note that the same SearchBuilder is used to create multiple SearchCriteria.
- *      This is equivalent to clearing the parameters on PreparedStatement.  The
- *      multiple SearchCriteria does not interfere with each other.
- *   4. Note that the same field (getHostId()) was specified with two param
- *      names.  This is basically allowing you to reuse the same field in two
- *      parts of the search.
- * 
- * {@code
- * final SearchBuilder<UserVmVO> search = _userVmDao.createSearchBuilder();
- * final String param1 = "param1";
- * final String param2 = "param2";
- * search.addAnd(param1, search.entity().getHostId(), SearchCriteria.Op.NEQ);
- * search.addAnd(param2, search.entity().getHostId(), SearchCriteria.op.GT);
- * ...
- * SearchCriteria sc = search.create();
- * sc.setParameters(param1, 3);
- * sc.setParameters(param2, 1);
- * 
- * ...
- * 
- * SearchCriteria sc2 = search.create();
- * sc2.setParameters(param1, 4);
- * sc2.setParameters(param2, 1);
- * }
- * 
- * @param <T> VO object.
- */
-public class SearchBuilder<T> extends GenericSearchBuilder<T, T> {
-    
-    @SuppressWarnings("unchecked")
-    public SearchBuilder(T entity, Map<String, Attribute> attrs) {
-        super(entity, (Class<T>)entity.getClass(), attrs);
-    }
-}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f5e5b39c/utils/src/com/cloud/utils/db/SearchCriteria.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/db/SearchCriteria.java b/utils/src/com/cloud/utils/db/SearchCriteria.java
deleted file mode 100755
index 22bccd3..0000000
--- a/utils/src/com/cloud/utils/db/SearchCriteria.java
+++ /dev/null
@@ -1,364 +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.db;
-
-import java.lang.reflect.Field;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import com.cloud.utils.Pair;
-import com.cloud.utils.db.GenericSearchBuilder.Condition;
-import com.cloud.utils.db.GenericSearchBuilder.Select;
-
-/**
- * big joins or high performance searches, it is much better to
- */
-public class SearchCriteria<K> {
-    public enum Op {
-        GT(" > ? ", 1),
-        GTEQ(" >= ? ", 1),
-        LT(" < ? ", 1),
-        LTEQ(" <= ? ", 1),
-        EQ(" = ? ", 1),
-        NEQ(" != ? ", 1),
-        BETWEEN(" BETWEEN ? AND ? ", 2),
-        NBETWEEN(" NOT BETWEEN ? AND ? ", 2),
-        IN(" IN () ", -1),
-        NOTIN(" NOT IN () ", -1),
-        LIKE(" LIKE ? ", 1),
-        NLIKE(" NOT LIKE ? ", 1),
-        NIN(" NOT IN () ", -1),
-        NULL(" IS NULL ", 0),
-        NNULL(" IS NOT NULL ", 0),
-        SC(" () ", 1),
-        TEXT("  () ", 1),
-        RP("", 0),
-        AND(" AND ", 0),
-        OR(" OR ", 0),
-        NOT(" NOT ", 0);
-
-        private final String op;
-        int params;
-        Op(String op, int params) {
-            this.op = op;
-            this.params = params;
-        }
-
-        @Override
-        public String toString() {
-            return op;
-        }
-
-        public int getParams() {
-            return params;
-        }
-    }
-
-    public enum Func {
-        NATIVE("@", 1),
-        MAX("MAX(@)", 1),
-        MIN("MIN(@)", 1),
-        FIRST("FIRST(@)", 1),
-        LAST("LAST(@)", 1),
-        SUM("SUM(@)", 1),
-        COUNT("COUNT(@)", 1),
-        DISTINCT("DISTINCT(@)", 1);
-
-        private String func;
-        private int count;
-
-        Func(String func, int params) {
-            this.func = func;
-            this.count = params;
-        }
-
-        @Override
-        public String toString() {
-            return func;
-        }
-
-        public int getCount() {
-            return count;
-        }
-    }
-
-    public enum SelectType {
-        Fields,
-        Entity,
-        Single,
-        Result
-    }
-
-    private final Map<String, Attribute> _attrs;
-    private final ArrayList<Condition> _conditions;
-    private ArrayList<Condition> _additionals = null;
-    private HashMap<String, Object[]> _params = new HashMap<String, Object[]>();
-    private int _counter;
-    private HashMap<String, JoinBuilder<SearchCriteria<?>>> _joins;
-    private final ArrayList<Select> _selects;
-    private final GroupBy<?, K> _groupBy;
-    private final List<Object> _groupByValues;
-    private final Class<K> _resultType;
-    private final SelectType _selectType;
-
-    protected SearchCriteria(final Map<String, Attribute> attrs, ArrayList<GenericSearchBuilder.Condition> conditions, ArrayList<Select> selects, SelectType selectType, Class<K> resultType, HashMap<String, Object[]> params) {
-        this._attrs = attrs;
-        this._conditions = conditions;
-        this._selects = selects;
-        this._selectType = selectType;
-        this._resultType = resultType;
-        this._params = params;
-        this._additionals = new ArrayList<Condition>();
-        this._counter = 0;
-        this._joins = null;
-        this._groupBy = null;
-        this._groupByValues = null;
-    }
-
-    protected SearchCriteria(GenericSearchBuilder<?, K> sb) {
-        this._attrs = sb._attrs;
-        this._conditions = sb._conditions;
-        this._additionals = new ArrayList<Condition>();
-        this._counter = 0;
-        this._joins = null;
-        if (sb._joins != null) {
-            _joins = new HashMap<String, JoinBuilder<SearchCriteria<?>>>(sb._joins.size());
-            for (Map.Entry<String, JoinBuilder<GenericSearchBuilder<?, ?>>> entry : sb._joins.entrySet()) {
-                JoinBuilder<GenericSearchBuilder<?, ?>> value =  entry.getValue();
-                _joins.put(entry.getKey(), new JoinBuilder<SearchCriteria<?>>(value.getT().create(),value.getFirstAttribute(), value.getSecondAttribute(), value.getType()));
-            }
-        }
-        _selects = sb._selects;
-        _groupBy = sb._groupBy;
-        if (_groupBy != null) {
-            _groupByValues = new ArrayList<Object>();
-        } else {
-            _groupByValues = null;
-        }
-        _resultType = sb._resultType;
-        _selectType = sb._selectType;
-    }
-
-    public SelectType getSelectType() {
-        return _selectType;
-    }
-
-    public void getSelect(StringBuilder str, int insertAt) {
-        if (_selects == null || _selects.size() == 0) {
-            return;
-        }
-
-        for (Select select : _selects) {
-            String func = select.func.toString() + ",";
-            if (select.attr == null) {
-                func = func.replace("@", "*");
-            } else {
-                func = func.replace("@", select.attr.table + "." + select.attr.columnName);
-            }
-            str.insert(insertAt, func);
-            insertAt += func.length();
-            if (select.field == null) {
-                break;
-            }
-        }
-
-        str.delete(insertAt - 1, insertAt);
-    }
-
-    public List<Field> getSelectFields() {
-        List<Field> fields = new ArrayList<Field>(_selects.size());
-        for (Select select : _selects) {
-            fields.add(select.field);
-        }
-
-        return fields;
-    }
-
-    public void setParameters(String conditionName, Object... params) {
-        assert _conditions.contains(new Condition(conditionName)) || _additionals.contains(new Condition(conditionName)) : "Couldn't find " + conditionName;
-        _params.put(conditionName, params);
-    }
-
-    public boolean isSelectAll() {
-        return _selects == null || _selects.size() == 0;
-    }
-
-    protected JoinBuilder<SearchCriteria<?>> findJoin(Map<String, JoinBuilder<SearchCriteria<?>>> jbmap, String joinName) {
-    	JoinBuilder<SearchCriteria<?>> jb = jbmap.get(joinName);
-    	if (jb != null) {
-    		return jb;
-    	}
-    	
-    	for (JoinBuilder<SearchCriteria<?>> j2 : jbmap.values()) {
-    		SearchCriteria<?> sc = j2.getT();
-    		if(sc._joins != null)
-    		    jb = findJoin(sc._joins, joinName);
-    		if (jb != null) {
-    			return jb;
-    		}
-    	}
-    	
-    	assert (false) : "Unable to find a join by the name " + joinName;
-    	return null;
-    }
-
-    public void setJoinParameters(String joinName, String conditionName, Object... params) {
-        JoinBuilder<SearchCriteria<?>> join = findJoin(_joins, joinName);
-        assert (join != null) : "Incorrect join name specified: " + joinName;
-        join.getT().setParameters(conditionName, params);
-
-    }
-
-    public void addJoinAnd(String joinName, String field, Op op, Object... values) {
-        JoinBuilder<SearchCriteria<?>> join = _joins.get(joinName);
-        assert (join != null) : "Incorrect join name specified: " + joinName;
-        join.getT().addAnd(field, op, values);
-    }
-
-    public void addJoinOr(String joinName, String field, Op op, Object... values) {
-        JoinBuilder<SearchCriteria<?>> join = _joins.get(joinName);
-        assert (join != null) : "Incorrect join name specified: " + joinName;
-        join.getT().addOr(field, op, values);
-    }
-
-    public SearchCriteria<?> getJoin(String joinName) {
-        return _joins.get(joinName).getT();
-    }
-
-    public Pair<GroupBy<?, ?>, List<Object>> getGroupBy() {
-        return _groupBy == null ? null : new Pair<GroupBy<?, ?>, List<Object>>(_groupBy, _groupByValues);
-    }
-
-    public void setGroupByValues(Object... values) {
-        for (Object value : values) {
-            _groupByValues.add(value);
-        }
-    }
-
-    public Class<K> getResultType() {
-        return _resultType;
-    }
-
-    public void addAnd(String field, Op op, Object... values) {
-        String name = Integer.toString(_counter++);
-        addCondition(name, " AND ", field, op);
-        setParameters(name, values);
-    }
-
-    public void addAnd(Attribute attr, Op op, Object... values) {
-        String name = Integer.toString(_counter++);
-        addCondition(name, " AND ", attr, op);
-        setParameters(name, values);
-    }
-
-    public void addOr(String field, Op op, Object... values) {
-        String name = Integer.toString(_counter++);
-        addCondition(name, " OR ", field, op);
-        setParameters(name, values);
-    }
-
-    public void addOr(Attribute attr, Op op, Object... values) {
-        String name = Integer.toString(_counter++);
-        addCondition(name, " OR ", attr, op);
-        setParameters(name, values);
-    }
-
-    protected void addCondition(String conditionName, String cond, String fieldName, Op op) {
-        Attribute attr = _attrs.get(fieldName);
-        assert attr != null : "Unable to find field: " + fieldName;
-        addCondition(conditionName, cond, attr, op);
-    }
-
-    protected void addCondition(String conditionName, String cond, Attribute attr, Op op) {
-        Condition condition = new Condition(conditionName, /*(_conditions.size() + _additionals.size()) == 0 ? "" : */cond, attr, op);
-        _additionals.add(condition);
-    }
-
-    public String getWhereClause() {
-        StringBuilder sql = new StringBuilder();
-        int i = 0;
-        for (Condition condition : _conditions) {
-            if (condition.isPreset()) {
-                _params.put(condition.name, condition.presets);
-            }
-            Object[] params = _params.get(condition.name);
-            if ((condition.op == null || condition.op.params == 0) || (params != null)) {
-                condition.toSql(sql, params, i++);
-            }
-        }
-
-        for (Condition condition : _additionals) {
-            if (condition.isPreset()) {
-                _params.put(condition.name, condition.presets);
-            }
-            Object[] params = _params.get(condition.name);
-            if ((condition.op.params == 0) || (params != null)) {
-                condition.toSql(sql, params, i++);
-            }
-        }
-
-        return sql.toString();
-    }
-
-    public List<Pair<Attribute, Object>> getValues() {
-        ArrayList<Pair<Attribute, Object>> params = new ArrayList<Pair<Attribute, Object>>(_params.size());
-        for (Condition condition : _conditions) {
-            Object[] objs = _params.get(condition.name);
-            if (condition.op != null && condition.op.params != 0 && objs != null) {
-                getParams(params, condition, objs);
-            }
-        }
-
-        for (Condition condition : _additionals) {
-            Object[] objs = _params.get(condition.name);
-            if ((condition.op.params == 0) || (objs != null)) {
-                getParams(params, condition, objs);
-            }
-        }
-
-        return params;
-    }
-
-    public Collection<JoinBuilder<SearchCriteria<?>>> getJoins() {
-        return _joins != null ? _joins.values() : null;
-    }
-
-    private void getParams(ArrayList<Pair<Attribute, Object>> params, Condition condition, Object[] objs) {
-        if (condition.op == Op.SC) {
-            assert (objs != null && objs.length > 0) : " Where's your search criteria object? " + condition.name;
-            params.addAll(((SearchCriteria<?>)objs[0]).getValues());
-            return;
-        }
-
-        if (objs != null && objs.length > 0) {
-            for (Object obj : objs) {
-                if ((condition.op != Op.EQ && condition.op != Op.NEQ) || (obj != null)) {
-                    params.add(new Pair<Attribute, Object>(condition.attr, obj));
-                }
-            }
-        }
-    }
-
-    public Pair<String, ArrayList<Object>> toSql() {
-        StringBuilder sql = new StringBuilder();
-
-        return new Pair<String, ArrayList<Object>>(sql.toString(), null);
-    }
-}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f5e5b39c/utils/src/com/cloud/utils/db/SearchCriteria2.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/db/SearchCriteria2.java b/utils/src/com/cloud/utils/db/SearchCriteria2.java
deleted file mode 100755
index 5875106..0000000
--- a/utils/src/com/cloud/utils/db/SearchCriteria2.java
+++ /dev/null
@@ -1,213 +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.db;
-
-import java.io.Serializable;
-import java.lang.reflect.Field;
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
-
-import javax.persistence.Transient;
-
-import net.sf.cglib.proxy.Factory;
-import net.sf.cglib.proxy.MethodInterceptor;
-import net.sf.cglib.proxy.MethodProxy;
-
-import com.cloud.utils.db.GenericSearchBuilder.Condition;
-import com.cloud.utils.db.GenericSearchBuilder.Select;
-import com.cloud.utils.db.SearchCriteria.Func;
-import com.cloud.utils.db.SearchCriteria.Op;
-import com.cloud.utils.db.SearchCriteria.SelectType;
-
-public class SearchCriteria2<T, K> implements SearchCriteriaService<T, K>, MethodInterceptor{
-	GenericDao<? extends Serializable, ? extends Serializable> _dao;
-	final protected Map<String, Attribute> _attrs;
-	protected ArrayList<Attribute> _specifiedAttrs;
-	protected T _entity;
-	protected ArrayList<GenericSearchBuilder.Condition> _conditions;
-	protected ArrayList<Select> _selects;
-	private final HashMap<String, Object[]> _params = new HashMap<String, Object[]>();
-	protected Class<K> _resultType;
-    protected SelectType _selectType;
-    protected Class<T> _entityBeanType;
-	
-	protected SearchCriteria2(T entity, Class<K> resultType, final Map<String, Attribute> attrs, GenericDao<? extends Serializable, ? extends Serializable> dao) {
-		_entityBeanType = (Class<T>)entity.getClass();
-		_dao = dao;
-		_resultType = resultType;
-		_attrs = attrs;
-		_entity = entity;
-		_conditions = new ArrayList<Condition>();
-		_specifiedAttrs = new ArrayList<Attribute>();
-    }
-	
-	static public <T, K> SearchCriteria2<T, K> create(Class<T> entityType, Class<K> resultType) {
-		GenericDao<? extends Serializable, ? extends Serializable> dao = (GenericDao<? extends Serializable, ? extends Serializable>)GenericDaoBase.getDao(entityType);
-		assert dao != null : "Can not find DAO for " + entityType.getName();
-		SearchCriteria2<T, K> sc = dao.createSearchCriteria2(resultType);
-		return sc;
-	}
-	
-	static public <T, K> SearchCriteria2<T, K> create(Class<T> entityType) {
-		GenericDao<? extends Serializable, ? extends Serializable> dao = (GenericDao<? extends Serializable, ? extends Serializable>)GenericDaoBase.getDao(entityType);
-		assert dao != null : "Can not find DAO for " + entityType.getName();
-		SearchCriteria2<T, K> sc = dao.createSearchCriteria2();
-		return sc;
-	}
-	
-	@Override
-	public void selectField(Object... useless) {
-        assert _entity != null : "SearchBuilder cannot be modified once it has been setup";
-        assert _specifiedAttrs.size() > 0 : "You didn't specify any attributes";
-   
-        if (_selects == null) {
-            _selects = new ArrayList<Select>();
-        }
-        
-        for (Attribute attr : _specifiedAttrs) {
-            Field field = null;
-            try {
-                field = _resultType.getDeclaredField(attr.field.getName());
-                field.setAccessible(true);
-            } catch (SecurityException e) {
-            } catch (NoSuchFieldException e) {
-            }
-            _selects.add(new Select(Func.NATIVE, attr, field, null));
-        }
-        
-        _specifiedAttrs.clear();
-    }
-	
-    private void constructCondition(String conditionName, String cond, Attribute attr, Op op) {
-        assert _entity != null : "SearchBuilder cannot be modified once it has been setup";
-        assert op == null || _specifiedAttrs.size() == 1 : "You didn't select the attribute.";
-        assert op != Op.SC : "Call join";
-        
-        GenericSearchBuilder.Condition condition = new GenericSearchBuilder.Condition(conditionName, cond, attr, op);
-        _conditions.add(condition);
-        _specifiedAttrs.clear();
-    }
-    
-    private void setParameters(String conditionName, Object... params) {
-        assert _conditions.contains(new Condition(conditionName)) : "Couldn't find " + conditionName;
-        _params.put(conditionName, params);
-    }
-    
-	@Override
-	public void addAnd(Object useless, Op op, Object...values) {
-		String uuid = UUID.randomUUID().toString();
-		constructCondition(uuid, " AND ", _specifiedAttrs.get(0), op);
-		setParameters(uuid, values);
-	}
-	
-	@Override
-	public List<K> list() {
-		done();
-		SearchCriteria sc1 = createSearchCriteria();
-		if (isSelectAll()) {
-			return (List<K>)_dao.search(sc1, null);
-		} else {
-			return (List<K>)_dao.customSearch(sc1, null);
-		}
-	}
-	
-	private boolean isSelectAll() {
-        return _selects == null || _selects.size() == 0;
-    }
-	
-	@Override
-	public T getEntity() {
-		return (T) _entity; 
-	}
-
-	private SearchCriteria<K> createSearchCriteria() {
-		return new SearchCriteria<K>(_attrs, _conditions, _selects, _selectType, _resultType, _params);
-	}
-	
-    private void set(String name) {
-        Attribute attr = _attrs.get(name);
-        assert (attr != null) : "Searching for a field that's not there: " + name;
-        _specifiedAttrs.add(attr);
-    }
-    
-    private void done() {
-        if (_entity != null) {
-            Factory factory = (Factory)_entity;
-            factory.setCallback(0, null);
-            _entity = null;
-        }
-                
-        if (_selects == null || _selects.size() == 0) {
-            _selectType = SelectType.Entity;
-            assert _entityBeanType.equals(_resultType) : "Expecting " + _entityBeanType + " because you didn't specify any selects but instead got " + _resultType;
-            return;
-        }
-        
-        for (Select select : _selects) {
-            if (select.field == null) {
-                assert (_selects.size() == 1) : "You didn't specify any fields to put the result in but you're specifying more than one select so where should I put the selects?";
-                _selectType = SelectType.Single;
-                return;
-            }
-            if (select.func != null) {
-                _selectType = SelectType.Result;
-                return;
-            }
-        }
-        
-        _selectType = SelectType.Fields;
-    }
-    
-	@Override
-	public Object intercept(Object object, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
-		String name = method.getName();
-		if (method.getAnnotation(Transient.class) == null) {
-			if (name.startsWith("get")) {
-				String fieldName = Character.toLowerCase(name.charAt(3)) + name.substring(4);
-				set(fieldName);
-				return null;
-			} else if (name.startsWith("is")) {
-				String fieldName = Character.toLowerCase(name.charAt(2)) + name.substring(3);
-				set(fieldName);
-				return null;
-			} else {
-				name = name.toLowerCase();
-				for (String fieldName : _attrs.keySet()) {
-					if (name.endsWith(fieldName.toLowerCase())) {
-						set(fieldName);
-						return null;
-					}
-				}
-				assert false : "Perhaps you need to make the method start with get or is?";
-			}
-		}
-        return methodProxy.invokeSuper(object, args);
-    }
-
-	@Override
-    public <K> K find() {
-		assert isSelectAll() : "find doesn't support select search";
-		done();
-		SearchCriteria sc1 = createSearchCriteria();
-		return (K)_dao.findOneBy(sc1);
-    }
-
-}