comparison artifact-database/src/main/java/de/intevation/artifactdatabase/db/DBConnection.java @ 305:f33401ea2a6c

Artifact database: Refactorized the usage of dialect independent SQL to be reusable. artifacts/trunk@2412 c6561f87-3c4e-4783-a992-168aeb5c3f6f
author Sascha L. Teichmann <sascha.teichmann@intevation.de>
date Thu, 28 Jul 2011 10:19:35 +0000
parents
children a077bb098eb4
comparison
equal deleted inserted replaced
304:40b64b4aafce 305:f33401ea2a6c
1 package de.intevation.artifactdatabase.db;
2
3 import java.sql.SQLException;
4
5 import javax.sql.DataSource;
6
7 import java.io.File;
8
9 import org.apache.commons.dbcp.BasicDataSource;
10
11 import de.intevation.artifacts.common.utils.Config;
12
13 public class DBConnection
14 {
15 public static final String DEFAULT_DRIVER = "org.h2.Driver";
16 public static final String DEFAULT_USER = "";
17 public static final String DEFAULT_PASSWORD = "";
18 public static final String DEFAULT_DATABASE_FILE = "artifacts.db";
19 public static final String DEFAULT_URL = getDefaultURL();
20
21 public static final String getDefaultURL() {
22 File configDir = Config.getConfigDirectory();
23 File databaseFile = new File(configDir, DEFAULT_DATABASE_FILE);
24 return "jdbc:h2:" + databaseFile;
25 }
26
27 protected BasicDataSource dataSource;
28
29 protected String driver;
30 protected String url;
31 protected String user;
32 protected String password;
33
34 public DBConnection() {
35 }
36
37 public DBConnection(
38 String driver,
39 String url,
40 String user,
41 String password
42 ) {
43 this.driver = driver;
44 this.url = url;
45 this.user = user;
46 this.password = password;
47 }
48
49 public String getUser() {
50 return user;
51 }
52
53 public void setUser(String user) {
54 this.user = user;
55 }
56
57 public String getPassword() {
58 return password;
59 }
60
61 public void setPassword(String password) {
62 this.password = password;
63 }
64
65 public String getDriver() {
66 return driver;
67 }
68
69 public void setDriver(String driver) {
70 this.driver = driver;
71 }
72
73 public String getUrl() {
74 return url;
75 }
76
77 public void setUrl(String url) {
78 this.url = url;
79 }
80
81 protected void addShutdownHook() {
82 Runtime.getRuntime().addShutdownHook(new Thread() {
83 @Override
84 public void run() {
85 if (dataSource != null) {
86 try {
87 dataSource.close();
88 }
89 catch (SQLException sqle) {
90 }
91 dataSource = null;
92 }
93 }
94 });
95 }
96
97 public synchronized DataSource getDataSource() {
98 if (dataSource == null) {
99 dataSource = new BasicDataSource();
100
101 dataSource.setDriverClassName(driver);
102 dataSource.setUsername(user);
103 dataSource.setPassword(password);
104 dataSource.setUrl(url);
105 addShutdownHook();
106 }
107 return dataSource;
108 }
109 }
110 // vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :

http://dive4elements.wald.intevation.org