KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > springframework > jdbc > datasource > DriverManagerDataSource


1 /*
2  * Copyright 2002-2006 the original author or authors.
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.springframework.jdbc.datasource;
18
19 import java.sql.Connection JavaDoc;
20 import java.sql.DriverManager JavaDoc;
21 import java.sql.SQLException JavaDoc;
22 import java.util.Properties JavaDoc;
23
24 import org.springframework.jdbc.CannotGetJdbcConnectionException;
25 import org.springframework.util.ClassUtils;
26 import org.springframework.util.StringUtils;
27
28 /**
29  * Simple implementation of the standard JDBC DataSource interface, configuring
30  * a plain old JDBC Driver via bean properties, and returning a new Connection
31  * for every <code>getConnection</code> call.
32  *
33  * <p><b>NOTE: This class is not an actual connection pool; it does not actually
34  * pool Connections.</b> It just serves as simple replacement for a full-blown
35  * connection pool, implementing the same standard interface, but creating new
36  * Connections on every call.
37  *
38  * <p>Useful for test or standalone environments outside of a J2EE container, either
39  * as a DataSource bean in a corresponding ApplicationContext or in conjunction with
40  * a simple JNDI environment. Pool-assuming <code>Connection.close()</code> calls will
41  * simply close the Connection, so any DataSource-aware persistence code should work.
42  *
43  * <p>In a J2EE container, it is recommended to use a JNDI DataSource provided by
44  * the container. Such a DataSource can be exposed as a DataSource bean in a Spring
45  * ApplicationContext via JndiObjectFactoryBean, for seamless switching to and from
46  * a local DataSource bean like this class. For tests, you can then either set up a
47  * mock JNDI environment through Spring's SimpleNamingContextBuilder, or switch the
48  * bean definition to a local DataSource (which is simpler and thus recommended).
49  *
50  * <p>If you need a "real" connection pool outside of a J2EE container, consider
51  * <a HREF="http://jakarta.apache.org/commons/dbcp">Apache's Jakarta Commons DBCP</a>
52  * or <a HREF="http://sourceforge.net/projects/c3p0">C3P0</a>.
53  * Commons DBCP's BasicDataSource and C3P0's ComboPooledDataSource are full
54  * connection pool beans, supporting the same basic properties as this class
55  * plus specific settings (such as minimal/maximal pool size etc).
56  *
57  * <p>Commons DBCP's BasicDataSource can even be used as a direct replacement for an
58  * instance of this class just by changing the class name of the bean definition to
59  * "org.apache.commons.dbcp.BasicDataSource", because the names of all common
60  * properties match exactly. Note that both BasicDataSource and ComboPooledDataSource
61  * should be defined with destroy-method="close", for immediate shutdown when the
62  * Spring ApplicationContext shuts down.
63  *
64  * @author Juergen Hoeller
65  * @since 14.03.2003
66  * @see org.springframework.jndi.JndiObjectFactoryBean
67  * @see org.springframework.mock.jndi.SimpleNamingContextBuilder
68  * @see org.apache.commons.dbcp.BasicDataSource
69  * @see com.mchange.v2.c3p0.ComboPooledDataSource
70  */

71 public class DriverManagerDataSource extends AbstractDataSource {
72
73     private String JavaDoc driverClassName;
74
75     private String JavaDoc url;
76
77     private String JavaDoc username;
78
79     private String JavaDoc password;
80
81     private Properties JavaDoc connectionProperties;
82
83
84     /**
85      * Constructor for bean-style configuration.
86      */

87     public DriverManagerDataSource() {
88     }
89
90     /**
91      * Create a new DriverManagerDataSource with the given standard
92      * DriverManager parameters.
93      * @param driverClassName the JDBC driver class name
94      * @param url the JDBC URL to use for accessing the DriverManager
95      * @param username the JDBC username to use for accessing the DriverManager
96      * @param password the JDBC password to use for accessing the DriverManager
97      * @see java.sql.DriverManager#getConnection(String, String, String)
98      */

99     public DriverManagerDataSource(String JavaDoc driverClassName, String JavaDoc url, String JavaDoc username, String JavaDoc password)
100             throws CannotGetJdbcConnectionException {
101         setDriverClassName(driverClassName);
102         setUrl(url);
103         setUsername(username);
104         setPassword(password);
105     }
106
107     /**
108      * Create a new DriverManagerDataSource with the given standard
109      * DriverManager parameters.
110      * @param url the JDBC URL to use for accessing the DriverManager
111      * @param username the JDBC username to use for accessing the DriverManager
112      * @param password the JDBC password to use for accessing the DriverManager
113      * @see java.sql.DriverManager#getConnection(String, String, String)
114      */

115     public DriverManagerDataSource(String JavaDoc url, String JavaDoc username, String JavaDoc password)
116             throws CannotGetJdbcConnectionException {
117         setUrl(url);
118         setUsername(username);
119         setPassword(password);
120     }
121
122     /**
123      * Create a new DriverManagerDataSource with the given JDBC URL,
124      * not specifying a username or password for JDBC access.
125      * @param url the JDBC URL to use for accessing the DriverManager
126      * @see java.sql.DriverManager#getConnection(String)
127      */

128     public DriverManagerDataSource(String JavaDoc url)
129             throws CannotGetJdbcConnectionException {
130         setUrl(url);
131     }
132
133
134     /**
135      * Set the JDBC driver class name. This driver will get initialized
136      * on startup, registering itself with the JDK's DriverManager.
137      * <p>Alternatively, consider initializing the JDBC driver yourself
138      * before instantiating this DataSource.
139      * @see Class#forName(String)
140      * @see java.sql.DriverManager#registerDriver(java.sql.Driver)
141      */

142     public void setDriverClassName(String JavaDoc driverClassName) throws CannotGetJdbcConnectionException {
143         if (!StringUtils.hasText(driverClassName)) {
144             throw new IllegalArgumentException JavaDoc("driverClassName must not be empty");
145         }
146         this.driverClassName = driverClassName.trim();
147         try {
148             Class.forName(this.driverClassName, true, ClassUtils.getDefaultClassLoader());
149         }
150         catch (ClassNotFoundException JavaDoc ex) {
151             throw new CannotGetJdbcConnectionException(
152                     "Could not load JDBC driver class [" + this.driverClassName + "]", ex);
153         }
154         if (logger.isInfoEnabled()) {
155             logger.info("Loaded JDBC driver: " + this.driverClassName);
156         }
157     }
158
159     /**
160      * Return the JDBC driver class name, if any.
161      */

162     public String JavaDoc getDriverClassName() {
163         return driverClassName;
164     }
165
166     /**
167      * Set the JDBC URL to use for accessing the DriverManager.
168      * @see java.sql.DriverManager#getConnection(String, String, String)
169      */

170     public void setUrl(String JavaDoc url) {
171         if (!StringUtils.hasText(url)) {
172             throw new IllegalArgumentException JavaDoc("url must not be empty");
173         }
174         this.url = url.trim();
175     }
176
177     /**
178      * Return the JDBC URL to use for accessing the DriverManager.
179      */

180     public String JavaDoc getUrl() {
181         return url;
182     }
183
184     /**
185      * Set the JDBC username to use for accessing the DriverManager.
186      * @see java.sql.DriverManager#getConnection(String, String, String)
187      */

188     public void setUsername(String JavaDoc username) {
189         this.username = username;
190     }
191
192     /**
193      * Return the JDBC username to use for accessing the DriverManager.
194      */

195     public String JavaDoc getUsername() {
196         return username;
197     }
198
199     /**
200      * Set the JDBC password to use for accessing the DriverManager.
201      * @see java.sql.DriverManager#getConnection(String, String, String)
202      */

203     public void setPassword(String JavaDoc password) {
204         this.password = password;
205     }
206
207     /**
208      * Return the JDBC password to use for accessing the DriverManager.
209      */

210     public String JavaDoc getPassword() {
211         return password;
212     }
213
214     /**
215      * Specify arbitrary connection properties as key/value pairs,
216      * to be passed to the DriverManager.
217      * <p>Can also contain "user" and "password" properties. However,
218      * any "username" and "password" bean properties specified on this
219      * DataSource will override the corresponding connection properties.
220      * @see java.sql.DriverManager#getConnection(String, java.util.Properties)
221      */

222     public void setConnectionProperties(Properties JavaDoc connectionProperties) {
223         this.connectionProperties = connectionProperties;
224     }
225
226     /**
227      * Return the connection properties to be passed to the DriverManager, if any.
228      */

229     public Properties JavaDoc getConnectionProperties() {
230         return connectionProperties;
231     }
232
233
234     /**
235      * This implementation delegates to <code>getConnectionFromDriverManager</code>,
236      * using the default username and password of this DataSource.
237      * @see #getConnectionFromDriverManager()
238      */

239     public Connection JavaDoc getConnection() throws SQLException JavaDoc {
240         return getConnectionFromDriverManager();
241     }
242
243     /**
244      * This implementation delegates to <code>getConnectionFromDriverManager</code>,
245      * using the given username and password.
246      * @see #getConnectionFromDriverManager(String, String)
247      */

248     public Connection JavaDoc getConnection(String JavaDoc username, String JavaDoc password) throws SQLException JavaDoc {
249         return getConnectionFromDriverManager(username, password);
250     }
251
252
253     /**
254      * Get a Connection from the DriverManager,
255      * using the default username and password of this DataSource.
256      * @see #getConnectionFromDriverManager(String, String)
257      */

258     protected Connection JavaDoc getConnectionFromDriverManager() throws SQLException JavaDoc {
259         return getConnectionFromDriverManager(getUsername(), getPassword());
260     }
261
262     /**
263      * Build properties for the DriverManager, including the given username
264      * and password (if any).
265      * @see #getConnectionFromDriverManager(String, java.util.Properties)
266      */

267     protected Connection JavaDoc getConnectionFromDriverManager(String JavaDoc username, String JavaDoc password)
268         throws SQLException JavaDoc {
269
270         Properties JavaDoc props = new Properties JavaDoc(getConnectionProperties());
271         if (username != null) {
272             props.setProperty("user", username);
273         }
274         if (password != null) {
275             props.setProperty("password", password);
276         }
277         return getConnectionFromDriverManager(getUrl(), props);
278     }
279
280     /**
281      * Getting a connection using the nasty static from DriverManager is extracted
282      * into a protected method to allow for easy unit testing.
283      * @see java.sql.DriverManager#getConnection(String, java.util.Properties)
284      */

285     protected Connection JavaDoc getConnectionFromDriverManager(String JavaDoc url, Properties JavaDoc props)
286         throws SQLException JavaDoc {
287
288         if (logger.isDebugEnabled()) {
289             logger.debug("Creating new JDBC Connection to [" + url + "]");
290         }
291         return DriverManager.getConnection(url, props);
292     }
293
294 }
295
Popular Tags