1 19 20 package org.apache.cayenne.jpa.conf; 21 22 import java.sql.SQLException ; 23 import java.util.Properties ; 24 25 import javax.naming.InitialContext ; 26 import javax.naming.NamingException ; 27 import javax.persistence.spi.PersistenceUnitInfo; 28 import javax.sql.DataSource ; 29 30 import org.apache.cayenne.access.ConnectionLogger; 31 import org.apache.cayenne.access.QueryLogger; 32 import org.apache.cayenne.conn.PoolManager; 33 import org.apache.cayenne.jpa.JpaProviderException; 34 import org.apache.cayenne.jpa.Provider; 35 import org.apache.cayenne.util.Util; 36 37 56 public class DefaultDataSourceFactory implements JpaDataSourceFactory { 57 58 public DataSource getJtaDataSource(String name, PersistenceUnitInfo info) { 59 return getDataSource(name, info); 60 } 61 62 public DataSource getNonJtaDataSource(String name, PersistenceUnitInfo info) { 63 return getDataSource(name, info); 64 } 65 66 protected DataSource getJndiDataSource(String name, PersistenceUnitInfo info) { 67 if (name == null) { 68 return null; 69 } 70 71 try { 72 return (DataSource ) new InitialContext ().lookup(name); 73 } 74 catch (NamingException namingEx) { 75 return null; 76 } 77 } 78 79 protected DataSource getDataSource(String name, PersistenceUnitInfo info) { 80 if (name == null) { 81 return null; 82 } 83 84 DataSource ds = getCayenneDataSource(name, info.getProperties()); 85 return ds != null ? ds : getJndiDataSource(name, info); 86 } 87 88 protected DataSource getCayenneDataSource(String name, Properties properties) { 89 90 String driverName = properties.getProperty(Provider.DATA_SOURCE_DRIVER_PROPERTY); 91 if (Util.isEmptyString(driverName)) { 92 return null; 93 } 94 95 String url = properties.getProperty(Provider.DATA_SOURCE_URL_PROPERTY); 96 if (Util.isEmptyString(url)) { 97 return null; 98 } 99 100 int minConnection; 101 try { 102 minConnection = Integer.parseInt(properties 103 .getProperty(Provider.DATA_SOURCE_MIN_CONNECTIONS_PROPERTY)); 104 } 105 catch (Exception e) { 106 minConnection = 1; 107 } 108 109 int maxConnection; 110 try { 111 maxConnection = Integer.parseInt(properties 112 .getProperty(Provider.DATA_SOURCE_MAX_CONNECTIONS_PROPERTY)); 113 } 114 catch (Exception e) { 115 maxConnection = 1; 116 } 117 118 try { 120 return new PoolManager( 121 driverName, 122 url, 123 minConnection, 124 maxConnection, 125 properties.getProperty(Provider.DATA_SOURCE_USER_NAME_PROPERTY), 126 properties.getProperty(Provider.DATA_SOURCE_PASSWORD_PROPERTY), 127 new ConnectionLogger()); 128 } 129 catch (SQLException e) { 130 QueryLogger.logConnectFailure(e); 131 throw new JpaProviderException("Error creating connection pool", e); 132 } 133 } 134 } 135 | Popular Tags |