/*
  Copyright (C) 2006 Helge Hess

  This file is part of JOPE.

  JOPE is free software; you can redistribute it and/or modify it under
  the terms of the GNU Lesser General Public License as published by the
  Free Software Foundation; either version 2, or (at your option) any
  later version.

  JOPE is distributed in the hope that it will be useful, but WITHOUT ANY
  WARRANTY; without even the implied warranty of MERCHANTABILITY or
  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
  License for more details.

  You should have received a copy of the GNU Lesser General Public
  License along with JOPE; see the file COPYING.  If not, write to the
  Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
  02111-1307, USA.
*/

package org.opengroupware.jope.appserver.core;

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;
  }
}
