KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > sape > carbon > services > sqldataloader > total > SqlBeanDataLoader


1 /*
2  * The contents of this file are subject to the Sapient Public License
3  * Version 1.0 (the "License"); you may not use this file except in compliance
4  * with the License. You may obtain a copy of the License at
5  * http://carbon.sf.net/License.html.
6  *
7  * Software distributed under the License is distributed on an "AS IS" basis,
8  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
9  * the specific language governing rights and limitations under the License.
10  *
11  * The Original Code is The Carbon Component Framework.
12  *
13  * The Initial Developer of the Original Code is Sapient Corporation
14  *
15  * Copyright (C) 2003 Sapient Corporation. All Rights Reserved.
16  */

17
18 package org.sape.carbon.services.sqldataloader.total;
19
20 import org.apache.commons.logging.Log;
21 import org.apache.commons.logging.LogFactory;
22
23 import java.lang.reflect.Constructor JavaDoc;
24 import java.lang.reflect.InvocationTargetException JavaDoc;
25 import java.sql.Connection JavaDoc;
26 import java.sql.PreparedStatement JavaDoc;
27 import java.sql.ResultSet JavaDoc;
28 import java.sql.SQLException JavaDoc;
29 import java.util.Comparator JavaDoc;
30 import java.util.Iterator JavaDoc;
31 import java.util.Map JavaDoc;
32 import java.util.Set JavaDoc;
33
34 import org.sape.carbon.core.component.ComponentConfiguration;
35 import org.sape.carbon.core.component.lifecycle.Configurable;
36 import org.sape.carbon.core.config.InvalidConfigurationException;
37 import org.sape.carbon.core.util.reflection.BeanUtil;
38 import org.sape.carbon.services.cache.CacheLoadException;
39 import org.sape.carbon.services.cache.total.ConfigurableMapTypeCacheDataLoader;
40
41
42 /**
43  * <p>Class provides a generic lookup class to users with a mechanism to cache
44  * data retreived from a table. The object containing the data, query
45  * retreiving the data and the key for the cache are all configurable
46  * propertied read from the component configuration file.
47  * </p>
48  *
49  * <p> It reads the data from database using the configured query and loads
50  * it into Javabean objects which are then stored in cache. </p>
51  * @see SqlBeanDataLoaderConfiguration
52  *
53  * Copyright 2003 Sapient
54  * @since carbon 2.1
55  * @author Akash Tayal, May 2003
56  * @version $Revision: 1.1 $($Author: ghinkl $ / $Date: 2003/09/30 02:08:19 $)
57  */

58 public class SqlBeanDataLoader implements ConfigurableMapTypeCacheDataLoader,
59     Configurable {
60
61     /** The handle to Apache-commons logger */
62     private Log log = LogFactory.getLog(this.getClass());
63
64     /** Reference to configuration document */
65     protected SqlBeanDataLoaderConfiguration config = null;
66
67
68     /**
69      * Configure the component. This is preceded and followed by the suspend
70      * and resume operations if they are available on the component.
71      *
72      * @param configuration A GenericTotalCacheDataLoaderConfiguration
73      */

74     public void configure(ComponentConfiguration configuration) {
75         this.config = (SqlBeanDataLoaderConfiguration) configuration;
76     }
77
78     /**
79      * <p>Creates and executes the PreparedStatement to retrieve data from
80      * database. This method abstracts out the creation and execution of SQL
81      * statement. </p>
82      * <p> You can extend this class and provide implementation for this
83      * method in case you want to retrieve data using callable statement.
84      * </p>
85      *
86      * @param connection Connection to the database
87      * @return ResultSet of retrieved data
88      * @throws CacheLoadException in case there is some error in loading
89      * the data
90      */

91     protected ResultSet JavaDoc retrieveResult(Connection JavaDoc connection)
92         throws SQLException JavaDoc {
93
94         PreparedStatement JavaDoc preparedStatement =
95             connection.prepareStatement(config.getDataLoadQuery());
96         ResultSet JavaDoc resultSet = preparedStatement.executeQuery();
97         return resultSet;
98     }
99
100     /**
101      * <p>Loads the cache with data elements.
102      * Executes the configured SQL query and loads the data into
103      * configured bean. </p>
104      *
105      * <p>Reads the configuration to retrieve a map of db columns and bean
106      * attributes. Reads the value for each column from database and populates
107      * it into the mapping bean attributes. </p>
108      *
109      * @return Map of cached data
110      * @throws CacheLoadException in case there is some error in loading
111      * the data
112      */

113     public Map JavaDoc loadAllData() throws CacheLoadException {
114         Connection JavaDoc connection = null;
115         String JavaDoc beanAttributeName = null;
116         try {
117
118             // Obtaining the connection
119
connection = (config.getConnectionFactory()).getConnection();
120
121             // Retrieving the result from database
122
ResultSet JavaDoc resultSet = retrieveResult(connection);
123
124             // Creating the map based on implmentation provided
125
Map JavaDoc returnMap = getMapInstance();
126
127             // Reading the mapping of db column name to bean attribute
128
Set JavaDoc attributeSet = (config.getBeanAttribute()).entrySet();
129
130             while (resultSet.next()) {
131                 Object JavaDoc key = resultSet.getObject(config.getKeyColumn());
132                 Object JavaDoc bean;
133                 try {
134                     bean = (config.getBeanClass()).newInstance();
135                 } catch (IllegalAccessException JavaDoc iae) {
136                     throw new InvalidConfigurationException(this.getClass(),
137                         this.config.getConfigurationName(), "BeanClass",
138                         "Could not create instance of lookup bean", iae);
139                 } catch (InstantiationException JavaDoc ie) {
140                     throw new InvalidConfigurationException(this.getClass(),
141                         this.config.getConfigurationName(), "BeanClass",
142                         "Could not create instance of lookup bean", ie);
143                 }
144                 // Reading each column name from map and retrieving value
145
// from the row of result set.
146
Iterator JavaDoc attributeIterator = attributeSet.iterator();
147
148                 while (attributeIterator.hasNext()) {
149                     Map.Entry JavaDoc attribute = (Map.Entry JavaDoc) attributeIterator.next();
150                     String JavaDoc columnName = (String JavaDoc) attribute.getKey();
151                     beanAttributeName = (String JavaDoc) attribute.getValue();
152                     log.info("BEAN DATA LOADER COLUMN NAME IS " + columnName);
153                     log.info("BEAN DATA LOADER ATTRIBUTE NAME IS " + beanAttributeName);
154                     log.info("DATA TYPE OF COLUMN IS " + resultSet.getObject(columnName).getClass());
155                     BeanUtil.setObjectAttribute(bean,
156                         beanAttributeName,
157                         resultSet.getObject(columnName));
158                 }
159                 returnMap.put(key,bean);
160             }
161             return returnMap;
162         } catch (IllegalArgumentException JavaDoc iarge) {
163             throw new InvalidConfigurationException(this.getClass(),
164                 this.config.getConfigurationName(), "BeanAttribute",
165                 "Bean attribute type for " + beanAttributeName
166                 + " and db column type do not match", iarge);
167         } catch (IllegalAccessException JavaDoc iae) {
168             throw new InvalidConfigurationException(this.getClass(),
169                 this.config.getConfigurationName(), "BeanAttribute",
170                 "Could not set attribute " + beanAttributeName
171                 + " in bean class", iae);
172         } catch (NoSuchMethodException JavaDoc nsme) {
173             throw new InvalidConfigurationException(this.getClass(),
174                 this.config.getConfigurationName(), "BeanAttribute",
175                 "Could not set attribute " + beanAttributeName
176                 + " in bean class", nsme);
177         } catch (InvocationTargetException JavaDoc ite) {
178             throw new InvalidConfigurationException(this.getClass(),
179                 this.config.getConfigurationName(), "BeanAttribute",
180                 "Could not set attribute " + beanAttributeName
181                 + " in bean class", ite);
182         } catch (SQLException JavaDoc sqle) {
183             throw new CacheLoadException(getClass(),
184                 "Could not load Cache from database" , sqle);
185         } finally {
186             if (connection != null) {
187                 try {
188                     connection.close();
189                 } catch (SQLException JavaDoc sqle) {
190                     // eating the exception
191
}
192             }
193         }
194     }
195
196     /**
197      * <p>Returns an instance of configured map implementation.
198      * This method just returns a new and blank instance.
199      * In case comparator is defined for the map, the appropriate
200      * constructor of the map implementation is used to create the
201      * new instance. </p>
202      * <p> Please note that the new map instance is not synchronized in
203      * this method. As required the synchronization takes place in the
204      * <code>WritableCache</code> </p>
205      *
206      * @return Map instance
207      */

208     public Map JavaDoc getMapInstance() {
209
210         Map JavaDoc returnMap;
211         // if comparator implementation to be used is specified
212
if (this.config.getComparator() != null) {
213             Class JavaDoc[] constructorParameters = new Class JavaDoc[]
214                 {Comparator JavaDoc.class};
215             Object JavaDoc[] constructorArguments;
216             try {
217                 constructorArguments = new Object JavaDoc[]
218                     {(config.getComparator()).newInstance()};
219             } catch (IllegalAccessException JavaDoc iae) {
220                 throw new InvalidConfigurationException(this.getClass(),
221                     this.config.getConfigurationName(), "Comparator",
222                     "Could not instantiate comparator instance", iae);
223             } catch (InstantiationException JavaDoc ie) {
224                 throw new InvalidConfigurationException(this.getClass(),
225                     this.config.getConfigurationName(), "Comparator",
226                     "Could not instantiate comparator instance", ie);
227             }
228             try {
229                 Constructor JavaDoc constr = (config.getMapType()).getConstructor(
230                     constructorParameters);
231                 returnMap = (Map JavaDoc)
232                     constr.newInstance(constructorArguments);
233             } catch (IllegalAccessException JavaDoc iae) {
234                 throw new InvalidConfigurationException(this.getClass(),
235                     this.config.getConfigurationName(), "MapType",
236                     "Could not instantiate map instance", iae);
237             } catch (NoSuchMethodException JavaDoc nsme) {
238                 throw new InvalidConfigurationException(this.getClass(),
239                     this.config.getConfigurationName(), "MapType",
240                     "Could not instantiate map instance", nsme);
241             } catch (InstantiationException JavaDoc ie) {
242                 throw new InvalidConfigurationException(this.getClass(),
243                     this.config.getConfigurationName(), "MapType",
244                     "Could not instantiate map instance", ie);
245             } catch (InvocationTargetException JavaDoc ite) {
246                 throw new InvalidConfigurationException(this.getClass(),
247                     this.config.getConfigurationName(), "MapType",
248                     "Could not instantiate map instance", ite);
249             }
250         } else {
251             // No Comparator implementation was specified
252
try {
253                 if (log.isTraceEnabled()) {
254                     log.trace("No Comparator implementation was provided. " +
255                         "Creating map instance without comparator of type " +
256                         config.getMapType().getName());
257                 }
258                 returnMap = (Map JavaDoc) (config.getMapType()).newInstance();
259             } catch (IllegalAccessException JavaDoc iae) {
260                 throw new InvalidConfigurationException(this.getClass(),
261                     this.config.getConfigurationName(), "MapType",
262                     "Could not instantiate map instance", iae);
263             } catch (InstantiationException JavaDoc ie) {
264                 throw new InvalidConfigurationException(this.getClass(),
265                     this.config.getConfigurationName(), "MapType",
266                     "Could not instantiate map instance", ie);
267             }
268         }
269         return returnMap;
270     }
271
272 }
Popular Tags