001 002package io.vrap.rmf.base.client.utils; 003 004import java.util.Map; 005import java.util.Optional; 006import java.util.function.Function; 007import java.util.function.Supplier; 008 009import io.vrap.rmf.base.client.ApiHttpResponse; 010import io.vrap.rmf.base.client.ContextAware; 011import io.vrap.rmf.base.client.MDCContext; 012 013import org.slf4j.MDC; 014 015public class ThreadUtils { 016 017 public static <U, T> Function<ApiHttpResponse<T>, U> withMdc(Function<ApiHttpResponse<T>, U> fn) { 018 return (response) -> { 019 Optional.ofNullable(response) 020 .map(r -> r.getContext(MDCContext.class)) 021 .ifPresent(c -> MDC.setContextMap(c.getValue())); 022 return fn.apply(response); 023 }; 024 } 025 026 public static Runnable withMdc(ContextAware<?> request, Runnable runnable) { 027 return () -> { 028 Optional.ofNullable(request) 029 .map(r -> r.getContext(MDCContext.class)) 030 .ifPresent(c -> MDC.setContextMap(c.getValue())); 031 runnable.run(); 032 }; 033 } 034 035 public static <U> Supplier<U> withMdc(ContextAware<?> request, Supplier<U> supplier) { 036 return () -> { 037 Optional.ofNullable(request) 038 .map(r -> r.getContext(MDCContext.class)) 039 .ifPresent(c -> MDC.setContextMap(c.getValue())); 040 return supplier.get(); 041 }; 042 } 043 044 public static Runnable withMdc(Runnable runnable) { 045 Map<String, String> mdc = MDC.getCopyOfContextMap(); 046 return () -> { 047 MDC.setContextMap(mdc); 048 runnable.run(); 049 }; 050 } 051 052 public static <U> Supplier<U> withMdc(Supplier<U> supplier) { 053 Map<String, String> mdc = MDC.getCopyOfContextMap(); 054 return () -> { 055 MDC.setContextMap(mdc); 056 return supplier.get(); 057 }; 058 } 059}