commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From dgra...@apache.org
Subject cvs commit: jakarta-commons-sandbox/dbutils/src/java/org/apache/commons/dbutils ResultSetConverter.java BasicResultSetConverter.java BeanHandler.java VectorHandler.java ResultSetIterator.java MapHandler.java CollectionHandler.java ResultSetIteratorV1.java DbUtils.java BeanCollectionHandler.java
Date Thu, 16 Oct 2003 04:21:12 GMT
dgraham     2003/10/15 21:21:12

  Modified:    dbutils/src/java/org/apache/commons/dbutils BeanHandler.java
                        VectorHandler.java ResultSetIterator.java
                        MapHandler.java CollectionHandler.java
                        ResultSetIteratorV1.java DbUtils.java
                        BeanCollectionHandler.java
  Added:       dbutils/src/java/org/apache/commons/dbutils
                        ResultSetConverter.java
                        BasicResultSetConverter.java
  Log:
  Refactored DbUtils.resultSetTo* methods into a ResultSetConverter
  interface with a BasicResultSetConverter implementation.  This
  allows clients to customize the implementation of these methods with
  subclasses.  It also makes the DbUtils API smaller and clearer.
  
  Revision  Changes    Path
  1.4       +7 -4      jakarta-commons-sandbox/dbutils/src/java/org/apache/commons/dbutils/BeanHandler.java
  
  Index: BeanHandler.java
  ===================================================================
  RCS file: /home/cvs/jakarta-commons-sandbox/dbutils/src/java/org/apache/commons/dbutils/BeanHandler.java,v
  retrieving revision 1.3
  retrieving revision 1.4
  diff -u -r1.3 -r1.4
  --- BeanHandler.java	16 Oct 2003 03:05:10 -0000	1.3
  +++ BeanHandler.java	16 Oct 2003 04:21:11 -0000	1.4
  @@ -68,6 +68,7 @@
    * <code>ResultSet</code> row into a JavaBean.
    * 
    * @see ResultSetHandler
  + * 
    * @author Juozas Baliuka
    * @author David Graham
    */
  @@ -101,7 +102,9 @@
       public Object handle(ResultSet rs, Object[] params, Object userObject)
           throws SQLException {
   
  -        return rs.next() ? DbUtils.resultSetToBean(rs, this.type) : null;
  +        return rs.next()
  +            ? BasicResultSetConverter.instance().toBean(rs, this.type)
  +            : null;
       }
   
   }
  
  
  
  1.5       +5 -4      jakarta-commons-sandbox/dbutils/src/java/org/apache/commons/dbutils/VectorHandler.java
  
  Index: VectorHandler.java
  ===================================================================
  RCS file: /home/cvs/jakarta-commons-sandbox/dbutils/src/java/org/apache/commons/dbutils/VectorHandler.java,v
  retrieving revision 1.4
  retrieving revision 1.5
  diff -u -r1.4 -r1.5
  --- VectorHandler.java	16 Oct 2003 03:14:38 -0000	1.4
  +++ VectorHandler.java	16 Oct 2003 04:21:11 -0000	1.5
  @@ -69,6 +69,7 @@
    * <code>ResultSet</code> into an <code>Object[]</code>.
    * 
    * @see ResultSetHandler
  + * 
    * @author Juozas Baliuka
    * @author David Graham
    */
  @@ -86,7 +87,7 @@
       public Object handle(ResultSet rs, Object[] params, Object userObject)
           throws SQLException {
   
  -        return rs.next() ? DbUtils.resultSetToArray(rs) : null;
  +        return rs.next() ? BasicResultSetConverter.instance().toArray(rs) : null;
       }
   
   }
  
  
  
  1.5       +4 -4      jakarta-commons-sandbox/dbutils/src/java/org/apache/commons/dbutils/ResultSetIterator.java
  
  Index: ResultSetIterator.java
  ===================================================================
  RCS file: /home/cvs/jakarta-commons-sandbox/dbutils/src/java/org/apache/commons/dbutils/ResultSetIterator.java,v
  retrieving revision 1.4
  retrieving revision 1.5
  diff -u -r1.4 -r1.5
  --- ResultSetIterator.java	16 Oct 2003 03:34:07 -0000	1.4
  +++ ResultSetIterator.java	16 Oct 2003 04:21:11 -0000	1.5
  @@ -94,7 +94,7 @@
       public Object next() {
           try {
               rs.next();
  -            return DbUtils.resultSetToArray(rs);
  +            return BasicResultSetConverter.instance().toArray(rs);
   
           } catch (SQLException e) {
               // TODO Logging?
  
  
  
  1.4       +4 -4      jakarta-commons-sandbox/dbutils/src/java/org/apache/commons/dbutils/MapHandler.java
  
  Index: MapHandler.java
  ===================================================================
  RCS file: /home/cvs/jakarta-commons-sandbox/dbutils/src/java/org/apache/commons/dbutils/MapHandler.java,v
  retrieving revision 1.3
  retrieving revision 1.4
  diff -u -r1.3 -r1.4
  --- MapHandler.java	16 Oct 2003 03:14:38 -0000	1.3
  +++ MapHandler.java	16 Oct 2003 04:21:11 -0000	1.4
  @@ -88,7 +88,7 @@
       public Object handle(ResultSet rs, Object[] params, Object userObject)
           throws SQLException {
   
  -        return rs.next() ? DbUtils.resultSetToMap(rs) : null;
  +        return rs.next() ? BasicResultSetConverter.instance().toMap(rs) : null;
       }
   
   }
  
  
  
  1.3       +9 -7      jakarta-commons-sandbox/dbutils/src/java/org/apache/commons/dbutils/CollectionHandler.java
  
  Index: CollectionHandler.java
  ===================================================================
  RCS file: /home/cvs/jakarta-commons-sandbox/dbutils/src/java/org/apache/commons/dbutils/CollectionHandler.java,v
  retrieving revision 1.2
  retrieving revision 1.3
  diff -u -r1.2 -r1.3
  --- CollectionHandler.java	16 Oct 2003 03:14:38 -0000	1.2
  +++ CollectionHandler.java	16 Oct 2003 04:21:11 -0000	1.3
  @@ -71,6 +71,7 @@
    * <code>ResultSet</code> into a <code>List</code> of <code>Object[]</code>s.
    * 
    * @see ResultSetHandler
  + * 
    * @author Juozas Baliuka
    * @author David Graham
    */
  @@ -89,13 +90,14 @@
        */
       public Object handle(ResultSet rs, Object[] params, Object userObject)
           throws SQLException {
  -            
  +
           List result = new ArrayList();
  -        
  +
  +        ResultSetConverter convert = BasicResultSetConverter.instance();
           while (rs.next()) {
  -            result.add(DbUtils.resultSetToArray(rs));
  +            result.add(convert.toArray(rs));
           }
  -        
  +
           return result;
       }
   
  
  
  
  1.5       +4 -4      jakarta-commons-sandbox/dbutils/src/java/org/apache/commons/dbutils/ResultSetIteratorV1.java
  
  Index: ResultSetIteratorV1.java
  ===================================================================
  RCS file: /home/cvs/jakarta-commons-sandbox/dbutils/src/java/org/apache/commons/dbutils/ResultSetIteratorV1.java,v
  retrieving revision 1.4
  retrieving revision 1.5
  diff -u -r1.4 -r1.5
  --- ResultSetIteratorV1.java	16 Oct 2003 03:34:07 -0000	1.4
  +++ ResultSetIteratorV1.java	16 Oct 2003 04:21:11 -0000	1.5
  @@ -94,7 +94,7 @@
       private void doNext() {
           try {
               rs.next();
  -            this.val = DbUtils.resultSetToArray(rs);
  +            this.val = BasicResultSetConverter.instance().toArray(rs);
               
           } catch (SQLException sqle) {
               this.val = null;
  
  
  
  1.35      +119 -302  jakarta-commons-sandbox/dbutils/src/java/org/apache/commons/dbutils/DbUtils.java
  
  Index: DbUtils.java
  ===================================================================
  RCS file: /home/cvs/jakarta-commons-sandbox/dbutils/src/java/org/apache/commons/dbutils/DbUtils.java,v
  retrieving revision 1.34
  retrieving revision 1.35
  diff -u -r1.34 -r1.35
  --- DbUtils.java	16 Oct 2003 03:34:07 -0000	1.34
  +++ DbUtils.java	16 Oct 2003 04:21:11 -0000	1.35
  @@ -61,27 +61,17 @@
    
   package org.apache.commons.dbutils;
   
  -import java.beans.BeanInfo;
  -import java.beans.IntrospectionException;
  -import java.beans.Introspector;
  -import java.beans.PropertyDescriptor;
   import java.io.PrintWriter;
  -import java.lang.reflect.InvocationTargetException;
  -import java.lang.reflect.Method;
   import java.sql.Connection;
   import java.sql.PreparedStatement;
   import java.sql.ResultSet;
  -import java.sql.ResultSetMetaData;
   import java.sql.SQLException;
   import java.sql.Statement;
   import java.sql.Types;
   import java.util.ArrayList;
   import java.util.Arrays;
  -import java.util.Collection;
  -import java.util.HashMap;
   import java.util.Iterator;
   import java.util.List;
  -import java.util.Map;
   
   /**
    * A collection of JDBC helper methods.
  @@ -93,122 +83,125 @@
    */
   public final class DbUtils {
       
  -    private static Map DEFAULTS = new HashMap();
  -    
  -    static{
  -        
  -        DEFAULTS.put(int.class,     new Integer(0));
  -        DEFAULTS.put(short.class,   new Short((short)0));
  -        DEFAULTS.put(byte.class,    new Byte((byte)0));
  -        DEFAULTS.put(float.class,   new Float(0f));
  -        DEFAULTS.put(double.class,  new Double(0.0));
  -        DEFAULTS.put(long.class,    new Long(0L));
  -        DEFAULTS.put(boolean.class, Boolean.FALSE);
  -        DEFAULTS.put(char.class,    new Character('\u0000'));
  -        
  -    }
  -    
  -    public static abstract class ListAdapter extends ArrayList implements ResultSetHandler{
  -        
  -        public final Object handle(java.sql.ResultSet rs, Object[] params, Object userObject)
throws java.sql.SQLException{
  -            
  -            while(rs.next()){
  +    private static abstract class ListAdapter
  +        extends ArrayList
  +        implements ResultSetHandler {
  +
  +        public final Object handle(ResultSet rs, Object[] params, Object userObject)
  +            throws SQLException {
  +
  +            while (rs.next()) {
                   add(fetch(rs));
               }
  +            
               return this;
           }
  -        
  -        public abstract Object fetch( ResultSet rs )throws SQLException;
  -        
  +
  +        public abstract Object fetch(ResultSet rs) throws SQLException;
       }
       
  -    
  -    
  -    public static boolean execute(Connection connection, String query,Object[] vals, ResultSetHandler
rsh, ResultSetMetaDataHandler rsmdh, Object userObject)
  -    throws SQLException {
  -        
  +    public static boolean execute(
  +        Connection conn,
  +        String query,
  +        Object[] vals,
  +        ResultSetHandler rsh,
  +        ResultSetMetaDataHandler rsmdh,
  +        Object userObject)
  +        throws SQLException {
  +
           PreparedStatement stmt = null;
           ResultSet rs = null;
  -        
  +
           try {
  -            
  -            stmt = connection.prepareStatement(query);
  +            stmt = conn.prepareStatement(query);
               fillStatement(stmt, vals);
  -            
  -            try{
  -                if(stmt.execute()){
  -                    do{
  -                        
  +
  +            try {
  +                if (stmt.execute()) {
  +                    do {
                           rs = stmt.getResultSet();
  -                        if(rs != null) {
  -                            if(rsmdh != null) {
  +                        if (rs != null) {
  +                            if (rsmdh != null) {
                                   rsmdh.handle(rs.getMetaData());
                               }
                           }
  -                        rsh.handle(rs,vals,userObject);
  -                        
  -                    }while(stmt.getMoreResults());
  -                    
  +                        rsh.handle(rs, vals, userObject);
  +
  +                    } while (stmt.getMoreResults());
  +
                       return true;
  -                    
  -                }else{
  -                    
  +
  +                } else {
  +
                       return false;
  -                    
  +
                   }
  -            }catch(SQLException sqle){
  -                
  +            } catch (SQLException sqle) {
  +
                   closeQuietly(rs);
  -                rethrow( sqle, query, vals);
  -                
  +                rethrow(sqle, query, vals);
  +
               }
               return false;
  -            
  +
           } finally {
               closeQuietly(stmt);
           }
  -        
  +
       }
  -    
  -    public static Object executeQuery(Connection connection, String query,
  -    Object[] vals, ResultSetHandler rsh, ResultSetMetaDataHandler rsmdh) throws SQLException{
  -        return  executeQuery(connection,query, vals, rsh, rsmdh, null  );
  +
  +    public static Object executeQuery(
  +        Connection conn,
  +        String query,
  +        Object[] vals,
  +        ResultSetHandler rsh,
  +        ResultSetMetaDataHandler rsmdh)
  +        throws SQLException {
  +            
  +        return executeQuery(conn, query, vals, rsh, rsmdh, null);
       }
  -    
  -    public static Object executeQuery(Connection connection, String query,
  -    Object[] vals, ResultSetHandler rsh, ResultSetMetaDataHandler rsmdh, Object userObject)
  -    throws SQLException {
  -        
  +
  +    public static Object executeQuery(
  +        Connection conn,
  +        String query,
  +        Object[] vals,
  +        ResultSetHandler rsh,
  +        ResultSetMetaDataHandler rsmdh,
  +        Object userObject)
  +        throws SQLException {
  +
           PreparedStatement stmt = null;
           ResultSet rs = null;
  -        
  +
           try {
  -            
  -            stmt = connection.prepareStatement(query);
  +
  +            stmt = conn.prepareStatement(query);
               fillStatement(stmt, vals);
  -            
  -            try{
  +
  +            try {
                   rs = stmt.executeQuery();
  -            }catch(SQLException sqle){
  -                rethrow( sqle, query, vals);
  +                
  +            } catch (SQLException sqle) {
  +                rethrow(sqle, query, vals);
               }
  -            if(rs != null){
  -                if(rsmdh != null) {
  -                    try{
  +            
  +            if (rs != null) {
  +                if (rsmdh != null) {
  +                    try {
                           rsmdh.handle(rs.getMetaData());
  -                    }
  -                    catch(SQLException sqle){
  -                        rethrow( sqle, query, vals);
  +                    } catch (SQLException sqle) {
  +                        rethrow(sqle, query, vals);
                       }
                   }
               }
  -            return rsh.handle(rs,vals,userObject);
               
  +            return rsh.handle(rs, vals, userObject);
  +
           } finally {
               closeQuietly(rs);
               closeQuietly(stmt);
           }
  -        
  +
       }
       
       private static void rethrow(SQLException cause, String sql, Object[] vals)
  @@ -259,11 +252,14 @@
           }
       }
       
  -    
  -    public static List executeListQuery(Connection connection,
  -    String query, Object[] vals, Object userObject )
  -    throws SQLException {
  -        return executeListQuery(connection, query, vals, null, userObject);
  +    public static List executeListQuery(
  +        Connection conn,
  +        String query,
  +        Object[] vals,
  +        Object userObject)
  +        throws SQLException {
  +            
  +        return executeListQuery(conn, query, vals, null, userObject);
       }
       
       /**
  @@ -272,30 +268,33 @@
        * inside an List.
        * Null values in the Object array will be passed to the driver.
        */
  -    public static List executeListQuery(Connection connection,
  -    String query, Object[] vals, ResultSetMetaDataHandler rsmdh, Object userObject )
  -    throws SQLException {
  -        return (List)executeQuery(connection,query,vals,
  -        
  -        new ListAdapter(){
  +    public static List executeListQuery(
  +        Connection conn,
  +        String query,
  +        Object[] vals,
  +        ResultSetMetaDataHandler rsmdh,
  +        Object userObject)
  +        throws SQLException {
               
  -            public  Object fetch( ResultSet rs )throws SQLException{
  -                return resultSetToArray(rs);
  -            }
  +        ListAdapter la = new ListAdapter() {
  +            private ResultSetConverter convert = BasicResultSetConverter.instance();
               
  -        }
  -        
  -        , rsmdh
  -        , userObject );
  +            public Object fetch(ResultSet rs) throws SQLException {
  +                return convert.toArray(rs);
  +            }
  +        };
           
  +        return (List) executeQuery(conn, query, vals, la, rsmdh, userObject);
       }
       
  -    
  -    
  -    public static Iterator executeQuery(Connection connection, String query, Object[] vals,
ResultSetMetaDataHandler rsmdh )
  -    throws SQLException {
  -        return executeListQuery(connection, query, vals, rsmdh, null ).iterator();
  -        
  +    public static Iterator executeQuery(
  +        Connection conn,
  +        String query,
  +        Object[] vals,
  +        ResultSetMetaDataHandler rsmdh)
  +        throws SQLException {
  +            
  +        return executeListQuery(conn, query, vals, rsmdh, null).iterator();
       }
       
       /**
  @@ -304,15 +303,15 @@
        * inside an Iterator.
        * Null values in the Object array will be passed to the driver.
        */
  -    public static Iterator executeQuery(Connection connection, String query, Object[] vals
)
  -    throws SQLException {
  -        return executeListQuery(connection, query, vals, null, null ).iterator();
  -        
  +    public static Iterator executeQuery(
  +        Connection connection,
  +        String query,
  +        Object[] vals)
  +        throws SQLException {
  +            
  +        return executeListQuery(connection, query, vals, null, null).iterator();
       }
       
  -    
  -    
  -    
       /**
        * Ensures that a database driver class is loaded.
        * If this succeeds, then it returns true, else it returns false.
  @@ -342,188 +341,6 @@
           } catch (Throwable t) {
               return false;
           }
  -    }
  -    
  -    /**
  -     * Create a Map from a ResultSet.
  -     * It is assumed that next() has already been called on the ResultSet.
  -     */
  -    public static Map resultSetToMap(ResultSet rs) throws SQLException {
  -        Map result = new HashMap();
  -        ResultSetMetaData rsmd = rs.getMetaData();
  -        int cols = rsmd.getColumnCount();
  -        
  -        for (int i = 1; i <= cols; i++) {
  -            Object value = rs.getObject(i);
  -            if (!rs.wasNull()) {
  -                result.put(rsmd.getColumnName(i), value);
  -            }
  -        }
  -        
  -        return result;
  -    }
  -    
  -    /**
  -     * Create a JavaBean from a <code>ResultSet</code>.  It is assumed 
  -     * that <code>next()</code> has already been called on the 
  -     * <code>ResultSet</code>.
  -     */
  -    public static Object resultSetToBean(ResultSet rs, Class cls)
  -        throws SQLException {
  -
  -        Object obj = newInstance(cls);
  -
  -        PropertyDescriptor[] pd = propertyDescriptors(cls);
  -
  -        ResultSetMetaData rsmd = rs.getMetaData();
  -        int cols = rsmd.getColumnCount();
  -        LOOP : for (int i = 1; i <= cols; i++) {
  -            String columnName = rsmd.getColumnName(i);
  -            for (int j = 0; j < pd.length; j++) {
  -                if (columnName.equals(pd[j].getName())) {
  -                    Object value = rs.getObject(i);
  -                    if (rs.wasNull() && pd[j].getPropertyType().isPrimitive())
{
  -                        value = DEFAULTS.get(pd[j].getPropertyType());
  -                    }
  -
  -                    callSetter(pd[j], obj, value);
  -                    continue LOOP;
  -                }
  -            }
  -
  -            throw new SQLException(
  -                columnName + " not found in " + obj.getClass().getName());
  -        }
  -
  -        return obj;
  -    }
  -    
  -    /**
  -     * Calls the setter method on the target object for the given property.
  -     * If no setter method exists for the property, this method does nothing.
  -     * @param pd The property to set.
  -     * @param target The object to set the property on.
  -     * @param value The value to pass into the setter.
  -     * @throws DbException if an error occurs setting the property.
  -     */
  -    private static void callSetter(
  -        PropertyDescriptor pd,
  -        Object target,
  -        Object value) {
  -
  -        try {
  -            Method setter = pd.getWriteMethod();
  -
  -            if (setter != null) {
  -                setter.invoke(target, new Object[] { value });
  -            }
  -
  -        } catch (IllegalArgumentException e) {
  -            throw new DbException("Cannot set " + pd.getName(), e);
  -        } catch (IllegalAccessException e) {
  -            throw new DbException("Cannot set " + pd.getName(), e);
  -        } catch (InvocationTargetException e) {
  -            throw new DbException("Cannot set " + pd.getName(), e);
  -        }
  -    }
  -
  -    /**
  -     * Returns a PropertyDescriptor[] for the given Class.
  -     * @param c The Class to retrieve PropertyDescriptors for.
  -     * @return A PropertyDescriptor[] describing the Class.
  -     * @throws DbException if introspection failed.
  -     */
  -    private static PropertyDescriptor[] propertyDescriptors(Class c) {
  -        BeanInfo beanInfo = null;
  -        try {
  -            beanInfo = Introspector.getBeanInfo(c);
  -        } catch (IntrospectionException e) {
  -            throw new DbException(e);
  -        }
  -        
  -        return beanInfo.getPropertyDescriptors();
  -    }
  -    
  -    /**
  -     * Optimized for collections of beans.
  -     */
  -    public static Collection resultSetToBeanCollection(ResultSet rs, Class cls)
  -        throws SQLException {
  -
  -        Collection results = new ArrayList();
  -
  -        if (!rs.next()) {
  -            return results;
  -        }
  -
  -        PropertyDescriptor[] pd = propertyDescriptors(cls);
  -        ResultSetMetaData rsmd = rs.getMetaData();
  -        int cols = rsmd.getColumnCount();
  -        int nameToIndex[] = new int[cols + 1];
  -
  -        LOOP : for (int i = 1; i <= cols; i++) {
  -            String columnName = rsmd.getColumnName(i);
  -            for (int j = 0; j < pd.length; j++) {
  -                if (columnName.equals(pd[j].getName())) {
  -                    nameToIndex[i] = j;
  -                    continue LOOP;
  -                }
  -            }
  -            throw new SQLException(" index not found for " + columnName);
  -        }
  -
  -        do {
  -            Object obj = newInstance(cls);
  -
  -            for (int i = 1; i <= cols; i++) {
  -                Object value = rs.getObject(i);
  -                if (rs.wasNull()) {
  -                    continue;
  -                }
  -
  -                callSetter(pd[nameToIndex[i]], obj, value);
  -            }
  -
  -            results.add(obj);
  -
  -        } while (rs.next());
  -
  -        return results;
  -    }
  -
  -    /**
  -     * Returns a new instance of the given Class.
  -     * @param c The Class to create an object from.
  -     * @return A newly created object of the Class.
  -     * @throws DbException if creation failed.
  -     */
  -    private static Object newInstance(Class c) {
  -        try {
  -            return c.newInstance();
  -
  -        } catch (InstantiationException e) {
  -            throw new DbException("Cannot create " + c.getName(), e);
  -        } catch (IllegalAccessException e) {
  -            throw new DbException("Cannot create " + c.getName(), e);
  -        }
  -    }
  -    
  -    
  -    /**
  -     * Create an Object array from a ResultSet.
  -     * It is assumed that next() has already been called on the ResultSet.
  -     */
  -    public static Object[] resultSetToArray(ResultSet rs) throws SQLException {
  -        ResultSetMetaData meta = rs.getMetaData();
  -        int cols = meta.getColumnCount();
  -        Object[] objs = new Object[cols];
  -        for (int i = 0; i < cols; i++) {
  -            Object obj = rs.getObject(i + 1);
  -            
  -            objs[i] = rs.wasNull() ? null : obj;
  -        }
  -
  -        return objs;
       }
       
       /**
  
  
  
  1.3       +5 -4      jakarta-commons-sandbox/dbutils/src/java/org/apache/commons/dbutils/BeanCollectionHandler.java
  
  Index: BeanCollectionHandler.java
  ===================================================================
  RCS file: /home/cvs/jakarta-commons-sandbox/dbutils/src/java/org/apache/commons/dbutils/BeanCollectionHandler.java,v
  retrieving revision 1.2
  retrieving revision 1.3
  diff -u -r1.2 -r1.3
  --- BeanCollectionHandler.java	16 Oct 2003 03:14:38 -0000	1.2
  +++ BeanCollectionHandler.java	16 Oct 2003 04:21:11 -0000	1.3
  @@ -69,6 +69,7 @@
    * <code>ResultSet</code> column into an Object.
    * 
    * @see ResultSetHandler
  + * 
    * @author Juozas Baliuka
    * @author David Graham
    */
  @@ -102,7 +103,7 @@
       public Object handle(ResultSet rs, Object[] params, Object userObject)
           throws SQLException {
               
  -        return DbUtils.resultSetToBeanCollection(rs, type);
  +        return BasicResultSetConverter.instance().toBeanList(rs, type);
       }
   
   }
  
  
  
  1.1                  jakarta-commons-sandbox/dbutils/src/java/org/apache/commons/dbutils/ResultSetConverter.java
  
  Index: ResultSetConverter.java
  ===================================================================
  /*
   * $Header: /home/cvs/jakarta-commons-sandbox/dbutils/src/java/org/apache/commons/dbutils/ResultSetConverter.java,v
1.1 2003/10/16 04:21:11 dgraham Exp $
   * $Revision: 1.1 $
   * $Date: 2003/10/16 04:21:11 $
   * 
   * ====================================================================
   *
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 2003 The Apache Software Foundation.  All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution, if
   *    any, must include the following acknowledgement:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowledgement may appear in the software itself,
   *    if and wherever such third-party acknowledgements normally appear.
   *
   * 4. The names "The Jakarta Project", "Commons", and "Apache Software
   *    Foundation" must not be used to endorse or promote products derived
   *    from this software without prior written permission. For written
   *    permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache"
   *    nor may "Apache" appear in their names without prior written
   *    permission of the Apache Software Foundation.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   *
   */
  
  package org.apache.commons.dbutils;
  
  import java.sql.ResultSet;
  import java.sql.SQLException;
  import java.util.List;
  import java.util.Map;
  
  /**
   * <code>ResultSetConverter</code> implementations convert 
   * <code>ResultSet</code> rows into various other objects.  Implementations
   * can extend <code>BasicResultSetConverter</code> to protect themselves
   * from changes to this interface. 
   * 
   * @see BasicResultSetConverter
   * @author David Graham
   */
  public interface ResultSetConverter {
  
      /**
       * Create an <code>Object[]</code> from the column values in one 
       * <code>ResultSet</code> row.  The <code>ResultSet</code> should
be 
       * positioned on a valid row before passing it to this method.  
       * Implementations of this method must not alter the row position of 
       * the <code>ResultSet</code>. 
       */
      public Object[] toArray(ResultSet rs) throws SQLException;
  
      /**
       * Create a JavaBean from the column values in one <code>ResultSet</code>

       * row.  The <code>ResultSet</code> should be positioned on a valid row
before
       * passing it to this method.  Implementations of this method must not
       * alter the row position of the <code>ResultSet</code>.
       */
      public Object toBean(ResultSet rs, Class type) throws SQLException;
  
      /**
       * Create a <code>List</code> of JavaBeans from the column values in all

       * <code>ResultSet</code> rows.  <code>ResultSet.next()</code>
should 
       * <strong>not</strong> be called before passing it to this method.
       * 
       * @return A <code>List</code> of beans with the given type in the order

       * they were returned by the <code>ResultSet</code>.
       */
      public List toBeanList(ResultSet rs, Class type) throws SQLException;
  
      /**
       * Create a <code>Map</code> from the column values in one 
       * <code>ResultSet</code> row.  The <code>ResultSet</code> should
be 
       * positioned on a valid row before
       * passing it to this method.  Implementations of this method must not
       * alter the row position of the <code>ResultSet</code>.
       */
      public Map toMap(ResultSet rs) throws SQLException;
  
  }
  
  
  
  1.1                  jakarta-commons-sandbox/dbutils/src/java/org/apache/commons/dbutils/BasicResultSetConverter.java
  
  Index: BasicResultSetConverter.java
  ===================================================================
  /*
   * $Header: /home/cvs/jakarta-commons-sandbox/dbutils/src/java/org/apache/commons/dbutils/BasicResultSetConverter.java,v
1.1 2003/10/16 04:21:11 dgraham Exp $
   * $Revision: 1.1 $
   * $Date: 2003/10/16 04:21:11 $
   * 
   * ====================================================================
   *
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 2002-2003 The Apache Software Foundation.  All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution, if
   *    any, must include the following acknowledgement:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowledgement may appear in the software itself,
   *    if and wherever such third-party acknowledgements normally appear.
   *
   * 4. The names "The Jakarta Project", "Commons", and "Apache Software
   *    Foundation" must not be used to endorse or promote products derived
   *    from this software without prior written permission. For written
   *    permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache"
   *    nor may "Apache" appear in their names without prior written
   *    permission of the Apache Software Foundation.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   *
   */
  
  package org.apache.commons.dbutils;
  
  import java.beans.BeanInfo;
  import java.beans.IntrospectionException;
  import java.beans.Introspector;
  import java.beans.PropertyDescriptor;
  import java.lang.reflect.InvocationTargetException;
  import java.lang.reflect.Method;
  import java.sql.ResultSet;
  import java.sql.ResultSetMetaData;
  import java.sql.SQLException;
  import java.util.ArrayList;
  import java.util.HashMap;
  import java.util.List;
  import java.util.Map;
  
  /**
   * Basic implementation of the <code>ResultSetConverter</code> interface.
   * This class is a thread-safe Singleton.
   * 
   * @see ResultSetConverter
   * 
   * @author Henri Yandell
   * @author Juozas Baliuka
   * @author David Graham
   */
  public class BasicResultSetConverter implements ResultSetConverter {
  
      /**
       * The Singleton instance of this class.
       */
      private static final BasicResultSetConverter instance =
          new BasicResultSetConverter();
  
      /**
       * If a column was null, and the bean property is a primitive type, set
       * the property to the default value for its type. 
       */
      private static final Map defaultValues = new HashMap();
  
      static {
          defaultValues.put(int.class, new Integer(0));
          defaultValues.put(short.class, new Short((short) 0));
          defaultValues.put(byte.class, new Byte((byte) 0));
          defaultValues.put(float.class, new Float(0f));
          defaultValues.put(double.class, new Double(0.0));
          defaultValues.put(long.class, new Long(0L));
          defaultValues.put(boolean.class, Boolean.FALSE);
          defaultValues.put(char.class, new Character('\u0000'));
      }
      
      /**
       * Returns the Singleton instance of this class.
       */
      public static BasicResultSetConverter instance(){
          return instance;
      }
  
      /**
       * Protected constructor for BasicResultSetConverter subclasses only.
       */
      protected BasicResultSetConverter() {
          super();
      }
  
      // See interface for javadoc.
      public Object[] toArray(ResultSet rs) throws SQLException {
          ResultSetMetaData meta = rs.getMetaData();
          int cols = meta.getColumnCount();
          Object[] objs = new Object[cols];
  
          for (int i = 0; i < cols; i++) {
              Object obj = rs.getObject(i + 1);
  
              objs[i] = rs.wasNull() ? null : obj;
          }
  
          return objs;
      }
  
      // See interface for javadoc.
      public Object toBean(ResultSet rs, Class type) throws SQLException {
          Object obj = newInstance(type);
  
          PropertyDescriptor[] pd = propertyDescriptors(type);
  
          ResultSetMetaData rsmd = rs.getMetaData();
          int cols = rsmd.getColumnCount();
          LOOP : for (int i = 1; i <= cols; i++) {
              String columnName = rsmd.getColumnName(i);
  
              for (int j = 0; j < pd.length; j++) {
  
                  if (columnName.equals(pd[j].getName())) {
                      Object value = rs.getObject(i);
  
                      if (rs.wasNull() && pd[j].getPropertyType().isPrimitive()) {
                          value = defaultValues.get(pd[j].getPropertyType());
                      }
  
                      callSetter(pd[j], obj, value);
                      continue LOOP;
                  }
              }
  
              throw new SQLException(
                  columnName + " not found in " + obj.getClass().getName());
          }
  
          return obj;
      }
  
      // See interface for javadoc.
      public List toBeanList(ResultSet rs, Class type) throws SQLException {
          List results = new ArrayList();
  
          if (!rs.next()) {
              return results;
          }
  
          PropertyDescriptor[] pd = propertyDescriptors(type);
          ResultSetMetaData rsmd = rs.getMetaData();
          int cols = rsmd.getColumnCount();
          int nameToIndex[] = new int[cols + 1];
  
          LOOP : for (int i = 1; i <= cols; i++) {
              String columnName = rsmd.getColumnName(i);
              for (int j = 0; j < pd.length; j++) {
  
                  if (columnName.equals(pd[j].getName())) {
                      nameToIndex[i] = j;
                      continue LOOP;
                  }
              }
  
              throw new SQLException(" index not found for " + columnName);
          }
  
          do {
              Object obj = newInstance(type);
  
              for (int i = 1; i <= cols; i++) {
                  Object value = rs.getObject(i);
                  if (rs.wasNull()) {
                      continue;
                  }
  
                  callSetter(pd[nameToIndex[i]], obj, value);
              }
  
              results.add(obj);
  
          } while (rs.next());
  
          return results;
      }
  
      // See interface for javadoc.
      public Map toMap(ResultSet rs) throws SQLException {
          Map result = new HashMap();
          ResultSetMetaData rsmd = rs.getMetaData();
          int cols = rsmd.getColumnCount();
  
          for (int i = 1; i <= cols; i++) {
              Object value = rs.getObject(i);
              if (!rs.wasNull()) {
                  result.put(rsmd.getColumnName(i), value);
              }
          }
  
          return result;
      }
  
      /**
       * Calls the setter method on the target object for the given property.
       * If no setter method exists for the property, this method does nothing.
       * @param pd The property to set.
       * @param target The object to set the property on.
       * @param value The value to pass into the setter.
       * @throws DbException if an error occurs setting the property.
       */
      private void callSetter(PropertyDescriptor pd, Object target, Object value) {
  
          try {
              Method setter = pd.getWriteMethod();
  
              if (setter != null) {
                  setter.invoke(target, new Object[] { value });
              }
  
          } catch (IllegalArgumentException e) {
              throw new DbException("Cannot set " + pd.getName(), e);
          } catch (IllegalAccessException e) {
              throw new DbException("Cannot set " + pd.getName(), e);
          } catch (InvocationTargetException e) {
              throw new DbException("Cannot set " + pd.getName(), e);
          }
      }
  
      /**
       * Returns a new instance of the given Class.
       * @param c The Class to create an object from.
       * @return A newly created object of the Class.
       * @throws DbException if creation failed.
       */
      private Object newInstance(Class c) {
          try {
              return c.newInstance();
  
          } catch (InstantiationException e) {
              throw new DbException("Cannot create " + c.getName(), e);
  
          } catch (IllegalAccessException e) {
              throw new DbException("Cannot create " + c.getName(), e);
          }
      }
  
      /**
       * Returns a PropertyDescriptor[] for the given Class.
       * @param c The Class to retrieve PropertyDescriptors for.
       * @return A PropertyDescriptor[] describing the Class.
       * @throws DbException if introspection failed.
       */
      private PropertyDescriptor[] propertyDescriptors(Class c) {
          BeanInfo beanInfo = null;
          try {
              beanInfo = Introspector.getBeanInfo(c);
  
          } catch (IntrospectionException e) {
              throw new DbException(e);
          }
  
          return beanInfo.getPropertyDescriptors();
      }
  
  }
  
  
  

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


Mime
View raw message