io.vrap.rmf.base.client.utils.ThreadUtils Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of rmf-java-base Show documentation
Show all versions of rmf-java-base Show documentation
The e-commerce SDK from commercetools Composable Commerce for Java
package io.vrap.rmf.base.client.utils;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Supplier;
import io.vrap.rmf.base.client.ApiHttpResponse;
import io.vrap.rmf.base.client.ContextAware;
import io.vrap.rmf.base.client.MDCContext;
import org.slf4j.MDC;
public class ThreadUtils {
public static Function, U> withMdc(Function, U> fn) {
return (response) -> {
Optional.ofNullable(response)
.map(r -> r.getContext(MDCContext.class))
.ifPresent(c -> MDC.setContextMap(c.getValue()));
return fn.apply(response);
};
}
public static Runnable withMdc(ContextAware> request, Runnable runnable) {
return () -> {
Optional.ofNullable(request)
.map(r -> r.getContext(MDCContext.class))
.ifPresent(c -> MDC.setContextMap(c.getValue()));
runnable.run();
};
}
public static Supplier withMdc(ContextAware> request, Supplier supplier) {
return () -> {
Optional.ofNullable(request)
.map(r -> r.getContext(MDCContext.class))
.ifPresent(c -> MDC.setContextMap(c.getValue()));
return supplier.get();
};
}
public static Runnable withMdc(Runnable runnable) {
Map mdc = MDC.getCopyOfContextMap();
return () -> {
MDC.setContextMap(mdc);
runnable.run();
};
}
public static Supplier withMdc(Supplier supplier) {
Map mdc = MDC.getCopyOfContextMap();
return () -> {
MDC.setContextMap(mdc);
return supplier.get();
};
}
}