1
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.action.ActionUtil;
24 import ch.qos.logback.core.joran.action.ActionUtil.Scope;
25 import ch.qos.logback.core.joran.spi.InterpretationContext;
26 import ch.qos.logback.core.util.OptionHelper;
27
28
34 public class InsertFromJNDIAction extends Action {
35
36 public static final String ENV_ENTRY_NAME_ATTR = "env-entry-name";
37 public static final String AS_ATTR = "as";
38
39 public void begin(InterpretationContext ec, String name, Attributes attributes) {
40
41 int errorCount = 0;
42 String envEntryName = ec.subst(attributes.getValue(ENV_ENTRY_NAME_ATTR));
43 String asKey = ec.subst(attributes.getValue(AS_ATTR));
44
45 String scopeStr = attributes.getValue(SCOPE_ATTRIBUTE);
46 Scope scope = ActionUtil.stringToScope(scopeStr);
47
48 String envEntryValue;
49
50 if (OptionHelper.isEmpty(envEntryName)) {
51 String lineColStr = getLineColStr(ec);
52 addError("[" + ENV_ENTRY_NAME_ATTR + "] missing, around " + lineColStr);
53 errorCount++;
54 }
55
56 if (OptionHelper.isEmpty(asKey)) {
57 String lineColStr = getLineColStr(ec);
58 addError("[" + AS_ATTR + "] missing, around " + lineColStr);
59 errorCount++;
60 }
61
62 if (errorCount != 0) {
63 return;
64 }
65
66 try {
67 Context ctx = JNDIUtil.getInitialContext();
68 envEntryValue = JNDIUtil.lookup(ctx, envEntryName);
69 if (OptionHelper.isEmpty(envEntryValue)) {
70 addError("[" + envEntryName + "] has null or empty value");
71 } else {
72 addInfo("Setting variable [" + asKey + "] to [" + envEntryValue + "] in [" + scope + "] scope");
73 ActionUtil.setProperty(ec, asKey, envEntryValue, scope);
74 }
75 } catch (NamingException e) {
76 addError("Failed to lookup JNDI env-entry [" + envEntryName + "]");
77 }
78
79 }
80
81 public void end(InterpretationContext ec, String name) {
82 }
83 }
84