title: Invoke method just before session expires
body: <p>My webapp has users who login. There is a timeout. Before the session expires, I would like to execute a method to cleanup some locks.</p>
  
  <p>I've implemented a <code>sessionListener</code> but once I reach <code>public void sessionDestroyed(HttpSessionEvent event)</code> the session is already gone and I need some data from it, so I would like to execute a method (which needs the session alive and be able to access <code>FacesConfig.getCurrentInstance()</code>) before the session is actually expired.</p>
  
  <p>How can I do that? Any ideas? This is my Session Listener:</p>
  
  <pre><code>public class MySessionListener implements HttpSessionListener {
  
      private static final Logger log = LoggerFactory.getLogger(MySessionListener.class);
  
      public MySessionListener() {
  
      }
  
      public void sessionCreated(HttpSessionEvent event) {
          log.debug("Current Session created : "
                + event.getSession().getId()+ " at "+ new Date());
      }
  
      public void sessionDestroyed(HttpSessionEvent event) {
          // get the destroying session...
  
          HttpSession session = event.getSession();
          prepareLogoutInfoAndLogoutActiveUser(session);
  
          log.debug("Current Session destroyed :"
                + session.getId()+ " Logging out user...");
  
          /*
           * nobody can reach user data after this point because 
           * session is invalidated already.
           * So, get the user data from session and save its 
           * logout information before losing it.
           * User's redirection to the timeout page will be 
           * handled by the SessionTimeoutFilter.
           */
  
           // Only if needed
      }
  
      /**
       * Clean your logout operations.
       */
      public void prepareLogoutInfoAndLogoutActiveUser(HttpSession httpSession) {
          UserBean user = FacesContext.getCurrentInstance().getApplication().evaluateExpressionGet(FacesContext.getCurrentInstance(), "#{user}", UserBean.class);
          LockBean lock = FacesContext.getCurrentInstance().getApplication().evaluateExpressionGet(FacesContext.getCurrentInstance(), "#{lock}", LockBean.class);
          lock.unlock(user.getUsername());
          log.info("Unlocked examination for user: "+user.getUsername());
      }
  }
  </code></pre>
  
  <p>But I'm getting <code>NullPointerException</code> at <code>FacesContext.getCurrentInstance().getApplication()</code> because either <code>getCurrentInstance</code> is null or <code>getApplication</code> returns null</p>