View Javadoc
1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2015, 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.core.util;
15  
16  import static ch.qos.logback.core.CoreConstants.JNDI_JAVA_NAMESPACE;
17  
18  import java.util.Hashtable;
19  
20  import javax.naming.Context;
21  import javax.naming.InitialContext;
22  import javax.naming.NamingException;
23  
24  /**
25   * A simple utility class to create and use a JNDI Context.
26   *
27   * @author Ceki Gülcü
28   * @author Michael Osipov
29   * @author Sébastien Pennec
30   * 
31   */
32  
33  public class JNDIUtil {
34  
35      static final String RESTRICTION_MSG = "JNDI name must start with " + JNDI_JAVA_NAMESPACE + " but was ";
36  
37      public static Context getInitialContext() throws NamingException {
38          return new InitialContext();
39      }
40  
41      public static Context getInitialContext(Hashtable<?, ?> props) throws NamingException {
42          return new InitialContext(props);
43      }
44  
45      public static Object lookupObject(Context ctx, String name) throws NamingException {
46          if (ctx == null) {
47              return null;
48          }
49  
50          if (OptionHelper.isNullOrEmptyOrAllSpaces(name)) {
51              return null;
52          }
53  
54          jndiNameSecurityCheck(name);
55  
56          Object lookup = ctx.lookup(name);
57          return lookup;
58      }
59  
60      public static void jndiNameSecurityCheck(String name) throws NamingException {
61          if (!name.startsWith(JNDI_JAVA_NAMESPACE)) {
62              throw new NamingException(RESTRICTION_MSG + name);
63          }
64      }
65  
66      public static String lookupString(Context ctx, String name) throws NamingException {
67          Object lookup = lookupObject(ctx, name);
68          return (String) lookup;
69      }
70  
71  }