001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache license, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the license for the specific language governing permissions and
015 * limitations under the license.
016 */
017package org.apache.logging.log4j.core.lookup;
018
019import java.util.Map;
020
021import org.apache.logging.log4j.core.LogEvent;
022import org.apache.logging.log4j.core.config.plugins.Plugin;
023import org.apache.logging.log4j.message.MapMessage;
024
025/**
026 * The basis for a lookup based on a Map.
027 */
028@Plugin(name = "map", category = "Lookup")
029public class MapLookup implements StrLookup {
030    
031    /**
032     * Map keys are variable names and value.
033     */
034    private final Map<String, String> map;
035
036    /**
037     * Creates a new instance backed by a Map. Used by the default lookup.
038     *
039     * @param map the map of keys to values, may be null
040     */
041    public MapLookup(final Map<String, String> map) {
042        this.map = map;
043    }
044
045    /**
046     * Constructor when used directly as a plugin.
047     */
048    public MapLookup() {
049        this.map = null;
050    }
051
052    /**
053     * Looks up a String key to a String value using the map.
054     * <p>
055     * If the map is null, then null is returned.
056     * The map result object is converted to a string using toString().
057     * </p>
058     *
059     * @param key the key to be looked up, may be null
060     * @return the matching value, null if no match
061     */
062    @Override
063    public String lookup(final String key) {
064        if (map == null) {
065            return null;
066        }
067        return map.get(key);
068    }
069
070    @Override
071    public String lookup(final LogEvent event, final String key) {
072        if (map == null && !(event.getMessage() instanceof MapMessage)) {
073            return null;
074        }
075        if (map != null && map.containsKey(key)) {
076            final String obj = map.get(key);
077            if (obj != null) {
078                return obj;
079            }
080        }
081        if (event.getMessage() instanceof MapMessage) {
082            return ((MapMessage) event.getMessage()).get(key);
083        }
084        return null;
085    }
086}