1
2
3
4
5
6
7
8
9
10
11
12
13
14 package ch.qos.logback.classic.joran.action;
15
16 import javax.naming.Context;
17 import javax.naming.NamingException;
18
19 import org.xml.sax.Attributes;
20
21 import ch.qos.logback.classic.util.JNDIUtil;
22 import ch.qos.logback.core.joran.action.Action;
23 import ch.qos.logback.core.joran.spi.InterpretationContext;
24 import ch.qos.logback.core.util.OptionHelper;
25
26
27
28
29
30
31
32 public class InsertFromJNDIAction extends Action {
33
34 public static String ENV_ENTRY_NAME_ATTR="env-entry-name";
35 public static String AS_ATTR="as";
36
37 public void begin(InterpretationContext ec, String name, Attributes attributes) {
38
39 int errorCount = 0;
40 String envEntryName = attributes.getValue(ENV_ENTRY_NAME_ATTR);
41 String asName = attributes.getValue(AS_ATTR);
42 String envEntryValue;
43
44 if(OptionHelper.isEmpty(envEntryName)) {
45 String lineColStr = getLineColStr(ec);
46 addError("["+ENV_ENTRY_NAME_ATTR+"] missing, around "+lineColStr);
47 errorCount++;
48 }
49
50 if(OptionHelper.isEmpty(asName)) {
51 String lineColStr = getLineColStr(ec);
52 addError("["+AS_ATTR+"] missing, around "+lineColStr);
53 errorCount++;
54 }
55
56 if(errorCount != 0) {
57 return;
58 }
59
60 try {
61 Context ctx = JNDIUtil.getInitialContext();
62 envEntryValue = JNDIUtil.lookup(ctx, envEntryName);
63 if(OptionHelper.isEmpty(envEntryValue)) {
64 addError("["+envEntryName+"] has null or empty value");
65 } else {
66 addInfo("Setting context variable ["+asName+"] to ["+envEntryValue+"]");
67 context.putProperty(asName, envEntryValue);
68 }
69 } catch (NamingException e) {
70 addError("Failed to lookup JNDI env-entry ["+envEntryName+"]");
71 }
72
73
74 }
75
76 public void end(InterpretationContext ec, String name) {
77 }
78 }