1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.kuali.rice.core.ojb;
17
18 import java.sql.Connection;
19 import java.util.ArrayList;
20 import java.util.HashMap;
21 import java.util.List;
22 import java.util.Map;
23
24 import javax.sql.DataSource;
25
26 import org.apache.ojb.broker.accesslayer.ConnectionFactoryNotPooledImpl;
27 import org.apache.ojb.broker.accesslayer.LookupException;
28 import org.apache.ojb.broker.metadata.JdbcConnectionDescriptor;
29 import org.springframework.beans.factory.BeanFactory;
30 import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;
31
32 public class RiceDataSourceConnectionFactory extends ConnectionFactoryNotPooledImpl {
33
34
35
36
37 private static List<BeanFactory> beanFactories = new ArrayList<BeanFactory>();
38
39 public static void addBeanFactory(BeanFactory beanFactory) {
40 beanFactories.add(beanFactory);
41 }
42
43
44
45
46
47 private Map<String, DataSource> dataSources = new HashMap<String, DataSource>();
48
49 public RiceDataSourceConnectionFactory() {
50 if (beanFactories.isEmpty()) {
51 throw new IllegalStateException("No BeanFactories found for configuration - must specify RiceOjbConfigurer as a Spring bean.");
52 }
53 }
54
55 public Connection lookupConnection(JdbcConnectionDescriptor jcd) throws LookupException {
56 try {
57 DataSource dataSource = null;
58 synchronized (this.dataSources) {
59 dataSource = this.dataSources.get(jcd.getJcdAlias());
60 if (dataSource == null) {
61 dataSource = getDataSource(jcd.getJcdAlias());
62 this.dataSources.put(jcd.getJcdAlias(), dataSource);
63 }
64 }
65 return dataSource.getConnection();
66 }
67 catch (Exception ex) {
68 throw new LookupException("Could not obtain connection from data source", ex);
69 }
70 }
71
72
73
74
75
76
77
78
79
80 protected DataSource getDataSource(String jcdAlias) throws LookupException {
81 DataSource dataSource = null;
82 for (BeanFactory beanFactory : beanFactories) {
83 if (beanFactory.containsBean(jcdAlias)) {
84 dataSource = (DataSource) beanFactory.getBean(jcdAlias, DataSource.class);
85 break;
86 }
87 }
88 if (dataSource == null) {
89 throw new LookupException("Could not lookup datasource with alias " + jcdAlias);
90 } else if (dataSource instanceof TransactionAwareDataSourceProxy) {
91 return dataSource;
92 } else {
93 return new TransactionAwareDataSourceProxy(dataSource);
94 }
95 }
96
97 }