class CreateQuerySessionIDFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext request, ContainerResponseContext response) throws IOException {
        ResourceMethodInvoker method = (ResourceMethodInvoker) request.getProperty(ResourceMethodInvoker.class.getName());
        
        GenerateQuerySessionId annotation = FindAnnotation.findAnnotation(method.getMethodAnnotations(), GenerateQuerySessionId.class);
        
        String path = annotation.cookieBasePath();
        String id = "";
        String cookieValue = generateCookieValue();
        boolean setCookie = true;
        switch (response.getStatusInfo().getFamily()) {
            case SERVER_ERROR:
            case CLIENT_ERROR:
                // If we're sending an error response, then there's no need to set a cookie since
                // there's no query "session" to stick to this server.
                setCookie = false;
                QUERY_ID.set(null);
                break;
            
            default:
                if (StringUtils.isEmpty(QUERY_ID.get())) {
                    log.error(method.getResourceClass() + "." + method.getMethod().getName() + " did not set QUERY_ID threadlocal.");
                } else {
                    id = QUERY_ID.get();
                    QUERY_ID.set(null);
                }
                break;
        }
        
        if (setCookie) {
            response.getHeaders().add(HttpHeaderNames.SET_COOKIE,
                            new NewCookie(Constants.QUERY_COOKIE_NAME, cookieValue, path + id, null, null, NewCookie.DEFAULT_MAX_AGE, false));
        }
    }

}