001package ch.qos.logback.core.model.processor; 002 003import javax.naming.NamingException; 004 005import ch.qos.logback.core.Context; 006import ch.qos.logback.core.joran.action.ActionUtil; 007import ch.qos.logback.core.joran.action.ActionUtil.Scope; 008import ch.qos.logback.core.model.InsertFromJNDIModel; 009import ch.qos.logback.core.model.Model; 010import ch.qos.logback.core.util.JNDIUtil; 011import ch.qos.logback.core.util.OptionHelper; 012import ch.qos.logback.core.model.ModelUtil; 013 014public class InsertFromJNDIModelHandler extends ModelHandlerBase { 015 016 public InsertFromJNDIModelHandler(Context context) { 017 super(context); 018 } 019 020 static public ModelHandlerBase makeInstance(Context context, ModelInterpretationContext ic) { 021 return new InsertFromJNDIModelHandler(context); 022 } 023 024 @Override 025 protected Class<InsertFromJNDIModel> getSupportedModelClass() { 026 return InsertFromJNDIModel.class; 027 } 028 029 @Override 030 public void handle(ModelInterpretationContext mic, Model model) throws ModelHandlerException { 031 int errorCount = 0; 032 033 InsertFromJNDIModel ifjm = (InsertFromJNDIModel) model; 034 035 String envEntryName = mic.subst(ifjm.getEnvEntryName()); 036 String asKey = mic.subst(ifjm.getAs()); 037 038 String scopeStr = mic.subst(ifjm.getScopeStr()); 039 Scope scope = ActionUtil.stringToScope(scopeStr); 040 041 String envEntryValue; 042 043 if (OptionHelper.isNullOrEmpty(envEntryName)) { 044 addError("[" + InsertFromJNDIModel.ENV_ENTRY_NAME_ATTR + "] missing"); 045 errorCount++; 046 } 047 048 if (OptionHelper.isNullOrEmpty(asKey)) { 049 addError("[" + InsertFromJNDIModel.AS_ATTR + "] missing"); 050 errorCount++; 051 } 052 053 if (errorCount != 0) { 054 return; 055 } 056 057 try { 058 javax.naming.Context ctx = JNDIUtil.getInitialContext(); 059 envEntryValue = JNDIUtil.lookupString(ctx, envEntryName); 060 if (OptionHelper.isNullOrEmpty(envEntryValue)) { 061 addError("[" + envEntryName + "] has null or empty value"); 062 } else { 063 addInfo("Setting variable [" + asKey + "] to [" + envEntryValue + "] in [" + scope + "] scope"); 064 ModelUtil.setProperty(mic, asKey, envEntryValue, scope); 065 } 066 } catch (NamingException e) { 067 addError("Failed to lookup JNDI env-entry [" + envEntryName + "]"); 068 } 069 070 } 071 072}