LogContextFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request.getCharacterEncoding() == null) { request.setCharacterEncoding("UTF-8"); } try { initContext((HttpServletRequest) request); chain.doFilter(request, response); } finally { clearContext(); } }  @Override void doFilter(ServletRequest request, ServletResponse response, FilterChain chain); @Override void init(FilterConfig filterConfig); @Override void destroy(); static String createSessionLogId(String id); static final String CTX_REQUEST_URI; static final String CTX_REQUEST_ID; static final String CTX_SESSION_ID; static final String CTX_CORRELATION_ID; static final String CTX_SOURCE_SYSTEM; static final String CTX_PROCESS_ID; }
@Test public void testLogContext() throws IOException, ServletException { final HttpServletRequest req = new MockHttpServletRequest("GET", "www.openhubframework.org"); ServletResponse res = new MockHttpServletResponse(); FilterChain chain = new MockFilterChain() { @Override public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { super.doFilter(request, response); assertThat(LogContext.getContextValue(CTX_REQUEST_URI), is(req.getRequestURI())); assertThat(LogContext.getContextValue(CTX_REQUEST_ID), notNullValue()); assertThat(LogContext.getContextValue(CTX_SESSION_ID), nullValue()); } }; LogContextFilter filter = new LogContextFilter(); filter.doFilter(req, res, chain); assertThat(req.getCharacterEncoding(), is("UTF-8")); }
@Test public void testLogContextWithHttpSession() throws IOException, ServletException { final HttpServletRequest req = new MockHttpServletRequest("GET", "www.openhubframework.org"); req.getSession(true); ServletResponse res = new MockHttpServletResponse(); FilterChain chain = new MockFilterChain() { @Override public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { super.doFilter(request, response); assertThat(LogContext.getContextValue(CTX_REQUEST_URI), is(req.getRequestURI())); assertThat(LogContext.getContextValue(CTX_REQUEST_ID), notNullValue()); assertThat(LogContext.getContextValue(CTX_SESSION_ID), notNullValue()); } }; LogContextFilter filter = new LogContextFilter(); filter.doFilter(req, res, chain); assertThat(req.getCharacterEncoding(), is("UTF-8")); }