001/**
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v1.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014package ch.qos.logback.core.util;
015
016import static ch.qos.logback.core.CoreConstants.JNDI_JAVA_NAMESPACE;
017
018import java.util.Hashtable;
019
020import javax.naming.Context;
021import javax.naming.InitialContext;
022import javax.naming.NamingException;
023
024/**
025 * A simple utility class to create and use a JNDI Context.
026 *
027 * @author Ceki Gülcü
028 * @author Michael Osipov
029 * @author Sébastien Pennec
030 * 
031 */
032
033public class JNDIUtil {
034
035    static final String RESTRICTION_MSG = "JNDI name must start with " + JNDI_JAVA_NAMESPACE + " but was ";
036
037    public static Context getInitialContext() throws NamingException {
038        return new InitialContext();
039    }
040
041    public static Context getInitialContext(Hashtable<?, ?> props) throws NamingException {
042        return new InitialContext(props);
043    }
044
045    public static Object lookupObject(Context ctx, String name) throws NamingException {
046        if (ctx == null) {
047            return null;
048        }
049
050        if (OptionHelper.isNullOrEmptyOrAllSpaces(name)) {
051            return null;
052        }
053
054        jndiNameSecurityCheck(name);
055
056        Object lookup = ctx.lookup(name);
057        return lookup;
058    }
059
060    public static void jndiNameSecurityCheck(String name) throws NamingException {
061        if (!name.startsWith(JNDI_JAVA_NAMESPACE)) {
062            throw new NamingException(RESTRICTION_MSG + name);
063        }
064    }
065
066    public static String lookupString(Context ctx, String name) throws NamingException {
067        Object lookup = lookupObject(ctx, name);
068        return (String) lookup;
069    }
070
071}