1
2
3
4
5
6
7
8
9
10 package ch.qos.logback.core.db;
11
12 import java.sql.Connection;
13 import java.sql.SQLException;
14
15 import javax.naming.Context;
16 import javax.naming.InitialContext;
17 import javax.naming.NamingException;
18
19
20
21 import javax.sql.DataSource;
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38 public class JNDIConnectionSource extends ConnectionSourceBase {
39 private String jndiLocation = null;
40 private DataSource dataSource = null;
41
42
43
44
45 public void start() {
46 if (jndiLocation == null) {
47 addError("No JNDI location specified for JNDIConnectionSource.");
48 }
49
50 discoverConnnectionProperties();
51
52 }
53
54
55
56
57 public Connection getConnection() throws SQLException {
58 Connection conn = null;
59 try {
60
61 if (dataSource == null) {
62 dataSource = lookupDataSource();
63 }
64 if (getUser() == null) {
65 conn = dataSource.getConnection();
66 } else {
67 conn = dataSource.getConnection(getUser(), getPassword());
68 }
69 } catch (final NamingException ne) {
70 addError("Error while getting data source", ne);
71 throw new SQLException("NamingException while looking up DataSource: "
72 + ne.getMessage());
73 } catch (final ClassCastException cce) {
74 addError("ClassCastException while looking up DataSource.", cce);
75 throw new SQLException("ClassCastException while looking up DataSource: "
76 + cce.getMessage());
77 }
78
79 return conn;
80 }
81
82
83
84
85
86
87 public String getJndiLocation() {
88 return jndiLocation;
89 }
90
91
92
93
94
95
96
97 public void setJndiLocation(String jndiLocation) {
98 this.jndiLocation = jndiLocation;
99 }
100
101 private DataSource lookupDataSource() throws NamingException, SQLException {
102 DataSource ds;
103 Context ctx = new InitialContext();
104 Object obj = ctx.lookup(jndiLocation);
105
106
107
108 ds = (DataSource) obj;
109
110 if (ds == null) {
111 throw new SQLException("Failed to obtain data source from JNDI location "
112 + jndiLocation);
113 } else {
114 return ds;
115 }
116 }
117 }