KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > avalon > excalibur > datasource > JdbcDataSource


1 /*
2  * Copyright (C) The Apache Software Foundation. All rights reserved.
3  *
4  * This software is published under the terms of the Apache Software License
5  * version 1.1, a copy of which has been included with this distribution in
6  * the LICENSE.txt file.
7  */

8 package org.apache.avalon.excalibur.datasource;
9
10 import java.sql.Connection JavaDoc;
11 import java.sql.SQLException JavaDoc;
12 import org.apache.avalon.framework.activity.Disposable;
13 import org.apache.avalon.framework.configuration.Configuration;
14 import org.apache.avalon.framework.configuration.ConfigurationException;
15 import org.apache.avalon.framework.logger.AbstractLogEnabled;
16 import org.apache.avalon.framework.logger.LogKitLogger;
17 import org.apache.avalon.framework.logger.Loggable;
18 import org.apache.avalon.excalibur.pool.DefaultPoolController;
19
20 /**
21  * The Default implementation for DataSources in Avalon. This uses the
22  * normal <code>java.sql.Connection</code> object and
23  * <code>java.sql.DriverManager</code>. The Configuration is like this:
24  *
25  * <pre>
26  * &lt;jdbc&gt;
27  * &lt;pool-controller min="<i>5</i>" max="<i>10</i>" connection-class="<i>my.overrided.ConnectionClass</i>"&gt;
28  * &lt;keep-alive disable="false"&gt;select 1&lt;/keep-alive&gt;
29  * &lt;/pool-controller&gt;
30  * &lt;driver&gt;<i>com.database.jdbc.JdbcDriver</i>&lt;/driver&gt;
31  * &lt;dburl&gt;<i>jdbc:driver://host/mydb</i>&lt;/dburl&gt;
32  * &lt;user&gt;<i>username</i>&lt;/user&gt;
33  * &lt;password&gt;<i>password</i>&lt;/password&gt;
34  * &lt;/jdbc&gt;
35  * </pre>
36  *
37  * @author <a HREF="mailto:bloritsch@apache.org">Berin Loritsch</a>
38  * @version CVS $Revision: 1.14 $ $Date: 2002/01/26 16:58:06 $
39  * @since 4.0
40  */

41 public class JdbcDataSource
42     extends AbstractLogEnabled
43     implements DataSourceComponent, Disposable, Loggable
44 {
45     protected JdbcConnectionPool m_pool;
46
47     public void setLogger( final org.apache.log.Logger logger )
48     {
49         enableLogging( new LogKitLogger( logger ) );
50     }
51
52     /**
53      * Configure and set up DB connection. Here we set the connection
54      * information needed to create the Connection objects. It must
55      * be called only once.
56      *
57      * @param conf The Configuration object needed to describe the
58      * connection.
59      *
60      * @throws ConfigurationException
61      */

62     public void configure( final Configuration configuration )
63         throws ConfigurationException
64     {
65         if( null == m_pool )
66         {
67             final String JavaDoc driver = configuration.getChild( "driver" ).getValue("");
68             final String JavaDoc dburl = configuration.getChild( "dburl" ).getValue();
69             final String JavaDoc user = configuration.getChild( "user" ).getValue( null );
70             final String JavaDoc passwd = configuration.getChild( "password" ).getValue( null );
71             final Configuration controller = configuration.getChild( "pool-controller" );
72             String JavaDoc keepAlive = controller.getChild( "keep-alive" ).getValue( "SELECT 1" );
73             final boolean disableKeepAlive = controller.getChild( "keep-alive" ).getAttributeAsBoolean( "disable", false );
74
75             final int min = controller.getAttributeAsInteger( "min", 1 );
76             final int max = controller.getAttributeAsInteger( "max", 3 );
77             final long timeout = controller.getAttributeAsLong( "timeout", -1 );
78             final boolean autoCommit = configuration.getChild("auto-commit").getValueAsBoolean(true);
79             final boolean oradb = controller.getAttributeAsBoolean( "oradb", false );
80             // Get the JdbcConnection class. The factory will resolve one if null.
81
final String JavaDoc connectionClass = controller.getAttribute( "connection-class", null );
82
83             final int l_max;
84             final int l_min;
85
86             // If driver is specified....
87
if ( ! "".equals(driver) )
88             {
89                 if (getLogger().isDebugEnabled())
90                 {
91                     getLogger().debug("Loading new driver: " + driver);
92                 }
93
94                 try
95                 {
96                     Class.forName( driver, true, Thread.currentThread().getContextClassLoader() );
97                 }
98                 catch (ClassNotFoundException JavaDoc cnfe)
99                 {
100                     if (getLogger().isWarnEnabled())
101                     {
102                         getLogger().warn( "Could not load driver: " + driver, cnfe );
103                     }
104                 }
105             }
106
107             // Validate the min and max pool size values.
108
if ( min < 1 )
109             {
110                 if (getLogger().isWarnEnabled())
111                 {
112                     getLogger().warn( "Minumum number of connections specified must be at least 1." );
113                 }
114
115                 l_min = 1;
116             }
117             else
118             {
119                 l_min = min;
120             }
121
122             if( max < 1 )
123             {
124                 if (getLogger().isWarnEnabled())
125                 {
126                     getLogger().warn( "Maximum number of connections specified must be at least 1." );
127                 }
128
129                 l_max = 1;
130             }
131             else
132             {
133                 if ( max < min )
134                 {
135                     if (getLogger().isWarnEnabled())
136                     {
137                         getLogger().warn( "Maximum number of connections specified must be " +
138                                           "more than the minimum number of connections." );
139                     }
140
141                     l_max = min + 1;
142                 }
143                 else
144                 {
145                     l_max = max;
146                 }
147             }
148             
149             // If the keepAlive disable attribute was set, then set the keepAlive query to null, disabling it.
150
if (disableKeepAlive)
151             {
152                 keepAlive = null;
153             }
154
155             // If the oradb attribute was set, then override the keepAlive query.
156
// This will override any specified keepalive value even if disabled.
157
// (Deprecated, but keep this for backwards-compatability)
158
if (oradb)
159             {
160                 keepAlive = "SELECT 1 FROM DUAL";
161
162                 if (getLogger().isWarnEnabled())
163                 {
164                     getLogger().warn("The oradb attribute is deprecated, please use the" +
165                                      "keep-alive element instead.");
166                 }
167             }
168
169             
170             final JdbcConnectionFactory factory =
171                     new JdbcConnectionFactory( dburl, user, passwd, autoCommit, keepAlive, connectionClass );
172             final DefaultPoolController poolController = new DefaultPoolController(l_max / 4);
173
174             factory.enableLogging( getLogger() );
175
176             try
177             {
178                 m_pool = new JdbcConnectionPool( factory, poolController, l_min, l_max, autoCommit );
179                 m_pool.enableLogging( getLogger() );
180                 m_pool.setTimeout( timeout );
181                 m_pool.initialize();
182             }
183             catch (Exception JavaDoc e)
184             {
185                 if (getLogger().isDebugEnabled())
186                 {
187                     getLogger().debug("Error configuring JdbcDataSource", e);
188                 }
189
190                 throw new ConfigurationException("Error configuring JdbcDataSource", e);
191             }
192         }
193     }
194
195     /** Get the database connection */
196     public Connection JavaDoc getConnection()
197         throws SQLException JavaDoc
198     {
199         try
200         {
201             return (Connection JavaDoc) m_pool.get();
202         }
203         catch( final SQLException JavaDoc se )
204         {
205             if (getLogger().isWarnEnabled())
206             {
207                 getLogger().warn( "Could not return Connection", se );
208             }
209
210             // Rethrow so that we keep the original stack trace
211
throw se;
212         }
213         catch( final Exception JavaDoc e )
214         {
215             if (getLogger().isWarnEnabled())
216             {
217                 getLogger().warn( "Could not return Connection", e );
218             }
219
220             throw new NoAvailableConnectionException( e.getMessage() );
221         }
222     }
223
224     /** Dispose properly of the pool */
225     public void dispose()
226     {
227         m_pool.dispose();
228         m_pool = null;
229     }
230 }
231
Popular Tags