1 24 package org.ofbiz.entity.transaction; 25 26 import java.sql.Connection ; 27 import java.sql.SQLException ; 28 import java.util.HashMap ; 29 import java.util.Map ; 30 31 import javax.sql.DataSource ; 32 33 import org.apache.commons.dbcp.DriverManagerConnectionFactory; 34 import org.apache.commons.dbcp.PoolingDataSource; 35 import org.apache.commons.pool.ObjectPool; 36 import org.apache.commons.pool.impl.GenericObjectPool; 37 import org.ofbiz.base.util.Debug; 38 import org.ofbiz.entity.GenericEntityException; 39 import org.w3c.dom.Element ; 40 41 51 public class DBCPConnectionFactory { 52 53 public static final String module = DBCPConnectionFactory.class.getName(); 54 protected static Map dsCache = new HashMap (); 55 56 public static Connection getConnection(String helperName, Element dbcpJdbcElement) throws SQLException , GenericEntityException { 57 DataSource dataSource = (DataSource )dsCache.get(helperName); 59 60 if (dataSource != null) { 61 return TransactionFactory.getCursorConnection(helperName, dataSource.getConnection()); 62 } 63 64 try { 65 synchronized (DBCPConnectionFactory.class) { 66 dataSource = (DataSource )dsCache.get(helperName); 68 if (dataSource != null) { 69 return dataSource.getConnection(); 70 } 71 72 ObjectPool connectionPool = new GenericObjectPool(null); 74 75 String connectURI = dbcpJdbcElement.getAttribute("jdbc-uri"); 77 78 String username = dbcpJdbcElement.getAttribute("jdbc-username"); 80 String password = dbcpJdbcElement.getAttribute("jdbc-password"); 81 82 String driverClassName = dbcpJdbcElement.getAttribute("jdbc-driver"); 83 ClassLoader loader = Thread.currentThread().getContextClassLoader(); 84 Class clazz = loader.loadClass(driverClassName); 85 clazz.newInstance(); 86 org.apache.commons.dbcp.ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectURI,username,password); 87 88 93 dataSource = new PoolingDataSource(connectionPool); 96 dataSource.setLogWriter(Debug.getPrintWriter()); 97 dsCache.put(helperName, dataSource); 98 return TransactionFactory.getCursorConnection(helperName, dataSource.getConnection()); 99 } 100 } catch (Exception e) { 101 String errorMsg = "Error getting datasource via DBCP."; 102 Debug.logError(e, errorMsg, module); 103 } 104 105 return null; 106 } 107 } 108 | Popular Tags |