1   package com.atlassian.spring.filter;
2   
3   import com.atlassian.spring.container.ContainerManager;
4   import net.sf.hibernate.Session;
5   import net.sf.hibernate.SessionFactory;
6   import org.apache.log4j.Category;
7   import org.springframework.orm.hibernate.support.OpenSessionInViewFilter;
8   
9   import javax.servlet.FilterChain;
10  import javax.servlet.ServletException;
11  import javax.servlet.http.HttpServletRequest;
12  import javax.servlet.http.HttpServletResponse;
13  import java.io.IOException;
14  
15  /**
16   * SessionInViewFilter that explicitly flushes the session if it's connected.
17   */
18  public class FlushingSpringSessionInViewFilter extends OpenSessionInViewFilter
19  {
20      public static final Category log = Category.getInstance(FlushingSpringSessionInViewFilter.class);
21  
22      protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException
23      {
24          if (!ContainerManager.isContainerSetup() || !isDatabaseSetUp())
25          {
26              filterChain.doFilter(request, response);
27              return;
28          }
29          super.doFilterInternal(request, response, filterChain);
30      }
31  
32      protected boolean isDatabaseSetUp()
33      {
34          return true;
35      }
36  
37      // We have to make sure that we throw NO exceptions from this method, or we just end up masking problems
38      // in the Spring session filter (the terrible ClobStringType requires active txn sync bug..), and we also
39      // interrupt the session cleanup and leak db connections. - cm
40      protected void closeSession(Session session, SessionFactory sessionFactory)
41      {
42          if (session != null && session.isOpen() && session.isConnected())
43          {
44              try
45              {
46                  session.flush();
47              }
48              catch (Exception e)
49              {
50                  log.error("Unable to flush Hibernate session. Possible data loss: " + e.getMessage(), e);
51              }
52              finally
53              {
54                  super.closeSession(session, sessionFactory);
55              }
56          }
57      }
58  }