TraceHeaderFilter.java

  1. package no.nav.data.common.web;

  2. import no.nav.data.common.utils.Constants;
  3. import no.nav.data.common.utils.MdcUtils;
  4. import org.springframework.web.reactive.function.client.ClientRequest;
  5. import org.springframework.web.reactive.function.client.ClientResponse;
  6. import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
  7. import org.springframework.web.reactive.function.client.ExchangeFunction;
  8. import reactor.core.publisher.Mono;

  9. import java.util.Optional;

  10. public class TraceHeaderFilter implements ExchangeFilterFunction {

  11.     private final boolean includeAllHeaders;

  12.     public TraceHeaderFilter(boolean includeAllHeaders) {
  13.         this.includeAllHeaders = includeAllHeaders;
  14.     }

  15.     @Override
  16.     public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) {
  17.         var builder = ClientRequest.from(request);
  18.         var correlationId = MdcUtils.getOrGenerateCorrelationId();
  19.         builder.header(Constants.HEADER_CORRELATION_ID, correlationId);

  20.         if (includeAllHeaders) {
  21.             String callId = Optional.ofNullable(MdcUtils.getCallId()).orElse(correlationId);
  22.             builder.header(Constants.HEADER_CALL_ID, callId);
  23.             builder.header(Constants.HEADER_CONSUMER_ID, Constants.APP_ID);
  24.         }
  25.         return next.exchange(builder.build());
  26.     }
  27. }