Here is the code which I use to add filter to headers and add a UUID
@Slf4j
public class ReqTxIdFilterImpl implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
List<String> headerNames = Collections.list(request.getHeaderNames());
String requestTxId = "";
if(!headerNames.isEmpty()){
requestTxId = request.getHeader(
headerNames.stream()//
.filter(header -> header.contains("txId"))
.findAny()
.orElse("")//
);
}
if (StringUtils.isEmpty(requestTxId)) {
requestTxId = UUID.randomUUID().toString();
}
MDC.put("txId", requestTxId);
filterChain.doFilter(servletRequest, servletResponse);
MDC.clear();
}
}
I use spring boot and MockMvc to test APIs
@Autowired
private MockMvc mockMvc;
@Test
public void test_generatePolicyNumber() throws Exception {
MvcResult mvcResult = this.mockMvc.perform(post("/test"))
.header("txId", "test-id")
.andDo(print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andReturn();
Assert.assertTrue(mvcResult.getResponse().getContentAsString().contains("test"));
}
I also want to check the MDC context and check if this test-id is set as txId in the MDC context map and verify it. Is it possible ?