TraceHeaderRequestInterceptor.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.http.HttpRequest;
  5. import org.springframework.http.client.ClientHttpRequestExecution;
  6. import org.springframework.http.client.ClientHttpRequestInterceptor;
  7. import org.springframework.http.client.ClientHttpResponse;

  8. import java.io.IOException;
  9. import java.util.Optional;

  10. public class TraceHeaderRequestInterceptor implements ClientHttpRequestInterceptor {

  11.     private final boolean includeAllHeaders;

  12.     private TraceHeaderRequestInterceptor(boolean includeAllHeaders) {
  13.         this.includeAllHeaders = includeAllHeaders;
  14.     }

  15.     public static TraceHeaderRequestInterceptor fullInterceptor() {
  16.         return new TraceHeaderRequestInterceptor(true);
  17.     }

  18.     public static TraceHeaderRequestInterceptor correlationInterceptor() {
  19.         return new TraceHeaderRequestInterceptor(false);
  20.     }

  21.     @Override
  22.     public ClientHttpResponse intercept(HttpRequest req, byte[] body, ClientHttpRequestExecution execution) throws IOException {
  23.         String correlationId = MdcUtils.getOrGenerateCorrelationId();
  24.         req.getHeaders().set(Constants.HEADER_CORRELATION_ID, correlationId);

  25.         if (includeAllHeaders) {
  26.             String callId = Optional.ofNullable(MdcUtils.getCallId()).orElse(correlationId);
  27.             req.getHeaders().set(Constants.HEADER_CALL_ID, callId);
  28.             req.getHeaders().set(Constants.HEADER_CONSUMER_ID, Constants.APP_ID);
  29.         }
  30.         return execution.execute(req, body);
  31.     }
  32. }