1 package org.apache.commons.jcs.auxiliary.disk.jdbc.dsfactory;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.sql.SQLException;
23 import java.util.Hashtable;
24 import java.util.Iterator;
25 import java.util.Map;
26
27 import javax.naming.Context;
28 import javax.naming.InitialContext;
29 import javax.naming.NamingException;
30 import javax.sql.DataSource;
31
32 import org.apache.commons.jcs.auxiliary.disk.jdbc.JDBCDiskCacheAttributes;
33 import org.apache.commons.logging.Log;
34 import org.apache.commons.logging.LogFactory;
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49 public class JndiDataSourceFactory implements DataSourceFactory
50 {
51
52 private static Log log = LogFactory.getLog(JndiDataSourceFactory.class);
53
54
55 private String name;
56
57
58 private String path;
59
60
61 private Context ctx;
62
63
64 private DataSource ds = null;
65
66
67 private long lastLookup = 0;
68
69
70 private long ttl = 0;
71
72
73
74
75 @Override
76 public String getName()
77 {
78 return name;
79 }
80
81
82
83
84 @Override
85 public DataSource getDataSource() throws SQLException
86 {
87 long time = System.currentTimeMillis();
88
89 if (ds == null || time - lastLookup > ttl)
90 {
91 try
92 {
93 synchronized (ctx)
94 {
95 ds = ((DataSource) ctx.lookup(path));
96 }
97 lastLookup = time;
98 }
99 catch (NamingException e)
100 {
101 throw new SQLException(e);
102 }
103 }
104
105 return ds;
106 }
107
108
109
110
111 @Override
112 public void initialize(JDBCDiskCacheAttributes config) throws SQLException
113 {
114 this.name = config.getConnectionPoolName();
115 initJNDI(config);
116 }
117
118
119
120
121
122
123
124 private void initJNDI(JDBCDiskCacheAttributes config) throws SQLException
125 {
126 log.debug("Starting initJNDI");
127
128 try
129 {
130 this.path = config.getJndiPath();
131 if (log.isDebugEnabled())
132 {
133 log.debug("JNDI path: " + path);
134 }
135
136 this.ttl = config.getJndiTTL();
137 if (log.isDebugEnabled())
138 {
139 log.debug("Time between context lookups: " + ttl);
140 }
141
142 Hashtable<String, Object> env = new Hashtable<String, Object>();
143 ctx = new InitialContext(env);
144
145 if (log.isDebugEnabled())
146 {
147 log.debug("Created new InitialContext");
148 debugCtx(ctx);
149 }
150 }
151 catch (NamingException e)
152 {
153 throw new SQLException(e);
154 }
155 }
156
157
158
159
160
161 @Override
162 public void close()
163 {
164
165 }
166
167
168
169
170
171
172 private void debugCtx(Context ctx) throws NamingException
173 {
174 log.debug("InitialContext -------------------------------");
175 Map<?, ?> env = ctx.getEnvironment();
176 Iterator<?> qw = env.entrySet().iterator();
177 log.debug("Environment properties:" + env.size());
178 while (qw.hasNext())
179 {
180 Map.Entry<?, ?> entry = (Map.Entry<?, ?>) qw.next();
181 log.debug(" " + entry.getKey() + ": " + entry.getValue());
182 }
183 log.debug("----------------------------------------------");
184 }
185 }