001/**
002 * Copyright (c) 2004-2011 QOS.ch
003 * All rights reserved.
004 *
005 * Permission is hereby granted, free  of charge, to any person obtaining
006 * a  copy  of this  software  and  associated  documentation files  (the
007 * "Software"), to  deal in  the Software without  restriction, including
008 * without limitation  the rights to  use, copy, modify,  merge, publish,
009 * distribute,  sublicense, and/or sell  copies of  the Software,  and to
010 * permit persons to whom the Software  is furnished to do so, subject to
011 * the following conditions:
012 *
013 * The  above  copyright  notice  and  this permission  notice  shall  be
014 * included in all copies or substantial portions of the Software.
015 *
016 * THE  SOFTWARE IS  PROVIDED  "AS  IS", WITHOUT  WARRANTY  OF ANY  KIND,
017 * EXPRESS OR  IMPLIED, INCLUDING  BUT NOT LIMITED  TO THE  WARRANTIES OF
018 * MERCHANTABILITY,    FITNESS    FOR    A   PARTICULAR    PURPOSE    AND
019 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
020 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
021 * OF CONTRACT, TORT OR OTHERWISE,  ARISING FROM, OUT OF OR IN CONNECTION
022 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
023 *
024 */
025package org.slf4j.helpers;
026
027import org.slf4j.spi.MDCAdapter;
028
029import java.util.*;
030
031/**
032 * Basic MDC implementation, which can be used with logging systems that lack
033 * out-of-the-box MDC support.
034 *
035 * This code was initially inspired by  logback's LogbackMDCAdapter. However,
036 * LogbackMDCAdapter has evolved and is now considerably more sophisticated.
037 *
038 * @author Ceki Gulcu
039 * @author Maarten Bosteels
040 * @author Lukasz Cwik
041 * 
042 * @since 1.5.0
043 */
044public class BasicMDCAdapter implements MDCAdapter {
045
046    private final ThreadLocalMapOfStacks threadLocalMapOfDeques = new ThreadLocalMapOfStacks();
047
048    private final InheritableThreadLocal<Map<String, String>> inheritableThreadLocalMap = new InheritableThreadLocal<Map<String, String>>() {
049        @Override
050        protected Map<String, String> childValue(Map<String, String> parentValue) {
051            if (parentValue == null) {
052                return null;
053            }
054            return new HashMap<>(parentValue);
055        }
056    };
057
058    /**
059     * Put a context value (the <code>val</code> parameter) as identified with
060     * the <code>key</code> parameter into the current thread's context map.
061     * Note that contrary to log4j, the <code>val</code> parameter can be null.
062     *
063     * <p>
064     * If the current thread does not have a context map it is created as a side
065     * effect of this call.
066     *
067     * @throws IllegalArgumentException
068     *                 in case the "key" parameter is null
069     */
070    public void put(String key, String val) {
071        if (key == null) {
072            throw new IllegalArgumentException("key cannot be null");
073        }
074        Map<String, String> map = inheritableThreadLocalMap.get();
075        if (map == null) {
076            map = new HashMap<>();
077            inheritableThreadLocalMap.set(map);
078        }
079        map.put(key, val);
080    }
081
082    /**
083     * Get the context identified by the <code>key</code> parameter.
084     */
085    public String get(String key) {
086        Map<String, String> map = inheritableThreadLocalMap.get();
087        if ((map != null) && (key != null)) {
088            return map.get(key);
089        } else {
090            return null;
091        }
092    }
093
094    /**
095     * Remove the context identified by the <code>key</code> parameter.
096     */
097    public void remove(String key) {
098        Map<String, String> map = inheritableThreadLocalMap.get();
099        if (map != null) {
100            map.remove(key);
101        }
102    }
103
104    /**
105     * Clear all entries in the MDC.
106     */
107    public void clear() {
108        Map<String, String> map = inheritableThreadLocalMap.get();
109        if (map != null) {
110            map.clear();
111            inheritableThreadLocalMap.remove();
112        }
113    }
114
115    /**
116     * Returns the keys in the MDC as a {@link Set} of {@link String}s The
117     * returned value can be null.
118     *
119     * @return the keys in the MDC
120     */
121    public Set<String> getKeys() {
122        Map<String, String> map = inheritableThreadLocalMap.get();
123        if (map != null) {
124            return map.keySet();
125        } else {
126            return null;
127        }
128    }
129
130    /**
131     * Return a copy of the current thread's context map.
132     * Returned value may be null.
133     *
134     */
135    public Map<String, String> getCopyOfContextMap() {
136        Map<String, String> oldMap = inheritableThreadLocalMap.get();
137        if (oldMap != null) {
138            return new HashMap<>(oldMap);
139        } else {
140            return null;
141        }
142    }
143
144    public void setContextMap(Map<String, String> contextMap) {
145        Map<String, String> copy = null;
146        if (contextMap != null) {
147            copy = new HashMap<>(contextMap);
148        }
149        inheritableThreadLocalMap.set(copy);
150    }
151
152    @Override
153    public void pushByKey(String key, String value) {
154        threadLocalMapOfDeques.pushByKey(key, value);
155    }
156
157    @Override
158    public String popByKey(String key) {
159        return threadLocalMapOfDeques.popByKey(key);    
160     }
161
162    @Override
163    public Deque<String> getCopyOfDequeByKey(String key) {
164        return threadLocalMapOfDeques.getCopyOfDequeByKey(key);
165    }
166    @Override
167    public void clearDequeByKey(String key) {
168        threadLocalMapOfDeques.clearDequeByKey(key);
169    }
170}