[SDC-29] Amdocs OnBoard 1707 initial commit.
[sdc.git] / openecomp-be / lib / openecomp-logging-lib / openecomp-sdc-logging-core / src / main / java / org / openecomp / sdc / logging / context / MDCPropagationService.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.sdc.logging.context;
22
23 import org.openecomp.sdc.logging.api.context.ContextPropagationService;
24 import org.slf4j.MDC;
25
26 import java.util.Map;
27
28 /**
29  * Propagates the <a href="http://www.slf4j.org/manual.html#mdc">SLF4J Mapped Diagnostic Context (MDC)</a>
30  * of a thread onto a runnable created by that thread, so that the context is available when the runnable is executed
31  * in a new thread.
32  *
33  * @author evitaliy
34  * @since 12/09/2016.
35  */
36 public class MDCPropagationService implements ContextPropagationService {
37
38     public Runnable create(Runnable task) {
39         return new MDCCopyingWrapper(task);
40     }
41
42     private static class MDCCopyingWrapper implements Runnable {
43
44         private final Runnable task;
45         private final Map<String, String> context;
46
47         private MDCCopyingWrapper(Runnable task) {
48             this.task = task;
49             this.context = MDC.getCopyOfContextMap();
50         }
51
52         @Override
53         public void run() {
54
55             Map<String, String> oldContext = MDC.getCopyOfContextMap();
56             replaceMDC(this.context);
57
58             try {
59                 task.run();
60             } finally {
61                 replaceMDC(oldContext);
62             }
63         }
64
65         private static void replaceMDC(Map<String, String> context) {
66
67             if (context == null) {
68                 MDC.clear();
69             } else  {
70                 MDC.setContextMap(context);
71             }
72         }
73     }
74 }