1 package org.apache.commons.jcs3.auxiliary.disk.jdbc.dsfactory;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.sql.SQLException;
23
24 import javax.sql.ConnectionPoolDataSource;
25 import javax.sql.DataSource;
26
27 import org.apache.commons.dbcp2.cpdsadapter.DriverAdapterCPDS;
28 import org.apache.commons.dbcp2.datasources.InstanceKeyDataSource;
29 import org.apache.commons.dbcp2.datasources.SharedPoolDataSource;
30 import org.apache.commons.jcs3.auxiliary.disk.jdbc.JDBCDiskCacheAttributes;
31 import org.apache.commons.jcs3.log.Log;
32 import org.apache.commons.jcs3.log.LogManager;
33
34
35
36
37
38
39 public class SharedPoolDataSourceFactory implements DataSourceFactory
40 {
41
42 private static final Log log = LogManager.getLog(SharedPoolDataSourceFactory.class);
43
44
45 private String name;
46
47
48 private SharedPoolDataSource ds;
49
50
51
52
53 @Override
54 public String getName()
55 {
56 return name;
57 }
58
59
60
61
62 @Override
63 public DataSource getDataSource()
64 {
65 return ds;
66 }
67
68
69
70
71 @Override
72 public void initialize(final JDBCDiskCacheAttributes config) throws SQLException
73 {
74 this.name = config.getConnectionPoolName();
75 final ConnectionPoolDataSource cpds = initCPDS(config);
76 final SharedPoolDataSource dataSource = new SharedPoolDataSource();
77 initJdbc2Pool(dataSource, config);
78 dataSource.setConnectionPoolDataSource(cpds);
79 dataSource.setMaxTotal(config.getMaxTotal());
80 this.ds = dataSource;
81 }
82
83
84
85
86
87 @Override
88 public void close() throws SQLException
89 {
90 try
91 {
92 if (ds != null)
93 {
94 ds.close();
95 }
96 }
97 catch (final Exception e)
98 {
99 throw new SQLException("Exception caught closing data source", e);
100 }
101 ds = null;
102 }
103
104
105
106
107
108
109
110
111 private static ConnectionPoolDataSource initCPDS(final JDBCDiskCacheAttributes config)
112 throws SQLException
113 {
114 log.debug("Starting initCPDS");
115
116 final DriverAdapterCPDS cpds = new DriverAdapterCPDS();
117
118 try
119 {
120 cpds.setDriver(config.getDriverClassName());
121 }
122 catch (final ClassNotFoundException e)
123 {
124 throw new SQLException("Driver class not found " + config.getDriverClassName(), e);
125 }
126
127 cpds.setUrl(config.getUrl());
128 cpds.setUser(config.getUserName());
129 cpds.setPassword(config.getPassword());
130
131 return cpds;
132 }
133
134
135
136
137
138
139
140
141
142 private static void initJdbc2Pool(final InstanceKeyDataSource dataSource, final JDBCDiskCacheAttributes config)
143 throws SQLException
144 {
145 log.debug("Starting initJdbc2Pool");
146
147 dataSource.setDescription(config.getConnectionPoolName());
148 }
149 }