com.turbospaces.api.facade.MDCToHeadersContexPropagator Maven / Gradle / Ivy
package com.turbospaces.api.facade;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.slf4j.MDC;
import com.google.common.collect.Sets;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.turbospaces.mdc.ContextPropagator;
import com.turbospaces.mdc.MdcTags;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class MDCToHeadersContexPropagator implements ContextPropagator {
private static final Set TAGS_TO_EXCLUDE = Sets.newHashSet(MdcTags.MDC_MESSAGE_ID, MdcTags.MDC_TOOK);
@Override
public void injectContext(api.v1.Headers.Builder target) {
Map mdc = MDC.getCopyOfContextMap();
if (log.isTraceEnabled()) {
log.trace("about to inject mdc: {} into facade: {}", mdc, target);
}
Map map = api.v1.Headers.getDescriptor().getFields().stream().collect(Collectors.toMap(e -> e.getName(), Function.identity()));
if (Objects.nonNull(mdc)) {
Field[] fields = FieldUtils.getAllFields(MdcTags.class);
for (Field f : fields) {
if (Modifier.isPublic(f.getModifiers()) && Modifier.isStatic(f.getModifiers())) {
try {
String value = (String) FieldUtils.readStaticField(f);
if (mdc.containsKey(value)) {
String toPut = mdc.get(value);
if (StringUtils.isNotEmpty(toPut)) {
if (TAGS_TO_EXCLUDE.contains(value)) {
} else {
FieldDescriptor descriptor = map.get(value);
if (Objects.nonNull(descriptor)) {
target.setField(descriptor, toPut);
}
}
}
}
} catch (IllegalAccessException err) {
ExceptionUtils.wrapAndThrow(err);
}
}
}
}
}
}