package org.opengroupware.jope.appserver;

import java.util.HashMap;
import java.util.Map;

/*
 * WOServerSessionStore
 * 
 * This class keeps session in-memory.
 * 
 * Note: we just keep the live object. I think WO serializes the session which
 *       loweres memory requirements (because only persistent values are saved)
 *       and improves persistent store interoperability.
 * 
 * THREAD: the overridden operations are not threadsafe, but thread safety
 *         is accomplished by the checkout/checkin mechanism implemented in
 *         the superclass.
 */
public class WOServerSessionStore extends WOSessionStore {
  
  protected Map<String, WOSession> store = new HashMap<String,WOSession>(16);

  @Override
  public void saveSessionForContext(WOContext _ctx) {
    WOSession sn = _ctx.session();
    if (sn == null) {
      this.log.error("got no session to save ...");
      return;
    }

    if (this.log.isInfoEnabled())
      this.log.info("saving session: " + sn.sessionID());
    this.store.put(sn.sessionID(), sn);
  }

  @Override
  public WOSession removeSessionWithID(String _sid) {
    if (_sid == null) {
      this.log.info("got no session-id to remove ...");
      return null;
    }
    
    if (this.log.isInfoEnabled())
      this.log.info("removing session: " + _sid);
    return this.store.remove(_sid);
  }
  
  @Override
  public WOSession restoreSessionForID(String _sid, WORequest _rq) {
    boolean debugOn = this.log.isDebugEnabled();
    
    if (_sid == null) {
      if (debugOn) this.log.debug("got no session-id to restore ...");
      return null;
    }
    
    if (debugOn) this.log.debug("restore session: " + _sid);
    WOSession sn = this.store.get(_sid);
    if (sn == null)
      this.log.info("failed to restore session: " + _sid);
    
    if (debugOn) this.log.debug("  restored: " + sn);
    return sn;
  }
}
