1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.ibatis.datasource.jndi;
17
18 import java.util.Map.Entry;
19 import java.util.Properties;
20
21 import javax.naming.Context;
22 import javax.naming.InitialContext;
23 import javax.naming.NamingException;
24 import javax.sql.DataSource;
25
26 import org.apache.ibatis.datasource.DataSourceException;
27 import org.apache.ibatis.datasource.DataSourceFactory;
28
29
30
31
32 public class JndiDataSourceFactory implements DataSourceFactory {
33
34 public static final String INITIAL_CONTEXT = "initial_context";
35 public static final String DATA_SOURCE = "data_source";
36 public static final String ENV_PREFIX = "env.";
37
38 private DataSource dataSource;
39
40 @Override
41 public void setProperties(Properties properties) {
42 try {
43 InitialContext initCtx;
44 Properties env = getEnvProperties(properties);
45 if (env == null) {
46 initCtx = new InitialContext();
47 } else {
48 initCtx = new InitialContext(env);
49 }
50
51 if (properties.containsKey(INITIAL_CONTEXT) && properties.containsKey(DATA_SOURCE)) {
52 Context ctx = (Context) initCtx.lookup(properties.getProperty(INITIAL_CONTEXT));
53 dataSource = (DataSource) ctx.lookup(properties.getProperty(DATA_SOURCE));
54 } else if (properties.containsKey(DATA_SOURCE)) {
55 dataSource = (DataSource) initCtx.lookup(properties.getProperty(DATA_SOURCE));
56 }
57
58 } catch (NamingException e) {
59 throw new DataSourceException("There was an error configuring JndiDataSourceTransactionPool. Cause: " + e, e);
60 }
61 }
62
63 @Override
64 public DataSource getDataSource() {
65 return dataSource;
66 }
67
68 private static Properties getEnvProperties(Properties allProps) {
69 final String PREFIX = ENV_PREFIX;
70 Properties contextProperties = null;
71 for (Entry<Object, Object> entry : allProps.entrySet()) {
72 String key = (String) entry.getKey();
73 String value = (String) entry.getValue();
74 if (key.startsWith(PREFIX)) {
75 if (contextProperties == null) {
76 contextProperties = new Properties();
77 }
78 contextProperties.put(key.substring(PREFIX.length()), value);
79 }
80 }
81 return contextProperties;
82 }
83
84 }