db-torque-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From tfisc...@apache.org
Subject svn commit: r1103332 - in /db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/util: Criteria.java SummaryHelper.java
Date Sun, 15 May 2011 11:48:31 GMT
Author: tfischer
Date: Sun May 15 11:48:31 2011
New Revision: 1103332

URL: http://svn.apache.org/viewvc?rev=1103332&view=rev
Log:
TORQUE-150: Let Criteria not inherit from Hashtable any more but retain previous functionality

Modified:
    db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/util/Criteria.java
    db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/util/SummaryHelper.java

Modified: db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/util/Criteria.java
URL: http://svn.apache.org/viewvc/db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/util/Criteria.java?rev=1103332&r1=1103331&r2=1103332&view=diff
==============================================================================
--- db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/util/Criteria.java
(original)
+++ db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/util/Criteria.java
Sun May 15 11:48:31 2011
@@ -26,14 +26,15 @@ import java.io.Serializable;
 import java.math.BigDecimal;
 import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.Collection;
 import java.util.Collections;
 import java.util.GregorianCalendar;
 import java.util.HashMap;
-import java.util.Hashtable;
 import java.util.Iterator;
 import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.Set;
 
 import org.apache.commons.lang.ObjectUtils;
 import org.apache.commons.logging.Log;
@@ -44,12 +45,7 @@ import org.apache.torque.adapter.DB;
 import org.apache.torque.om.ObjectKey;
 
 /**
- * This is a utility class that is used for retrieving different types
- * of values from a hashtable based on a simple name string.  This
- * class is meant to minimize the amount of casting that needs to be
- * done when working with Hashtables.
- *
- * NOTE: other methods will be added as needed and as time permits.
+ * Encapsulates conditions to access rows in database tables.
  *
  * @author <a href="mailto:frank.kim@clearink.com">Frank Y. Kim</a>
  * @author <a href="mailto:jmcnally@collab.net">John D. McNally</a>
@@ -63,7 +59,7 @@ import org.apache.torque.om.ObjectKey;
  * @author <a href="mailto:tv@apache.org">Thomas Vandahl</a>
  * @version $Id$
  */
-public class Criteria extends Hashtable
+public class Criteria implements Serializable
 {
     /** Serial version. */
     private static final long serialVersionUID = -9001666575933085601L;
@@ -146,10 +142,13 @@ public class Criteria extends Hashtable
     /** &quot;INNER JOIN&quot; SQL statement */
     public static final SqlEnum INNER_JOIN = SqlEnum.INNER_JOIN;
 
-    private static final int DEFAULT_CAPACITY = 10;
-
+    /** Whether to ignore the case in all String conditions in the criteria. */
     private boolean ignoreCase = false;
+
+    /** Whether the result must be a single record. */
     private boolean singleRecord = false;
+
+    /** TODO Currently unused. */
     private boolean cascade = false;
 
     /** List of modifiers like DISTICT. */
@@ -158,14 +157,19 @@ public class Criteria extends Hashtable
     /** List of all columns to select. */
     private UniqueList<String> selectColumns = new UniqueList<String>();
 
-    /** All "order by" clauses, containg the order ASC or DESC. */
+    /** All "order by" clauses, containing the order ASC or DESC. */
     private UniqueList<String> orderByColumns = new UniqueList<String>();
 
     /** The names of columns to add to a groupoBy clause */
     private UniqueList<String> groupByColumns = new UniqueList<String>();
 
+    /** The having clause in a query. */
     private Criterion having = null;
 
+    /** The criterion objects, keyed by the column name. */
+    private Map<String, Criteria.Criterion> criterionMap
+            = new HashMap<String, Criteria.Criterion>();
+
     /**
      * Maps column alias names to the real column names.
      * The key of the map is the alias and the value is the real name
@@ -208,17 +212,19 @@ public class Criteria extends Hashtable
      */
     public Criteria()
     {
-        this(DEFAULT_CAPACITY);
+        this(Torque.getDefaultDB());
     }
 
     /**
      * Creates a new instance with the specified capacity.
      *
      * @param initialCapacity An int.
+     *
+     * @deprecated initialCapacity is disregarded
      */
     public Criteria(int initialCapacity)
     {
-        this(Torque.getDefaultDB(), initialCapacity);
+        this(Torque.getDefaultDB());
     }
 
     /**
@@ -229,7 +235,8 @@ public class Criteria extends Hashtable
      */
     public Criteria(String dbName)
     {
-        this(dbName, DEFAULT_CAPACITY);
+        this.dbName = dbName;
+        this.originalDbName = dbName;
     }
 
     /**
@@ -238,10 +245,11 @@ public class Criteria extends Hashtable
      *
      * @param dbName          The dabase name.
      * @param initialCapacity The initial capacity.
+     *
+     * @deprecated initialCapacity is disregarded
      */
     public Criteria(String dbName, int initialCapacity)
     {
-        super(initialCapacity);
         this.dbName = dbName;
         this.originalDbName = dbName;
     }
@@ -253,7 +261,7 @@ public class Criteria extends Hashtable
      */
     public void clear()
     {
-        super.clear();
+        criterionMap.clear();
         ignoreCase = false;
         singleRecord = false;
         cascade = false;
@@ -344,10 +352,14 @@ public class Criteria extends Hashtable
      * @param table The name of the table.
      * @param column The name of the column.
      * @return True if this Criteria Object contain the specified key.
+     *
+     * @deprecated this method does not check in all cases whether a matching
+     *             criterion is contained (e.g. if the criterion has been added
+     *             manually with another key).
      */
     public boolean containsKey(String table, String column)
     {
-        return containsKey(table + '.' + column);
+        return criterionMap.containsKey(table + '.' + column);
     }
 
     /**
@@ -405,7 +417,7 @@ public class Criteria extends Hashtable
      */
     public Criterion getCriterion(String column)
     {
-        return (Criterion) super.get(column);
+        return criterionMap.get(column);
     }
 
     /**
@@ -472,7 +484,7 @@ public class Criteria extends Hashtable
      */
     public Criteria add(Criterion c)
     {
-        super.put(c.getFullyQualifiedColumnName(), c);
+        criterionMap.put(c.getFullyQualifiedColumnName(), c);
         return this;
     }
 
@@ -786,8 +798,10 @@ public class Criteria extends Hashtable
      * Convenience method to return a List.
      *
      * @param name A String with the name of the key.
+     *
      * @return A List with the value of object at key.
      */
+    @SuppressWarnings("unchecked")
     public List<Object> getList(String name)
     {
         return (List<Object>) getCriterion(name).getValue();
@@ -861,40 +875,69 @@ public class Criteria extends Hashtable
     }
 
     /**
-     * Overrides Hashtable get, so that the value placed in the
-     * Criterion is returned instead of the Criterion.
+     * Returns the value in the top-level criterion for the given key.
+     *
+     * @param key the key for the criterion.
      *
-     * @param key An Object.
-     * @return An Object.
+     * @return the value of the criterion.
+     *
+     * @throws NullPointerException if no Criterion is stored under the key.
+     *
+     * @deprecated this method only works if a criterion exists for the key.
      */
-    public Object get(Object key)
+    public Object get(String key)
     {
-        return getValue((String) key);
+        return getValue(key);
     }
 
     /**
-     * Overrides Hashtable put, so that this object is returned
-     * instead of the value previously in the Criteria object.
-     * The reason is so that it more closely matches the behavior
-     * of the add() methods. If you want to get the previous value
-     * then you should first Criteria.get() it yourself. Note, if
-     * you attempt to pass in an Object that is not a String, it will
-     * throw a NPE. The reason for this is that none of the add()
-     * methods support adding anything other than a String as a key.
+     * Returns whether there are any criterions in this criteria.
+     *
+     * @return true if there are criterions, false otherwise.
+     */
+    public boolean isEmpty()
+    {
+        return criterionMap.isEmpty();
+    }
+
+    /**
+     * Returns how many top-level criterions are in this criteria.
+     *
+     * @return the number of op-level criterions.
+     *
+     * @deprecated this method counts only top-level criterions, not all.
+     */
+    public int size()
+    {
+        return criterionMap.size();
+    }
+
+    /**
+     * Returns all the top-level Criterions in this criteria
+     * (but not the chained Criterions).
+     *
+     * @return all top-level Criterions, not null.
+     */
+    public Collection<Criterion> values()
+    {
+        return criterionMap.values();
+    }
+
+    /**
+     * Equivalent to add(key, value).
+     *
+     * @param key the column name
+     * @param value An Object to which the column should be equal.
      *
-     * @param key An Object. Must be instanceof String!
-     * @param value An Object.
-     * @throws NullPointerException if key != String or key/value is null.
      * @return Instance of self.
+     *
+     * @throws NullPointerException if key is null.
+     *
+     * @deprecated use add(String, Object) instead
      */
-    public Object put(Object key, Object value)
+    public Object put(String key, Object value)
     {
-        if (!(key instanceof String))
-        {
-            throw new NullPointerException(
-                    "Criteria: Key must be a String object.");
-        }
-        return add((String) key, value);
+        return add(key, value);
     }
 
     /**
@@ -902,49 +945,17 @@ public class Criteria extends Hashtable
      * These mappings will replace any mappings that this Criteria had for any
      * of the keys currently in the specified Map.
      *
-     * if the map was another Criteria, its attributes are copied to this
-     * Criteria, overwriting previous settings.
-     *
-     * @param t Mappings to be stored in this map.
+     * @param t Objects to be stored in this criteria.
      */
-    public synchronized void putAll(Map t)
+    public synchronized void putAll(Map<String, Criterion> t)
     {
-        Iterator i = t.entrySet().iterator();
+        Iterator<Map.Entry<String, Criterion>> i = t.entrySet().iterator();
         while (i.hasNext())
         {
-            Map.Entry e = (Map.Entry) i.next();
-            Object val = e.getValue();
-            if (val instanceof Criteria.Criterion)
-            {
-                super.put(e.getKey(), val);
-            }
-            else
-            {
-                put(e.getKey(), val);
-            }
-        }
-        if (t instanceof Criteria)
-        {
-            Criteria c = (Criteria) t;
-            this.joins = c.joins;
+            Map.Entry<String, Criterion> e = i.next();
+            Criterion val = e.getValue();
+            criterionMap.put(e.getKey(), val);
         }
-        /* this would make a copy, not included
-           but might want to use some of it.
-           if (t instanceof Criteria)
-           {
-           Criteria c = (Criteria)t;
-           this.ignoreCase = c.ignoreCase;
-           this.singleRecord = c.singleRecord;
-           this.cascade = c.cascade;
-           this.selectModifiers = c.selectModifiers;
-           this.selectColumns = c.selectColumns;
-           this.orderByColumns = c.orderByColumns;
-           this.dbName = c.dbName;
-           this.limit = c.limit;
-           this.offset = c.offset;
-           this.aliases = c.aliases;
-           }
-        */
     }
 
     /**
@@ -969,7 +980,7 @@ public class Criteria extends Hashtable
      *
      * @return A modified Criteria object.
      */
-    public Criteria add (String column, Object value)
+    public Criteria add(String column, Object value)
     {
         add(column, value, EQUAL);
         return this;
@@ -1001,7 +1012,7 @@ public class Criteria extends Hashtable
      */
     public Criteria add(String column, Object value, SqlEnum comparison)
     {
-        super.put(column, new Criterion(column, value, comparison));
+        criterionMap.put(column, new Criterion(column, value, comparison));
         return this;
     }
 
@@ -1058,12 +1069,7 @@ public class Criteria extends Hashtable
             Object value,
             SqlEnum comparison)
     {
-        StringBuffer sb = new StringBuffer(table.length()
-                + column.length() + 1);
-        sb.append(table);
-        sb.append('.');
-        sb.append(column);
-        super.put(sb.toString(),
+        criterionMap.put(table + '.' + column,
                 new Criterion(table, column, value, comparison));
         return this;
     }
@@ -1376,28 +1382,6 @@ public class Criteria extends Hashtable
     }
 
     /**
-     * get one side of the set of possible joins.  This method is meant to
-     * be called by BasePeer.
-     *
-     * @deprecated This method is no longer used by BasePeer.
-     */
-    public List getJoinL()
-    {
-        throw new RuntimeException("getJoinL() in Criteria is no longer supported!");
-    }
-
-    /**
-     * get one side of the set of possible joins.  This method is meant to
-     * be called by BasePeer.
-     *
-     * @deprecated This method is no longer used by BasePeer.
-     */
-    public List getJoinR()
-    {
-        throw new RuntimeException("getJoinL() in Criteria is no longer supported!");
-    }
-
-    /**
      * Adds an 'IN' clause with the criteria supplied as an Object
      * array.  For example:
      *
@@ -1774,16 +1758,16 @@ public class Criteria extends Hashtable
      * Remove an object from the criteria.
      *
      * @param key A String with the key to be removed.
-     * @return The removed object.
+     * @return The value of the removed criterion, or null.
      */
     public Object remove(String key)
     {
-        Object foo = super.remove(key);
-        if (foo instanceof Criterion)
+        Criterion removed = criterionMap.remove(key);
+        if (removed == null)
         {
-            return ((Criterion) foo).getValue();
+            return null;
         }
-        return foo;
+        return removed.getValue();
     }
 
     /**
@@ -1799,7 +1783,7 @@ public class Criteria extends Hashtable
         {
             String key = (String) it.next();
             sb.append(key).append("<=>")
-                    .append(super.get(key).toString()).append(":  ");
+                    .append(criterionMap.get(key)).append(":  ");
         }
 
         try
@@ -1816,60 +1800,78 @@ public class Criteria extends Hashtable
     }
 
     /**
-     * This method checks another Criteria to see if they contain
-     * the same attributes and hashtable entries.
+     * Returns all keys in the Criterion map.
+     *
+     * @return all keys, not null.
      */
-    public boolean equals(Object crit)
+    public Set<String> keySet()
     {
-        boolean isEquiv = false;
-        if (crit == null || !(crit instanceof Criteria))
+        return criterionMap.keySet();
+    }
+
+    /**
+     * Checks whether an object is equal to this Criteria.
+     * This is the case if the other object is also a Criteria and has
+     * the same attributes and criterions.
+     * 
+     * @param object the other object to check, can be null.
+     * 
+     * @return true if the object is equal to this Criteria, false otherwise.
+     */
+    @Override
+    public boolean equals(Object object)
+    {
+        if (object == null)
         {
-            isEquiv = false;
-        }
-        else if (this == crit)
-        {
-            isEquiv = true;
-        }
-        else if (this.size() == ((Criteria) crit).size())
-        {
-            Criteria criteria = (Criteria) crit;
-            if (this.offset == criteria.getOffset()
-                    && this.limit == criteria.getLimit()
-                    && ignoreCase == criteria.isIgnoreCase()
-                    && singleRecord == criteria.isSingleRecord()
-                    && cascade == criteria.isCascade()
-                    && dbName.equals(criteria.getDbName())
-                    && selectModifiers.equals(criteria.getSelectModifiers())
-                    && selectColumns.equals(criteria.getSelectColumns())
-                    && orderByColumns.equals(criteria.getOrderByColumns())
-                    && aliases.equals(criteria.getAliases())
-                    && asColumns.equals(criteria.getAsColumns())
-                    && joins.equals(criteria.getJoins())
-                )
+            return false;
+        }
+        if (this == object)
+        {
+            return true;
+        }
+        if (object.getClass() != Criteria.class)
+        {
+            return false;
+        }
+        Criteria criteria = (Criteria) object;
+        if (criterionMap.size() !=  criteria.criterionMap.size())
+        {
+            return false;
+        }
+        if (this.offset != criteria.getOffset()
+                || this.limit != criteria.getLimit()
+                || ignoreCase != criteria.isIgnoreCase()
+                || singleRecord != criteria.isSingleRecord()
+                || cascade != criteria.isCascade()
+                || !dbName.equals(criteria.getDbName())
+                || !selectModifiers.equals(criteria.getSelectModifiers())
+                || !selectColumns.equals(criteria.getSelectColumns())
+                || !orderByColumns.equals(criteria.getOrderByColumns())
+                || !aliases.equals(criteria.getAliases())
+                || !asColumns.equals(criteria.getAsColumns())
+                || !joins.equals(criteria.getJoins())
+            )
+        {
+            return false;
+        }
+        for (Iterator<?> it = criteria.keySet().iterator(); it.hasNext();)
+        {
+            String key = (String) it.next();
+            if (criterionMap.containsKey(key))
             {
-                isEquiv = true;
-                for (Iterator<?> it = criteria.keySet().iterator(); it.hasNext();)
+                Criterion a = this.getCriterion(key);
+                Criterion b = criteria.getCriterion(key);
+                if (!a.equals(b))
                 {
-                    String key = (String) it.next();
-                    if (this.containsKey(key))
-                    {
-                        Criterion a = this.getCriterion(key);
-                        Criterion b = criteria.getCriterion(key);
-                        if (!a.equals(b))
-                        {
-                            isEquiv = false;
-                            break;
-                        }
-                    }
-                    else
-                    {
-                        isEquiv = false;
-                        break;
-                    }
+                    return false;
                 }
             }
+            else
+            {
+                return false;
+            }
         }
-        return isEquiv;
+        return true;
     }
 
     /**
@@ -2018,7 +2020,7 @@ public class Criteria extends Hashtable
 
         if (oc == null)
         {
-            super.put(column, nc);
+            criterionMap.put(column, nc);
         }
         else
         {
@@ -2077,18 +2079,12 @@ public class Criteria extends Hashtable
     public Criteria and(String table, String column, Object value,
             SqlEnum comparison)
     {
-        StringBuffer sb = new StringBuffer(table.length()
-                + column.length() + 1);
-        sb.append(table);
-        sb.append('.');
-        sb.append(column);
-
         Criterion oc = getCriterion(table, column);
         Criterion nc = new Criterion(table, column, value, comparison);
 
         if (oc == null)
         {
-            super.put(sb.toString(), nc);
+            criterionMap.put(table + '.' + column, nc);
         }
         else
         {
@@ -2583,7 +2579,7 @@ public class Criteria extends Hashtable
 
         if (oc == null)
         {
-            super.put(column, nc);
+            criterionMap.put(column, nc);
         }
         else
         {
@@ -2641,16 +2637,11 @@ public class Criteria extends Hashtable
     public Criteria or(String table, String column, Object value,
             SqlEnum comparison)
     {
-        StringBuffer sb = new StringBuffer(table.length() + column.length() + 1);
-        sb.append(table);
-        sb.append('.');
-        sb.append(column);
-
         Criterion oc = getCriterion(table, column);
         Criterion nc = new Criterion(table, column, value, comparison);
         if (oc == null)
         {
-            super.put(sb.toString(), nc);
+            criterionMap.put(table + '.' + column, nc);
         }
         else
         {
@@ -3094,18 +3085,6 @@ public class Criteria extends Hashtable
     {
         s.defaultReadObject();
 
-        // Criteria.put() differs somewhat from Hashtable.put().
-        // This necessitates some corrective behavior upon deserialization.
-        for (Iterator<?> iter = keySet().iterator(); iter.hasNext();)
-        {
-            Object key = iter.next();
-            Object value = get(key);
-            if (value instanceof Criteria.Criterion)
-            {
-                super.put(key, value);
-            }
-        }
-
         // Joins need to be deserialized manually.
         this.joins = new ArrayList<Join>(3);
 
@@ -3138,7 +3117,10 @@ public class Criteria extends Hashtable
         /** Serial version. */
         private static final long serialVersionUID = 7157097965404611710L;
 
+        /** Constant for thze operator " AND ". */
         public static final String AND = " AND ";
+
+        /** Constant for thze operator " OR ". */
         public static final String OR = " OR ";
 
         /** Value of the CO. */
@@ -3330,14 +3312,13 @@ public class Criteria extends Hashtable
          */
         public DB getDb()
         {
-            DB db = null;
             if (this.db == null)
             {
                 // db may not be set if generating preliminary sql for
                 // debugging.
                 try
                 {
-                    db = Torque.getDB(getDbName());
+                    return Torque.getDB(getDbName());
                 }
                 catch (Exception e)
                 {
@@ -3345,14 +3326,13 @@ public class Criteria extends Hashtable
                     // no need to throw up the exception, just make note of it.
                     log.error(
                             "Could not get a DB adapter, so sql may be wrong");
+                    return null;
                 }
             }
             else
             {
-                db = this.db;
+                return this.db;
             }
-
-            return db;
         }
 
         /**
@@ -3500,7 +3480,7 @@ public class Criteria extends Hashtable
                 return "";
             }
 
-            StringBuffer expr = new StringBuffer(25);
+            StringBuffer expr = new StringBuffer();
             try
             {
                 appendTo(expr);
@@ -3514,7 +3494,7 @@ public class Criteria extends Hashtable
 
         /**
          * This method checks another Criteria.Criterion to see if they contain
-         * the same attributes and hashtable entries.
+         * the same attributes.
          */
         public boolean equals(Object obj)
         {

Modified: db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/util/SummaryHelper.java
URL: http://svn.apache.org/viewvc/db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/util/SummaryHelper.java?rev=1103332&r1=1103331&r2=1103332&view=diff
==============================================================================
--- db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/util/SummaryHelper.java
(original)
+++ db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/util/SummaryHelper.java
Sun May 15 11:48:31 2011
@@ -344,7 +344,7 @@ public class SummaryHelper
         }
 
         // Check if the from table is set via a where clause.
-        if (!haveFromTable && c.keys().hasMoreElements())
+        if (!haveFromTable && !c.isEmpty())
         {
             haveFromTable = true;
             logger.debug("From table defined by a where clause");



---------------------------------------------------------------------
To unsubscribe, e-mail: torque-dev-unsubscribe@db.apache.org
For additional commands, e-mail: torque-dev-help@db.apache.org


Mime
View raw message