All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.vrap.rmf.base.client.utils.ThreadUtils Maven / Gradle / Ivy

There is a newer version: 17.17.0
Show newest version

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();
        };
    }
}