1
2
3
4
5
6
7
8
9
10
11
12
13
14 package ch.qos.logback.core.db;
15
16
17 import javax.naming.Context;
18 import javax.naming.InitialContext;
19 import javax.sql.DataSource;
20
21 import org.xml.sax.Attributes;
22
23 import ch.qos.logback.core.joran.action.Action;
24 import ch.qos.logback.core.joran.spi.InterpretationContext;
25 import ch.qos.logback.core.joran.util.PropertySetter;
26 import ch.qos.logback.core.util.OptionHelper;
27
28
29
30
31
32
33 public class BindDataSourceToJNDIAction extends Action {
34
35 static final String DATA_SOURCE_CLASS = "dataSourceClass";
36 static final String URL = "url";
37 static final String USER = "user";
38 static final String PASSWORD = "password";
39
40
41
42
43
44 public void begin(
45 InterpretationContext ec, String localName, Attributes attributes) {
46 String dsClassName = ec.getProperty(DATA_SOURCE_CLASS);
47
48 if (OptionHelper.isEmpty(dsClassName)) {
49 addWarn("dsClassName is a required parameter");
50 ec.addError("dsClassName is a required parameter");
51
52 return;
53 }
54
55 String urlStr = ec.getProperty(URL);
56 String userStr = ec.getProperty(USER);
57 String passwordStr = ec.getProperty(PASSWORD);
58
59 try {
60 DataSource ds =
61 (DataSource) OptionHelper.instantiateByClassName(dsClassName, DataSource.class, context);
62
63 PropertySetter setter = new PropertySetter(ds);
64 setter.setContext(context);
65
66 if (!OptionHelper.isEmpty(urlStr)) {
67 setter.setProperty("url", urlStr);
68 }
69
70 if (!OptionHelper.isEmpty(userStr)) {
71 setter.setProperty("user", userStr);
72 }
73
74 if (!OptionHelper.isEmpty(passwordStr)) {
75 setter.setProperty("password", passwordStr);
76 }
77
78 Context ctx = new InitialContext();
79 ctx.rebind("dataSource", ds);
80 } catch (Exception oops) {
81 addError(
82 "Could not bind datasource. Reported error follows.", oops);
83 ec.addError("Could not not bind datasource of type [" + dsClassName + "].");
84 }
85 }
86
87 public void end(InterpretationContext ec, String name) {
88 }
89 }