1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache license, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the license for the specific language governing permissions and 15 * limitations under the license. 16 */ 17 package org.apache.logging.log4j.core.lookup; 18 19 import javax.naming.Context; 20 import javax.naming.InitialContext; 21 import javax.naming.NamingException; 22 23 import org.apache.logging.log4j.core.LogEvent; 24 import org.apache.logging.log4j.core.config.plugins.Plugin; 25 import org.apache.logging.log4j.core.util.JndiCloser; 26 27 /** 28 * Looks up keys from JNDI resources. 29 */ 30 @Plugin(name = "jndi", category = "Lookup") 31 public class JndiLookup implements StrLookup { 32 33 /** JNDI resourcce path prefix used in a J2EE container */ 34 static final String CONTAINER_JNDI_RESOURCE_PATH_PREFIX = "java:comp/env/"; 35 36 /** 37 * Looks up the value of the JNDI resource. 38 * @param key the JNDI resource name to be looked up, may be null 39 * @return The value of the JNDI resource. 40 */ 41 @Override 42 public String lookup(final String key) { 43 return lookup(null, key); 44 } 45 46 /** 47 * Looks up the value of the JNDI resource. 48 * @param event The current LogEvent (is ignored by this StrLookup). 49 * @param key the JNDI resource name to be looked up, may be null 50 * @return The value of the JNDI resource. 51 */ 52 @Override 53 public String lookup(final LogEvent event, final String key) { 54 if (key == null) { 55 return null; 56 } 57 58 Context ctx = null; 59 try { 60 ctx = new InitialContext(); 61 return (String) ctx.lookup(convertJndiName(key)); 62 } catch (final NamingException e) { 63 return null; 64 } finally { 65 JndiCloser.closeSilently(ctx); 66 } 67 } 68 69 /** 70 * Convert the given JNDI name to the actual JNDI name to use. 71 * Default implementation applies the "java:comp/env/" prefix 72 * unless other scheme like "java:" is given. 73 * @param jndiName The name of the resource. 74 * @return The fully qualified name to look up. 75 */ 76 private String convertJndiName(String jndiName) { 77 if (!jndiName.startsWith(CONTAINER_JNDI_RESOURCE_PATH_PREFIX) && jndiName.indexOf(':') == -1) { 78 return CONTAINER_JNDI_RESOURCE_PATH_PREFIX + jndiName; 79 } 80 return jndiName; 81 } 82 }