david-PC\david
2018-06-12 cc7f57619fd09f68582b748a3580402717b84c50
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
package frame.persist;
 
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
 
import javax.sql.DataSource;
 
import org.apache.log4j.Logger;
 
import com.alibaba.druid.pool.DruidDataSource;
 
import frame.role.Scenario;
import frame.util.MapList;
 
 
public class ConnectionManager {
 
    private static Logger logger;
    private static MapList<NamedDataSource> dataSourceList;
    private static NamedDataSource defaultDataSource;
    private static NamedDataSource activeDataSource;
    
    static {
        logger = Logger.getLogger(ConnectionManager.class);
        dataSourceList = new MapList<NamedDataSource>();
    }
 
    public static Connection createConnection() {
        try {
            if (activeDataSource != null) {
                return activeDataSource.getConnection();
            }
            
            Scenario scenario = ScenarioContainer.getActiveScenario();
            
            if (scenario == null) {
                return defaultDataSource.getConnection();
            }
            
            DataSource dataSource = scenario.getDataSource();
            return dataSource.getConnection();
        } 
        catch (SQLException e) {
            logger.error(e);
            return null;
        }
    }
    
    public static void appendDataSource(NamedDataSource dataSource) throws SQLException {
        String name = dataSource.getName();
        
        if (name == null) {
            return;
        }
        
        dataSourceList.add(name, dataSource);
        
        if (defaultDataSource == null) {
            defaultDataSource = dataSource;
        }
    }
 
    public static NamedDataSource getDataSource(String code) {
        if (code == null) {
            return null;
        }
        
        return dataSourceList.get(code);
    }
 
    public static List<NamedDataSource> getDataSourceList() {
        return dataSourceList.getItemList();
    }
 
    public static void setActiveSource(NamedDataSource dataSource) {
        activeDataSource = dataSource;
    }
}