1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.seasar.tuigwaa.database;
17
18 import java.sql.Connection;
19 import java.sql.SQLException;
20 import java.util.Collections;
21 import java.util.HashMap;
22 import java.util.Iterator;
23 import java.util.Map;
24
25 import javax.sql.DataSource;
26
27 import org.seasar.extension.jdbc.util.DataSourceUtil;
28 import org.seasar.tuigwaa.database.util.BasicDynaBatchHandler;
29 import org.seasar.tuigwaa.database.util.BasicDynaSelectHandler;
30 import org.seasar.tuigwaa.database.util.DynaBatchHandler;
31 import org.seasar.tuigwaa.database.util.DynaBeanListResultSetHandler;
32 import org.seasar.tuigwaa.database.util.DynaSelectHandler;
33
34 public class MultiDataSourceImpl implements MultiDataSource {
35
36 private Map dataSourceMap = Collections.synchronizedMap(new HashMap());
37
38 private DataSource baseDataSource;
39
40 public MultiDataSourceImpl(DataSource dataSource) {
41 this.baseDataSource = dataSource;
42 }
43
44 public boolean isExistDatabase(String dbName){
45 return dataSourceMap.get(dbName) != null;
46 }
47
48 public String[] getExternalDatabaseNames() {
49 String[] names = new String[dataSourceMap.size()];
50 Iterator itr = dataSourceMap.keySet().iterator();
51 for (int i = 0; itr.hasNext(); i++) {
52 String name = (String) itr.next();
53 names[i] = name;
54 }
55 return names;
56 }
57
58 public Connection getBaseConnection() {
59 return DataSourceUtil.getConnection(baseDataSource);
60 }
61
62 public Connection getConnection(String dbName) throws SQLException {
63 DataSource dataSource = (DataSource) dataSourceMap.get(dbName);
64 if (dataSource != null) {
65 return dataSource.getConnection();
66 } else {
67 return getBaseConnection();
68 }
69 }
70
71 public void addDataSource(String dbName, DataSource dataSource) {
72 dataSourceMap.put(dbName, dataSource);
73 }
74
75 public void removeDataSource(String dbName){
76 dataSourceMap.remove(dbName);
77 }
78
79 public DynaBatchHandler getDynaBatchHandler(String dbName) {
80 DynaBatchHandler handler = new BasicDynaBatchHandler();
81 if(dbName == null || dataSourceMap.get(dbName) == null){
82 handler.setDataSource(baseDataSource);
83 }else{
84 handler.setDataSource((DataSource)dataSourceMap.get(dbName));
85 }
86 return handler;
87 }
88
89 public DynaSelectHandler getDynaSelectHandler(String dbName) {
90 DynaSelectHandler handler = new BasicDynaSelectHandler();
91 if(dbName == null || dataSourceMap.get(dbName) == null){
92 handler.setDataSource(baseDataSource);
93 }else{
94 handler.setDataSource((DataSource)dataSourceMap.get(dbName));
95 }
96 handler.setResultSetHandler(new DynaBeanListResultSetHandler());
97 return handler;
98 }
99
100 }