Question

I'm writing a JUL logging Handler and I'd like to augment the logged messages with information about the current request, if we're currently handling a request. To accomplish this, I've injected a Provider<Thing> into the Handler, where Thing is @RequestScoped.

However, calling provider.get() throws an OutOfScopeException if the logging happens while we're not handling a request. I feel like catching the OutOfScopeException would be bad form. Is there a better way to determine whether or not a request is currently executing?

Was it helpful?

Solution

With wicket I used a little trick. This should be framework independent. I made a request filter and put a public static ThreadLocal in it. So if current thread is born from request, threadlocal will be set.

public class SessionContext implements Filter {

    private static final ThreadLocal<HttpSession> session = new ThreadLocal<HttpSession>();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        return;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        session.set(((HttpServletRequest)servletRequest).getSession());
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        return;
    }

    public static HttpSession getSession(){
        return session.get();
    }

    public static User getUser(){
        return (User) session.get().getAttribute(UserService.USER);
    }
}

and in web.xml:

<filter>
    <filter-name>session</filter-name>
    <filter-class>SessionContext</filter-class>
</filter>

OTHER TIPS

As far as I know, there is no elegant way to do this. The Guice API is tight and will not grant access to the thread-local needed to make such a test. As of version 3, the thread-local in question sits on com.google.inject.servlet.GuiceFilter#localContext. You could access it by reflection but it is arguably even worse style than catching the exception.

I would stick on caching the exception... or hack into that class and add an static boolean test method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top