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