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)
52 && properties.containsKey(DATA_SOURCE)) {
53 Context ctx = (Context) initCtx.lookup(properties.getProperty(INITIAL_CONTEXT));
54 dataSource = (DataSource) ctx.lookup(properties.getProperty(DATA_SOURCE));
55 } else if (properties.containsKey(DATA_SOURCE)) {
56 dataSource = (DataSource) initCtx.lookup(properties.getProperty(DATA_SOURCE));
57 }
58
59 } catch (NamingException e) {
60 throw new DataSourceException("There was an error configuring JndiDataSourceTransactionPool. Cause: " + e, e);
61 }
62 }
63
64 @Override
65 public DataSource getDataSource() {
66 return dataSource;
67 }
68
69 private static Properties getEnvProperties(Properties allProps) {
70 final String PREFIX = ENV_PREFIX;
71 Properties contextProperties = null;
72 for (Entry<Object, Object> entry : allProps.entrySet()) {
73 String key = (String) entry.getKey();
74 String value = (String) entry.getValue();
75 if (key.startsWith(PREFIX)) {
76 if (contextProperties == null) {
77 contextProperties = new Properties();
78 }
79 contextProperties.put(key.substring(PREFIX.length()), value);
80 }
81 }
82 return contextProperties;
83 }
84
85 }