View Javadoc

1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2011, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v1.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
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   * Insert an env-entry found in JNDI as a new context variable  
28  
29   * @author Ceki Gulcu
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  }