KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > commons > dbcp > BasicDataSourceFactory


1 /*
2  * Copyright 1999-2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package org.apache.commons.dbcp;
18
19 import java.io.ByteArrayInputStream JavaDoc;
20 import java.sql.Connection JavaDoc;
21 import java.util.Enumeration JavaDoc;
22 import java.util.Hashtable JavaDoc;
23 import java.util.Properties JavaDoc;
24
25 import javax.naming.Context JavaDoc;
26 import javax.naming.Name JavaDoc;
27 import javax.naming.RefAddr JavaDoc;
28 import javax.naming.Reference JavaDoc;
29 import javax.naming.spi.ObjectFactory JavaDoc;
30 import javax.sql.DataSource JavaDoc;
31
32 /**
33  * <p>JNDI object factory that creates an instance of
34  * <code>BasicDataSource</code> that has been configured based on the
35  * <code>RefAddr</code> values of the specified <code>Reference</code>,
36  * which must match the names and data types of the
37  * <code>BasicDataSource</code> bean properties.</p>
38  *
39  * @author Craig R. McClanahan
40  * @author Dirk Verbeeck
41  * @version $Revision: 1.15 $ $Date: 2004/02/28 11:48:04 $
42  */

43 public class BasicDataSourceFactory implements ObjectFactory JavaDoc {
44
45     private final static String JavaDoc PROP_DEFAULTAUTOCOMMIT = "defaultAutoCommit";
46     private final static String JavaDoc PROP_DEFAULTREADONLY = "defaultReadOnly";
47     private final static String JavaDoc PROP_DEFAULTTRANSACTIONISOLATION = "defaultTransactionIsolation";
48     private final static String JavaDoc PROP_DEFAULTCATALOG = "defaultCatalog";
49     private final static String JavaDoc PROP_DRIVERCLASSNAME = "driverClassName";
50     private final static String JavaDoc PROP_MAXACTIVE = "maxActive";
51     private final static String JavaDoc PROP_MAXIDLE = "maxIdle";
52     private final static String JavaDoc PROP_MINIDLE = "minIdle";
53     private final static String JavaDoc PROP_INITIALSIZE = "initialSize";
54     private final static String JavaDoc PROP_MAXWAIT = "maxWait";
55     private final static String JavaDoc PROP_TESTONBORROW = "testOnBorrow";
56     private final static String JavaDoc PROP_TESTONRETURN = "testOnReturn";
57     private final static String JavaDoc PROP_TIMEBETWEENEVICTIONRUNSMILLIS = "timeBetweenEvictionRunsMillis";
58     private final static String JavaDoc PROP_NUMTESTSPEREVICTIONRUN = "numTestsPerEvictionRun";
59     private final static String JavaDoc PROP_MINEVICTABLEIDLETIMEMILLIS = "minEvictableIdleTimeMillis";
60     private final static String JavaDoc PROP_TESTWHILEIDLE = "testWhileIdle";
61     private final static String JavaDoc PROP_PASSWORD = "password";
62     private final static String JavaDoc PROP_URL = "url";
63     private final static String JavaDoc PROP_USERNAME = "username";
64     private final static String JavaDoc PROP_VALIDATIONQUERY = "validationQuery";
65     private final static String JavaDoc PROP_ACCESSTOUNDERLYINGCONNECTIONALLOWED = "accessToUnderlyingConnectionAllowed";
66     private final static String JavaDoc PROP_REMOVEABANDONED = "removeAbandoned";
67     private final static String JavaDoc PROP_REMOVEABANDONEDTIMEOUT = "removeAbandonedTimeout";
68     private final static String JavaDoc PROP_LOGABANDONED = "logAbandoned";
69     private final static String JavaDoc PROP_POOLPREPAREDSTATEMENTS = "poolPreparedStatements";
70     private final static String JavaDoc PROP_MAXOPENPREPAREDSTATEMENTS = "maxOpenPreparedStatements";
71     private final static String JavaDoc PROP_CONNECTIONPROPERTIES = "connectionProperties";
72
73     private final static String JavaDoc[] ALL_PROPERTIES = {
74         PROP_DEFAULTAUTOCOMMIT,
75         PROP_DEFAULTREADONLY,
76         PROP_DEFAULTTRANSACTIONISOLATION,
77         PROP_DEFAULTCATALOG,
78         PROP_DRIVERCLASSNAME,
79         PROP_MAXACTIVE,
80         PROP_MAXIDLE,
81         PROP_MINIDLE,
82         PROP_INITIALSIZE,
83         PROP_MAXWAIT,
84         PROP_TESTONBORROW,
85         PROP_TESTONRETURN,
86         PROP_TIMEBETWEENEVICTIONRUNSMILLIS,
87         PROP_NUMTESTSPEREVICTIONRUN,
88         PROP_MINEVICTABLEIDLETIMEMILLIS,
89         PROP_TESTWHILEIDLE,
90         PROP_PASSWORD,
91         PROP_URL,
92         PROP_USERNAME,
93         PROP_VALIDATIONQUERY,
94         PROP_ACCESSTOUNDERLYINGCONNECTIONALLOWED,
95         PROP_REMOVEABANDONED,
96         PROP_REMOVEABANDONEDTIMEOUT,
97         PROP_LOGABANDONED,
98         PROP_POOLPREPAREDSTATEMENTS,
99         PROP_MAXOPENPREPAREDSTATEMENTS,
100         PROP_CONNECTIONPROPERTIES
101     };
102
103     // -------------------------------------------------- ObjectFactory Methods
104

105     /**
106      * <p>Create and return a new <code>BasicDataSource</code> instance. If no
107      * instance can be created, return <code>null</code> instead.</p>
108      *
109      * @param obj The possibly null object containing location or
110      * reference information that can be used in creating an object
111      * @param name The name of this object relative to <code>nameCtx</code>
112      * @param nameCts The context relative to which the <code>name</code>
113      * parameter is specified, or <code>null</code> if <code>name</code>
114      * is relative to the default initial context
115      * @param environment The possibly null environment that is used in
116      * creating this object
117      *
118      * @exception Exception if an exception occurs creating the instance
119      */

120     public Object JavaDoc getObjectInstance(Object JavaDoc obj, Name JavaDoc name, Context JavaDoc nameCtx,
121                                     Hashtable JavaDoc environment)
122         throws Exception JavaDoc {
123
124         // We only know how to deal with <code>javax.naming.Reference</code>s
125
// that specify a class name of "javax.sql.DataSource"
126
if ((obj == null) || !(obj instanceof Reference JavaDoc)) {
127             return null;
128         }
129         Reference JavaDoc ref = (Reference JavaDoc) obj;
130         if (!"javax.sql.DataSource".equals(ref.getClassName())) {
131             return null;
132         }
133
134         Properties JavaDoc properties = new Properties JavaDoc();
135         for (int i = 0 ; i < ALL_PROPERTIES.length ; i++) {
136             String JavaDoc propertyName = ALL_PROPERTIES[i];
137             RefAddr JavaDoc ra = ref.get(propertyName);
138             if (ra != null) {
139                 String JavaDoc propertyValue = ra.getContent().toString();
140                 properties.setProperty(propertyName, propertyValue);
141             }
142         }
143
144         return createDataSource(properties);
145     }
146
147     /**
148      * Creates and configures a BasicDataSource instance based on the
149      * given properties.
150      */

151     public static DataSource JavaDoc createDataSource(Properties JavaDoc properties) throws Exception JavaDoc {
152         BasicDataSource dataSource = new BasicDataSource();
153         String JavaDoc value = null;
154
155         value = properties.getProperty(PROP_DEFAULTAUTOCOMMIT);
156         if (value != null) {
157             dataSource.setDefaultAutoCommit(Boolean.valueOf(value).booleanValue());
158         }
159
160         value = properties.getProperty(PROP_DEFAULTREADONLY);
161         if (value != null) {
162             dataSource.setDefaultReadOnly(Boolean.valueOf(value).booleanValue());
163         }
164
165         value = properties.getProperty(PROP_DEFAULTTRANSACTIONISOLATION);
166         if (value != null) {
167             int level = PoolableConnectionFactory.UNKNOWN_TRANSACTIONISOLATION;
168             if ("NONE".equalsIgnoreCase(value)) {
169                 level = Connection.TRANSACTION_NONE;
170             }
171             else if ("READ_COMMITTED".equalsIgnoreCase(value)) {
172                 level = Connection.TRANSACTION_READ_COMMITTED;
173             }
174             else if ("READ_UNCOMMITTED".equalsIgnoreCase(value)) {
175                 level = Connection.TRANSACTION_READ_UNCOMMITTED;
176             }
177             else if ("REPEATABLE_READ".equalsIgnoreCase(value)) {
178                 level = Connection.TRANSACTION_REPEATABLE_READ;
179             }
180             else if ("SERIALIZABLE".equalsIgnoreCase(value)) {
181                 level = Connection.TRANSACTION_SERIALIZABLE;
182             }
183             else {
184                 try {
185                     level = Integer.parseInt(value);
186                 } catch (NumberFormatException JavaDoc e) {
187                     System.err.println("Could not parse defaultTransactionIsolation: " + value);
188                     System.err.println("WARNING: defaultTransactionIsolation not set");
189                     System.err.println("using default value of database driver");
190                     level = PoolableConnectionFactory.UNKNOWN_TRANSACTIONISOLATION;
191                 }
192             }
193             dataSource.setDefaultTransactionIsolation(level);
194         }
195
196         value = properties.getProperty(PROP_DEFAULTCATALOG);
197         if (value != null) {
198             dataSource.setDefaultCatalog(value);
199         }
200
201         value = properties.getProperty(PROP_DRIVERCLASSNAME);
202         if (value != null) {
203             dataSource.setDriverClassName(value);
204         }
205
206         value = properties.getProperty(PROP_MAXACTIVE);
207         if (value != null) {
208             dataSource.setMaxActive(Integer.parseInt(value));
209         }
210
211         value = properties.getProperty(PROP_MAXIDLE);
212         if (value != null) {
213             dataSource.setMaxIdle(Integer.parseInt(value));
214         }
215
216         value = properties.getProperty(PROP_MINIDLE);
217         if (value != null) {
218             dataSource.setMinIdle(Integer.parseInt(value));
219         }
220
221         value = properties.getProperty(PROP_INITIALSIZE);
222         if (value != null) {
223             dataSource.setInitialSize(Integer.parseInt(value));
224         }
225
226         value = properties.getProperty(PROP_MAXWAIT);
227         if (value != null) {
228             dataSource.setMaxWait(Long.parseLong(value));
229         }
230
231         value = properties.getProperty(PROP_TESTONBORROW);
232         if (value != null) {
233             dataSource.setTestOnBorrow(Boolean.valueOf(value).booleanValue());
234         }
235
236         value = properties.getProperty(PROP_TESTONRETURN);
237         if (value != null) {
238             dataSource.setTestOnReturn(Boolean.valueOf(value).booleanValue());
239         }
240
241         value = properties.getProperty(PROP_TIMEBETWEENEVICTIONRUNSMILLIS);
242         if (value != null) {
243             dataSource.setTimeBetweenEvictionRunsMillis(Long.parseLong(value));
244         }
245
246         value = properties.getProperty(PROP_NUMTESTSPEREVICTIONRUN);
247         if (value != null) {
248             dataSource.setNumTestsPerEvictionRun(Integer.parseInt(value));
249         }
250
251         value = properties.getProperty(PROP_MINEVICTABLEIDLETIMEMILLIS);
252         if (value != null) {
253             dataSource.setMinEvictableIdleTimeMillis(Long.parseLong(value));
254         }
255
256         value = properties.getProperty(PROP_TESTWHILEIDLE);
257         if (value != null) {
258             dataSource.setTestWhileIdle(Boolean.valueOf(value).booleanValue());
259         }
260
261         value = properties.getProperty(PROP_PASSWORD);
262         if (value != null) {
263             dataSource.setPassword(value);
264         }
265
266         value = properties.getProperty(PROP_URL);
267         if (value != null) {
268             dataSource.setUrl(value);
269         }
270
271         value = properties.getProperty(PROP_USERNAME);
272         if (value != null) {
273             dataSource.setUsername(value);
274         }
275
276         value = properties.getProperty(PROP_VALIDATIONQUERY);
277         if (value != null) {
278             dataSource.setValidationQuery(value);
279         }
280
281         value = properties.getProperty(PROP_ACCESSTOUNDERLYINGCONNECTIONALLOWED);
282         if (value != null) {
283             dataSource.setAccessToUnderlyingConnectionAllowed(Boolean.valueOf(value).booleanValue());
284         }
285
286         value = properties.getProperty(PROP_REMOVEABANDONED);
287         if (value != null) {
288             dataSource.setRemoveAbandoned(Boolean.valueOf(value).booleanValue());
289         }
290
291         value = properties.getProperty(PROP_REMOVEABANDONEDTIMEOUT);
292         if (value != null) {
293             dataSource.setRemoveAbandonedTimeout(Integer.parseInt(value));
294         }
295
296         value = properties.getProperty(PROP_LOGABANDONED);
297         if (value != null) {
298             dataSource.setLogAbandoned(Boolean.valueOf(value).booleanValue());
299         }
300
301         value = properties.getProperty(PROP_POOLPREPAREDSTATEMENTS);
302         if (value != null) {
303             dataSource.setPoolPreparedStatements(Boolean.valueOf(value).booleanValue());
304         }
305
306         value = properties.getProperty(PROP_MAXOPENPREPAREDSTATEMENTS);
307         if (value != null) {
308             dataSource.setMaxOpenPreparedStatements(Integer.parseInt(value));
309         }
310
311         value = properties.getProperty(PROP_CONNECTIONPROPERTIES);
312         if (value != null) {
313           Properties JavaDoc p = getProperties(value);
314           Enumeration JavaDoc e = p.propertyNames();
315           while (e.hasMoreElements()) {
316             String JavaDoc propertyName = (String JavaDoc) e.nextElement();
317             dataSource.addConnectionProperty(propertyName, p.getProperty(propertyName));
318           }
319         }
320
321         // Return the configured DataSource instance
322
return dataSource;
323     }
324
325     /**
326      * <p>Parse properties from the string. Format of the string must be [propertyName=property;]*<p>
327      * @param propText
328      * @return Properties
329      * @throws Exception
330      */

331     static private Properties JavaDoc getProperties(String JavaDoc propText) throws Exception JavaDoc {
332       Properties JavaDoc p = new Properties JavaDoc();
333       if (propText != null) {
334         p.load(new ByteArrayInputStream JavaDoc(propText.replace(';', '\n').getBytes()));
335       }
336       return p;
337     }
338 }
339
Popular Tags