KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > sape > carbon > services > sqldataloader > mru > SqlBeanMapMRUDataLoader


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.mru;
19
20
21 import org.apache.commons.logging.Log;
22 import org.apache.commons.logging.LogFactory;
23
24 import java.lang.reflect.Constructor JavaDoc;
25 import java.lang.reflect.InvocationTargetException JavaDoc;
26 import java.sql.Connection JavaDoc;
27 import java.sql.PreparedStatement JavaDoc;
28 import java.sql.ResultSet JavaDoc;
29 import java.sql.SQLException JavaDoc;
30 import java.util.Comparator JavaDoc;
31 import java.util.Iterator JavaDoc;
32 import java.util.Map JavaDoc;
33 import java.util.Set JavaDoc;
34
35 import org.sape.carbon.core.component.ComponentConfiguration;
36 import org.sape.carbon.core.component.lifecycle.Configurable;
37 import org.sape.carbon.core.config.InvalidConfigurationException;
38 import org.sape.carbon.core.util.reflection.BeanUtil;
39 import org.sape.carbon.services.cache.CacheLoadException;
40 import org.sape.carbon.services.cache.mru.MRUCacheDataLoader;
41
42 /**
43  * <p>Class provides a generic lookup class to users with a mechanism to cache
44  * data retreived from a table. The map implementation and object containing
45  * the data and the query retreiving the data 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 loaded into a map then stored in cache.
51  * </p>
52  * @see SqlBeanMapMRUDataLoaderConfiguration
53  *
54  * Copyright 2003 Sapient
55  * @since carbon 2.1
56  * @author Akash Tayal, May 2003
57  * @version $Revision: 1.1 $($Author: ghinkl $ / $Date: 2003/09/30 02:08:19 $)
58  */

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

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

93     protected ResultSet JavaDoc retrieveResult(Connection JavaDoc connection, Object JavaDoc key)
94         throws SQLException JavaDoc {
95
96         PreparedStatement JavaDoc preparedStatement =
97             connection.prepareStatement(config.getDataLoadQuery());
98         preparedStatement.setObject(1,key);
99         ResultSet JavaDoc resultSet = preparedStatement.executeQuery();
100         return resultSet;
101     }
102
103     /**
104      * <p>Loads the Object corresponding to the particular key supplied.
105      * Executes the configured SQL query, loads the data into
106      * configured map implementation and returns the loaded map </p>
107      *
108      * <p> Reads data from database into configured java bean and stores
109      * the bean in the map implementation configured. This map is returned
110      * by the method as a value to the cache.
111      * </p>
112      *
113      * @param key that identifies the returned object in the cache
114      * @return Object contains map of data
115      * @throws CacheLoadException in case there is some error in loading
116      * the data
117      */

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

208     protected 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.getValueMapType()).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(), "ValueMapType",
236                     "Could not instantiate map instance", iae);
237             } catch (NoSuchMethodException JavaDoc nsme) {
238                 throw new InvalidConfigurationException(this.getClass(),
239                     this.config.getConfigurationName(), "ValueMapType",
240                     "Could not instantiate map instance", nsme);
241             } catch (InstantiationException JavaDoc ie) {
242                 throw new InvalidConfigurationException(this.getClass(),
243                     this.config.getConfigurationName(), "ValueMapType",
244                     "Could not instantiate map instance", ie);
245             } catch (InvocationTargetException JavaDoc ite) {
246                 throw new InvalidConfigurationException(this.getClass(),
247                     this.config.getConfigurationName(), "ValueMapType",
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 value map instance without comparator of type " +
256                         config.getValueMapType().getName());
257                 }
258                 returnMap = (Map JavaDoc) (config.getValueMapType()).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