View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.commons.beanutils;
19  
20  import java.io.Serializable;
21  import java.sql.Date;
22  import java.sql.ResultSet;
23  import java.sql.ResultSetMetaData;
24  import java.sql.SQLException;
25  import java.sql.Time;
26  import java.sql.Timestamp;
27  import java.util.ArrayList;
28  import java.util.HashMap;
29  import java.util.Map;
30  
31  /**
32   * <p>Provides common logic for JDBC implementations of {@link DynaClass}.</p>
33   *
34   * @version $Id$
35   */
36  
37  abstract class JDBCDynaClass implements DynaClass, Serializable {
38  
39      // ----------------------------------------------------- Instance Variables
40  
41      /**
42       * <p>Flag defining whether column names should be lower cased when
43       * converted to property names.</p>
44       */
45      protected boolean lowerCase = true;
46  
47      /**
48       * <p>Flag defining whether column names or labels should be used.
49       */
50      private boolean useColumnLabel;
51  
52      /**
53       * <p>The set of dynamic properties that are part of this
54       * {@link DynaClass}.</p>
55       */
56      protected DynaProperty[] properties = null;
57  
58      /**
59       * <p>The set of dynamic properties that are part of this
60       * {@link DynaClass}, keyed by the property name.  Individual descriptor
61       * instances will be the same instances as those in the
62       * <code>properties</code> list.</p>
63       */
64      protected Map<String, DynaProperty> propertiesMap = new HashMap<String, DynaProperty>();
65  
66      /**
67       * Cross Reference for column name --> dyna property name
68       * (needed when lowerCase option is true)
69       */
70      private Map<String, String> columnNameXref;
71  
72      // ------------------------------------------------------ DynaClass Methods
73  
74      /**
75       * <p>Return the name of this DynaClass (analogous to the
76       * <code>getName()</code> method of <code>java.lang.Class</code), which
77       * allows the same <code>DynaClass</code> implementation class to support
78       * different dynamic classes, with different sets of properties.</p>
79       */
80      public String getName() {
81  
82          return (this.getClass().getName());
83  
84      }
85  
86      /**
87       * <p>Return a property descriptor for the specified property, if it
88       * exists; otherwise, return <code>null</code>.</p>
89       *
90       * @param name Name of the dynamic property for which a descriptor
91       *  is requested
92       *
93       * @throws IllegalArgumentException if no property name is specified
94       */
95      public DynaProperty getDynaProperty(final String name) {
96  
97          if (name == null) {
98              throw new IllegalArgumentException("No property name specified");
99          }
100         return (propertiesMap.get(name));
101 
102     }
103 
104     /**
105      * <p>Return an array of <code>ProperyDescriptors</code> for the properties
106      * currently defined in this DynaClass.  If no properties are defined, a
107      * zero-length array will be returned.</p>
108      */
109     public DynaProperty[] getDynaProperties() {
110 
111         return (properties);
112 
113     }
114 
115     /**
116      * <p>Instantiate and return a new DynaBean instance, associated
117      * with this DynaClass.  <strong>NOTE</strong> - This operation is not
118      * supported, and throws an exception.</p>
119      *
120      * @throws IllegalAccessException if the Class or the appropriate
121      *  constructor is not accessible
122      * @throws InstantiationException if this Class represents an abstract
123      *  class, an array class, a primitive type, or void; or if instantiation
124      *  fails for some other reason
125      */
126     public DynaBean newInstance()
127             throws IllegalAccessException, InstantiationException {
128 
129         throw new UnsupportedOperationException("newInstance() not supported");
130 
131     }
132 
133     /**
134      * Set whether the column label or name should be used for the property name.
135      *
136      * @param useColumnLabel true if the column label should be used, otherwise false
137      */
138     public void setUseColumnLabel(final boolean useColumnLabel) {
139         this.useColumnLabel = useColumnLabel;
140     }
141 
142     /**
143      * <p>Loads and returns the <code>Class</code> of the given name.
144      * By default, a load from the thread context class loader is attempted.
145      * If there is no such class loader, the class loader used to load this
146      * class will be utilized.</p>
147      *
148      * @param className The name of the class to load
149      * @return The loaded class
150      * @throws SQLException if an exception was thrown trying to load
151      *  the specified class
152      */
153     protected Class<?> loadClass(final String className) throws SQLException {
154 
155         try {
156             ClassLoader cl = Thread.currentThread().getContextClassLoader();
157             if (cl == null) {
158                     cl = this.getClass().getClassLoader();
159             }
160             // use Class.forName() - see BEANUTILS-327
161             return Class.forName(className, false, cl);
162         } catch (final Exception e) {
163             throw new SQLException(
164                     "Cannot load column class '" + className + "': " + e);
165         }
166 
167     }
168 
169     /**
170      * <p>Factory method to create a new DynaProperty for the given index
171      * into the result set metadata.</p>
172      *
173      * @param metadata is the result set metadata
174      * @param i is the column index in the metadata
175      * @return the newly created DynaProperty instance
176      * @throws SQLException If an error occurs accessing the SQL metadata
177      */
178     protected DynaProperty createDynaProperty(
179                                     final ResultSetMetaData metadata,
180                                     final int i)
181                                     throws SQLException {
182 
183         String columnName = null;
184         if (useColumnLabel) {
185             columnName = metadata.getColumnLabel(i);
186         }
187         if (columnName == null || columnName.trim().length() == 0) {
188             columnName = metadata.getColumnName(i);
189         }
190         final String name = lowerCase ? columnName.toLowerCase() : columnName;
191         if (!name.equals(columnName)) {
192             if (columnNameXref == null) {
193                 columnNameXref = new HashMap<String, String>();
194             }
195             columnNameXref.put(name, columnName);
196         }
197         String className = null;
198         try {
199             final int sqlType = metadata.getColumnType(i);
200             switch (sqlType) {
201                 case java.sql.Types.DATE:
202                     return new DynaProperty(name, java.sql.Date.class);
203                 case java.sql.Types.TIMESTAMP:
204                     return new DynaProperty(name, java.sql.Timestamp.class);
205                 case java.sql.Types.TIME:
206                     return new DynaProperty(name, java.sql.Time.class);
207                 default:
208                     className = metadata.getColumnClassName(i);
209             }
210         } catch (final SQLException e) {
211             // this is a patch for HsqlDb to ignore exceptions
212             // thrown by its metadata implementation
213         }
214 
215         // Default to Object type if no class name could be retrieved
216         // from the metadata
217         Class<?> clazz = Object.class;
218         if (className != null) {
219             clazz = loadClass(className);
220         }
221         return new DynaProperty(name, clazz);
222 
223     }
224 
225     /**
226      * <p>Introspect the metadata associated with our result set, and populate
227      * the <code>properties</code> and <code>propertiesMap</code> instance
228      * variables.</p>
229      *
230      * @param resultSet The <code>resultSet</code> whose metadata is to
231      *  be introspected
232      *
233      * @throws SQLException if an error is encountered processing the
234      *  result set metadata
235      */
236     protected void introspect(final ResultSet resultSet) throws SQLException {
237 
238         // Accumulate an ordered list of DynaProperties
239         final ArrayList<DynaProperty> list = new ArrayList<DynaProperty>();
240         final ResultSetMetaData metadata = resultSet.getMetaData();
241         final int n = metadata.getColumnCount();
242         for (int i = 1; i <= n; i++) { // JDBC is one-relative!
243             final DynaProperty dynaProperty = createDynaProperty(metadata, i);
244             if (dynaProperty != null) {
245                     list.add(dynaProperty);
246             }
247         }
248 
249         // Convert this list into the internal data structures we need
250         properties =
251             list.toArray(new DynaProperty[list.size()]);
252         for (DynaProperty propertie : properties) {
253             propertiesMap.put(propertie.getName(), propertie);
254         }
255 
256     }
257 
258     /**
259      * Get a column value from a {@link ResultSet} for the specified name.
260      *
261      * @param resultSet The result set
262      * @param name The property name
263      * @return The value
264      * @throws SQLException if an error occurs
265      */
266     protected Object getObject(final ResultSet resultSet, final String name) throws SQLException {
267 
268         final DynaProperty property = getDynaProperty(name);
269         if (property == null) {
270             throw new IllegalArgumentException("Invalid name '" + name + "'");
271         }
272         final String columnName = getColumnName(name);
273         final Class<?> type = property.getType();
274 
275         // java.sql.Date
276         if (type.equals(Date.class)) {
277             return resultSet.getDate(columnName);
278         }
279 
280         // java.sql.Timestamp
281         if (type.equals(Timestamp.class)) {
282             return resultSet.getTimestamp(columnName);
283         }
284 
285         // java.sql.Time
286         if (type.equals(Time.class)) {
287             return resultSet.getTime(columnName);
288         }
289 
290         return resultSet.getObject(columnName);
291     }
292 
293     /**
294      * Get the table column name for the specified property name.
295      *
296      * @param name The property name
297      * @return The column name (which can be different if the <i>lowerCase</i>
298      * option is used).
299      */
300     protected String getColumnName(final String name) {
301         if (columnNameXref != null && columnNameXref.containsKey(name)) {
302             return columnNameXref.get(name);
303         } else {
304             return name;
305         }
306     }
307 
308 }