-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJDBCPropertyDataLoader.java
104 lines (84 loc) · 2.58 KB
/
JDBCPropertyDataLoader.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/**
*
*/
package com.tangoe.components;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.sql.DataSource;
/**
* @author ankitkumar
*
*/
public class JDBCPropertyDataLoader implements PropertyDataLoader,Runnable {
private volatile Map<String, String> props;
private DataSource dataSource;
private ScheduledExecutorService es;
private volatile boolean isLoaded;
private static JDBCPropertyDataLoader instance;
private JDBCPropertyDataLoader(DataSource dataSource) {
this.dataSource = dataSource;
}
public static JDBCPropertyDataLoader getInstance(DataSource datasource){
if(instance == null){
synchronized (JDBCPropertyDataLoader.class) {
if(instance == null){
instance = new JDBCPropertyDataLoader(datasource);
}
}
}
return instance;
}
private synchronized void loadData() {
Map<String, String> props = new HashMap<String, String>();
try {
Connection con = dataSource.getConnection();
String sql = "select prop_name,prop_value from property_table";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
String propName = rs.getString("prop_name");
String propValue = rs.getString("prop_value");
props.put(propName, propValue);
}
this.props = Collections.unmodifiableMap(props);
} catch (SQLException exp) {
throw new RuntimeException("Unable to load properties from DB.");
}
}
@Override
public synchronized void startLoading() {
if(!isLoaded){
loadData();
ScheduledExecutorService es = Executors.newScheduledThreadPool(1);
this.es = es;
es.schedule(this, 10, TimeUnit.MINUTES);
isLoaded=true;
}
}
@Override
public synchronized void stopLoading() {
if(isLoaded){
es.shutdown();
}
}
@Override
public Map<String, String> getProps() {
if(isLoaded){
return props;
}else{
throw new IllegalStateException("Properties not loaded");
}
}
@Override
public void run() {
loadData();
}
}