KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openbravo > database > ConnectionProviderImpl


1 /*
2  ************************************************************************************
3  * Copyright (C) 2001-2006 Openbravo S.L.
4  * Licensed under the Apache Software License version 2.0
5  * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
6  * Unless required by applicable law or agreed to in writing, software distributed
7  * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
8  * CONDITIONS OF ANY KIND, either express or implied. See the License for the
9  * specific language governing permissions and limitations under the License.
10  ************************************************************************************
11 */

12 package org.openbravo.database;
13
14 import org.apache.xerces.parsers.DOMParser;
15 import org.xml.sax.*;
16 import org.w3c.dom.*;
17 import org.apache.log4j.Logger;
18 import org.apache.commons.pool.ObjectPool;
19 import org.apache.commons.dbcp.ConnectionFactory;
20 import org.apache.commons.dbcp.PoolableConnectionFactory;
21 import org.apache.commons.pool.KeyedObjectPoolFactory;
22 import org.apache.commons.pool.impl.StackKeyedObjectPoolFactory;
23 import org.apache.commons.pool.impl.GenericObjectPool;
24 import org.apache.commons.dbcp.PoolingDriver;
25 import org.openbravo.exception.*;
26
27 import java.sql.*;
28 import java.io.*;
29
30
31 public class ConnectionProviderImpl implements ConnectionProvider {
32   static Logger log4j = Logger.getLogger(ConnectionProviderImpl.class);
33   String JavaDoc defaultPoolName = "";
34   String JavaDoc bbdd = "";
35   String JavaDoc rdbms = "";
36   String JavaDoc contextName = "openbravo";
37
38   public ConnectionProviderImpl (String JavaDoc file) throws PoolNotFoundException {
39     this(file, false, "openbravo");
40   }
41
42   public ConnectionProviderImpl (String JavaDoc file, String JavaDoc _context) throws PoolNotFoundException {
43     this(file, false, _context);
44   }
45
46
47   public ConnectionProviderImpl (String JavaDoc file, boolean isRelative, String JavaDoc _context) throws PoolNotFoundException {
48     if (log4j.isDebugEnabled()) log4j.debug("Creating ConnectionProviderImpl");
49     if (_context!=null && !_context.equals("")) contextName = _context;
50     try {
51       DOMParser parser = new DOMParser();
52       try {
53         parser.parse((!isRelative?(file.toUpperCase().startsWith("FILE:///")?"":"file:///"):"") + file);
54       } catch (SAXException se) {
55         log4j.error(se);
56         throw new PoolNotFoundException("Couldn't load parse for pool file " + file);
57       } catch (IOException ioe) {
58         log4j.error(ioe);
59         throw new PoolNotFoundException("Couldn't load pool file " + file + " for input/output operations");
60       }
61       Document xmlPool = parser.getDocument();
62       NodeList nodeList = xmlPool.getElementsByTagName("pool");
63       log4j.debug("Pool's elements: " + nodeList.getLength());
64       Node child = null;
65       for (int i=0;i<nodeList.getLength();i++) {
66         Node pool = nodeList.item(i);
67         NamedNodeMap atributos = pool.getAttributes();
68         String JavaDoc poolName = atributos.item(0).getNodeValue();
69         if (log4j.isDebugEnabled()) log4j.debug("poolName: " + poolName);
70
71         child = pool.getFirstChild();
72         child = child.getNextSibling();
73         String JavaDoc dbDriver = ((Text)child.getFirstChild()).getData();
74         if (log4j.isDebugEnabled()) log4j.debug("dbDriver: " + dbDriver);
75         child = child.getNextSibling();
76         child = child.getNextSibling();
77         String JavaDoc dbServer = ((Text)child.getFirstChild()).getData();
78         if (log4j.isDebugEnabled()) log4j.debug("dbServer: " + dbServer);
79         child = child.getNextSibling();
80         child = child.getNextSibling();
81         Text textDbLogin = (Text)child.getFirstChild();
82         String JavaDoc dbLogin;
83         if (textDbLogin != null) {
84           dbLogin = textDbLogin.getData();
85           if (log4j.isDebugEnabled()) log4j.debug("dbLogin: " + dbLogin);
86         } else
87           dbLogin = null;
88         child = child.getNextSibling();
89         child = child.getNextSibling();
90         Text textDbPassword = (Text)child.getFirstChild();
91         String JavaDoc dbPassword;
92         if (textDbPassword != null) {
93           dbPassword = textDbPassword.getData();
94           if (log4j.isDebugEnabled()) log4j.debug("dbPassword: " + dbPassword);
95         } else
96           dbPassword = null;
97         child = child.getNextSibling();
98         child = child.getNextSibling();
99         int minConns = Integer.valueOf(((Text)child.getFirstChild()).getData()).intValue();
100         if (log4j.isDebugEnabled()) log4j.debug("minConns: " + minConns);
101         child = child.getNextSibling();
102         child = child.getNextSibling();
103         int maxConns = Integer.valueOf(((Text)child.getFirstChild()).getData()).intValue();
104         if (log4j.isDebugEnabled()) log4j.debug("maxConns: " + maxConns);
105         child = child.getNextSibling();
106         child = child.getNextSibling();
107         double maxConnTime = Double.valueOf(((Text)child.getFirstChild()).getData()).doubleValue();
108         if (log4j.isDebugEnabled()) log4j.debug("maxConnTime: " + Double.toString(maxConnTime));
109         child = child.getNextSibling();
110         child = child.getNextSibling();
111         String JavaDoc dbSessionConfig = ((Text)child.getFirstChild()).getData();
112         if (log4j.isDebugEnabled()) log4j.debug("dbSessionConfig: " + dbSessionConfig);
113         child = child.getNextSibling();
114         child = child.getNextSibling();
115         String JavaDoc rdbms = ((Text)child.getFirstChild()).getData();
116         if (log4j.isDebugEnabled()) log4j.debug("rdbms: " + rdbms);
117
118
119         addNewPool(dbDriver,dbServer,dbLogin,dbPassword, minConns,maxConns,maxConnTime,dbSessionConfig, rdbms, poolName);
120       }
121     }
122     catch (Exception JavaDoc e) {
123       log4j.error(e);
124       throw new PoolNotFoundException("Failed when creating database connections pool");
125     }
126   }
127
128   public void destroy(String JavaDoc name) throws Exception JavaDoc {
129     PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");
130     driver.closePool(name);
131   }
132
133   public void destroy() throws Exception JavaDoc {
134     destroy(defaultPoolName);
135   }
136
137   public void addNewPool(String JavaDoc dbDriver, String JavaDoc dbServer, String JavaDoc dbLogin, String JavaDoc dbPassword, int minConns, int maxConns, double maxConnTime, String JavaDoc dbSessionConfig, String JavaDoc rdbms, String JavaDoc name) throws Exception JavaDoc {
138     if (log4j.isDebugEnabled()) log4j.debug("Loading underlying JDBC driver.");
139     try {
140       Class.forName(dbDriver);
141     } catch (ClassNotFoundException JavaDoc e) {
142       throw new Exception JavaDoc(e);
143     }
144     if (log4j.isDebugEnabled()) log4j.debug("Done.");
145
146
147     GenericObjectPool connectionPool = new GenericObjectPool(null);
148     connectionPool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_GROW);
149     connectionPool.setMaxActive(maxConns);
150     connectionPool.setTestOnBorrow(false);
151     connectionPool.setTestOnReturn(false);
152     connectionPool.setTestWhileIdle(false);
153
154     KeyedObjectPoolFactory keyedObject = new StackKeyedObjectPoolFactory();
155     ConnectionFactory connectionFactory = new OpenBravoDriverManagerConnectionFactory(dbServer, dbLogin, dbPassword, dbSessionConfig);
156     PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,connectionPool,keyedObject,
157         null,false,true);
158
159     Class.forName("org.apache.commons.dbcp.PoolingDriver");
160     PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");
161     driver.registerPool(contextName + "_" + name, connectionPool);
162
163     if (this.defaultPoolName==null || this.defaultPoolName.equals("")) {
164       this.defaultPoolName = name;
165       this.bbdd = dbServer;
166       this.rdbms = rdbms;
167     }
168   }
169
170   public ObjectPool getPool(String JavaDoc poolName) throws PoolNotFoundException {
171     if (poolName==null || poolName.equals("")) throw new PoolNotFoundException("Couldn´t get an unnamed pool");
172     ObjectPool connectionPool = null;
173     try {
174       PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");
175       connectionPool = driver.getConnectionPool(contextName + "_" + poolName);
176     } catch (SQLException ex) {
177       log4j.error(ex);
178     }
179     if (connectionPool == null)
180       throw new PoolNotFoundException(poolName + " not found");
181     else
182       return connectionPool;
183   }
184
185   public ObjectPool getPool() throws PoolNotFoundException {
186     return getPool(defaultPoolName);
187   }
188
189   public Connection getConnection() throws NoConnectionAvailableException {
190     return getConnection(defaultPoolName);
191   }
192
193   public Connection getConnection(String JavaDoc poolName) throws NoConnectionAvailableException {
194     if (poolName==null || poolName.equals("")) throw new NoConnectionAvailableException("Couldn´t get a connection for an unnamed pool");
195     Connection conn=null;
196     try {
197       conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:" + contextName + "_" + poolName);
198     } catch (SQLException ex) {
199       log4j.error(ex);
200       throw new NoConnectionAvailableException("There are no connections available in jdbc:apache:commons:dbcp:" + contextName + "_" + poolName);
201     }
202     return conn;
203   }
204
205   public String JavaDoc getRDBMS() {
206     return rdbms;
207   }
208
209   public boolean releaseConnection(Connection conn) {
210     if (conn==null) return false;
211     try {
212       conn.setAutoCommit(true);
213       conn.close();
214     } catch (Exception JavaDoc ex) {
215       ex.printStackTrace();
216       return false;
217     }
218     return true;
219   }
220
221   public Connection getTransactionConnection() throws NoConnectionAvailableException, SQLException {
222     Connection conn = getConnection();
223     if (conn==null) throw new NoConnectionAvailableException("Couldn´t get an available connection");
224     conn.setAutoCommit(false);
225     return conn;
226   }
227
228   public void releaseCommitConnection(Connection conn) throws SQLException {
229     if (conn==null) return;
230     conn.commit();
231     releaseConnection(conn);
232   }
233
234   public void releaseRollbackConnection(Connection conn) throws SQLException {
235     if (conn==null) return;
236     conn.rollback();
237     releaseConnection(conn);
238   }
239
240   public PreparedStatement getPreparedStatement(String JavaDoc SQLPreparedStatement) throws Exception JavaDoc {
241     return getPreparedStatement(defaultPoolName, SQLPreparedStatement);
242   }
243
244   public PreparedStatement getPreparedStatement(String JavaDoc poolName, String JavaDoc SQLPreparedStatement) throws Exception JavaDoc {
245     if (poolName == null || poolName.equals("")) throw new PoolNotFoundException("Can't get the pool. No pool name specified");
246     if (log4j.isDebugEnabled()) log4j.debug("connection requested");
247     Connection conn = getConnection(poolName);
248     if (log4j.isDebugEnabled()) log4j.debug("connection established");
249     return getPreparedStatement(conn, SQLPreparedStatement);
250   }
251
252   public PreparedStatement getPreparedStatement(Connection conn, String JavaDoc SQLPreparedStatement) throws SQLException {
253     if (conn == null || SQLPreparedStatement==null || SQLPreparedStatement.equals("")) return null;
254     PreparedStatement ps = null;
255     try {
256       if (log4j.isDebugEnabled()) log4j.debug("preparedStatement requested");
257       ps = conn.prepareStatement(SQLPreparedStatement, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
258       if (log4j.isDebugEnabled()) log4j.debug("preparedStatement received");
259     } catch(SQLException e) {
260       log4j.error("getPreparedStatement: " + SQLPreparedStatement + "\n" + e);
261       releaseConnection(conn);
262       throw e;
263     }
264     return(ps);
265   }
266
267   public CallableStatement getCallableStatement(String JavaDoc SQLCallableStatement) throws Exception JavaDoc {
268     return getCallableStatement(defaultPoolName, SQLCallableStatement);
269   }
270
271   public CallableStatement getCallableStatement(String JavaDoc poolName, String JavaDoc SQLCallableStatement) throws Exception JavaDoc {
272     if (poolName == null || poolName.equals("")) throw new PoolNotFoundException("Can't get the pool. No pool name specified");
273     Connection conn = getConnection(poolName);
274     return getCallableStatement(conn, SQLCallableStatement);
275   }
276
277   public CallableStatement getCallableStatement(Connection conn, String JavaDoc SQLCallableStatement) throws SQLException {
278     if (conn==null || SQLCallableStatement==null || SQLCallableStatement.equals("")) return null;
279     CallableStatement cs = null;
280     try {
281       cs = conn.prepareCall(SQLCallableStatement);
282     } catch(SQLException e) {
283       log4j.error("getCallableStatement: " + SQLCallableStatement + "\n" + e);
284       releaseConnection(conn);
285       throw e;
286     }
287     return(cs);
288   }
289
290   public Statement getStatement() throws Exception JavaDoc {
291     return getStatement(defaultPoolName);
292   }
293
294   public Statement getStatement(String JavaDoc poolName) throws Exception JavaDoc {
295     if (poolName == null || poolName.equals("")) throw new PoolNotFoundException("Can't get the pool. No pool name specified");
296     Connection conn = getConnection(poolName);
297     return getStatement(conn);
298   }
299
300   public Statement getStatement(Connection conn) throws SQLException {
301     if (conn == null) return null;
302     try {
303       return(conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY));
304     } catch(SQLException e) {
305       log4j.error("getStatement: " + e);
306       releaseConnection(conn);
307       throw e;
308     }
309   }
310
311   public void releasePreparedStatement(PreparedStatement preparedStatement) throws SQLException {
312     if (preparedStatement == null) return;
313     Connection conn = null;
314     try {
315       conn = preparedStatement.getConnection();
316       preparedStatement.close();
317       releaseConnection(conn);
318     } catch (SQLException e) {
319       log4j.error("releasePreparedStatement: " + e);
320       releaseConnection(conn);
321       throw e;
322     }
323   }
324
325   public void releaseCallableStatement(CallableStatement callableStatement) throws SQLException {
326     if (callableStatement == null) return;
327     Connection conn = null;
328     try {
329       conn = callableStatement.getConnection();
330       callableStatement.close();
331       releaseConnection(conn);
332     } catch (SQLException e) {
333       log4j.error("releaseCallableStatement: " + e);
334       releaseConnection(conn);
335       throw e;
336     }
337   }
338
339   public void releaseStatement(Statement statement) throws SQLException {
340     if (statement == null) return;
341     Connection conn = null;
342     try {
343       conn = statement.getConnection();
344       statement.close();
345       releaseConnection(conn);
346     } catch (SQLException e) {
347       log4j.error("releaseStatement: " + e);
348       releaseConnection(conn);
349       throw e;
350     }
351   }
352
353   public void releaseTransactionalStatement(Statement statement) throws SQLException {
354     if (statement == null) return;
355     statement.close();
356   }
357
358   public void releaseTransactionalPreparedStatement(PreparedStatement preparedStatement) throws SQLException {
359     if (preparedStatement==null) return;
360     preparedStatement.close();
361   }
362
363   /**
364    * Returns the actual status of the dynamic pool.
365    */

366   public String JavaDoc getStatus() {
367     StringBuffer JavaDoc strResultado = new StringBuffer JavaDoc();
368     strResultado.append("Not implemented yet");
369     return strResultado.toString();
370   }//End getStatus()
371
}
372
Popular Tags