package grails.plugin.multitenant.core.filter;

import grails.plugin.multitenant.core.CurrentTenant;
import grails.plugin.multitenant.core.resolve.TenantResolver;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class CurrentTenantFilter implements Filter {

    private CurrentTenant currentTenant;
    private TenantResolver tenantResolver;

    @Override
    public void init(FilterConfig fc) throws ServletException {
        ServletContext servletContext = fc.getServletContext();
        ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        currentTenant = (CurrentTenant) ctx.getBean("currentTenant");
        tenantResolver = (TenantResolver) ctx.getBean("tenantResolver");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain filterChain) throws IOException, ServletException {

        if (request instanceof HttpServletRequest) {
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            int currentTenantId = tenantResolver.resolve(httpRequest);
            currentTenant.set(currentTenantId);
        }

        filterChain.doFilter(request, response);
        currentTenant.set(-1);
    }

    @Override
    public void destroy() {
    }	
	
}

@@ -388,16 +388,52 @@
 Utils;%0A%0A
+/**%0A * %0A * @author Kim A. Betti%0A */%0A
 public c
@@ -518,16 +518,40 @@
 tTenant;
+ // thread local storage
 %0A    pri
@@ -585,16 +585,47 @@
 esolver;
+ // provided by implementation 
 %0A%0A    @O
@@ -1003,32 +1003,35 @@
 solver%22);%0A    %7D%0A
+   
 %0A    @Override%0A 
@@ -1108,24 +1108,18 @@
 se,%0A    
-        
+%09%09
 FilterCh
@@ -1174,17 +1174,34 @@
 ption %7B%0A
-%0A
+    %09%0A    %09try %7B%0A%09
         
@@ -1241,24 +1241,25 @@
 tRequest) %7B%0A
+%09
             
@@ -1321,16 +1321,17 @@
 equest;%0A
+%09
         
@@ -1389,24 +1389,25 @@
 tpRequest);%0A
+%09
             
@@ -1442,16 +1442,17 @@
 antId);%0A
+%09
         
@@ -1449,25 +1449,27 @@
 %0A%09        %7D%0A
-%0A
+%09%0A%09
         filt
@@ -1505,28 +1505,43 @@
 ponse);%0A    
-    
+%09%7D finally %7B%0A    %09%09
 currentTenan
@@ -1551,16 +1551,23 @@
 et(-1);%0A
+    %09%7D%0A
     %7D%0A%0A 
@@ -1616,10 +1616,8 @@
    %7D
-%09
 %0A%09%0A%7D
-%0A

Make sure that current-tenant thread local storage is reset in the event of an exception