1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package org.bitrepository.service.database;
23
24 import com.mchange.v2.c3p0.ComboPooledDataSource;
25 import com.mchange.v2.c3p0.DataSources;
26 import java.sql.Connection;
27 import java.sql.SQLException;
28 import java.util.Properties;
29 import org.bitrepository.common.ArgumentValidator;
30 import org.bitrepository.settings.referencesettings.DatabaseSpecifics;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33
34
35
36
37 public class DBConnector {
38
39 private Logger log = LoggerFactory.getLogger(getClass());
40
41 private final DatabaseSpecifics databaseSpecifics;
42
43 private ComboPooledDataSource connectionPool;
44
45
46
47
48
49 public DBConnector(DatabaseSpecifics databaseSpecifics) {
50 ArgumentValidator.checkNotNull(databaseSpecifics, "DatabaseSpecifics specifics");
51
52 silenceC3P0Logger();
53 this.databaseSpecifics = databaseSpecifics;
54 this.connectionPool = new ComboPooledDataSource();
55 initialiseConnectionPool();
56 }
57
58
59
60
61 public String getDatabaseDriverClass() {
62 return databaseSpecifics.getDriverClass();
63 }
64
65
66
67
68 private void initialiseConnectionPool() {
69 try {
70 log.info("Creating the connection to the database '" + databaseSpecifics + "'.");
71 connectionPool.setDriverClass(databaseSpecifics.getDriverClass());
72 connectionPool.setJdbcUrl(databaseSpecifics.getDatabaseURL());
73 if(databaseSpecifics.isSetUsername()) {
74 connectionPool.setUser(databaseSpecifics.getUsername());
75 }
76 if(databaseSpecifics.isSetPassword()) {
77 connectionPool.setPassword(databaseSpecifics.getPassword());
78 }
79 } catch (Exception e) {
80 throw new IllegalStateException("Could not connect to the database '" + databaseSpecifics + "'", e);
81 }
82 }
83
84
85
86
87 private void silenceC3P0Logger() {
88 Properties p = new Properties(System.getProperties());
89 p.put("com.mchange.v2.log.MLog", "com.mchange.v2.log.FallbackMLog");
90 p.put("com.mchange.v2.log.FallbackMLog.DEFAULT_CUTOFF_LEVEL", "OFF");
91 System.setProperties(p);
92 }
93
94
95
96
97
98 public Connection getConnection() {
99 try {
100 return connectionPool.getConnection();
101 } catch (SQLException e) {
102 throw new IllegalStateException("Could not establish connection to the database: '" + databaseSpecifics
103 + "'", e);
104 }
105 }
106
107
108
109
110 public void destroy() {
111 try {
112 DataSources.destroy(connectionPool);
113 } catch (SQLException e) {
114 log.error("Could not clean up the database '" + databaseSpecifics + "'.", e);
115 }
116 }
117 }