RequestIdFilter implements Filter { public void doFilter( ServletRequest req, ServletResponse resp, FilterChain chain ) throws ServletException, IOException { HttpServletRequest request = (HttpServletRequest) req; String requestId = Optional.ofNullable( request.getHeader( RequestIdUtil.X_REQUEST_ID ) ).orElse( UUID.randomUUID().toString() ); try { if ( logger.isDebugEnabled() ) { logger.debug( "received request with request id of: " + requestId ); } MDC.put( RequestIdUtil.REQUEST_ID, RequestIdUtil.getFormattedRequestUid( requestId ) ); chain.doFilter( req, resp ); } finally { if ( logger.isDebugEnabled() ) { logger.debug( "Exiting request with request id of: " + requestId ); } ( (HttpServletResponse) resp ).setHeader( RequestIdUtil.X_REQUEST_ID, requestId ); MDC.remove( RequestIdUtil.X_REQUEST_ID ); } }  void destroy(); void doFilter( ServletRequest req, ServletResponse resp, FilterChain chain ); void init( FilterConfig config );  }
@Test public void testRequestFilterNoIdProvided( ) throws ServletException, IOException { RequestIdFilter requestIdFilter = new RequestIdFilter( ); requestIdFilter.doFilter( request, response, chain ); verify( response ).setHeader( eq( RequestIdUtil.X_REQUEST_ID ), anyString() ); }
@Test public void testRequestFilterIdProvided() throws ServletException, IOException { String requestId = UUID.randomUUID().toString(); when( request.getHeader( RequestIdUtil.X_REQUEST_ID ) ).thenReturn( requestId ); RequestIdFilter requestIdFilter = new RequestIdFilter(); requestIdFilter.doFilter( request, response, chain ); verify( response ).setHeader( eq( RequestIdUtil.X_REQUEST_ID ), eq( requestId ) ); }