/**
 * @license
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

package foam.box;

import foam.core.*;
import foam.dao.*;
import foam.nanos.session.Session;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;


public class SessionServerBox
  extends ProxyBox
{

  protected boolean authenticate_;

  public SessionServerBox(X x, Box delegate, boolean authenticate) {
    super(x, delegate);
    authenticate_ = authenticate;
  }

  public void send(Message msg) {
    String sessionID = (String) msg.getAttributes().get("sessionId");

    try {
      System.err.println("**** SESSIONID: " + sessionID);

      if ( sessionID != null ) {
        DAO     dao     = (DAO) getX().get("sessionDAO");
        Session session = (Session) dao.find(sessionID);

        if ( session == null ) {
          session = new Session();
          session.setId(sessionID);

          HttpServletRequest req = (HttpServletRequest) getX().get(HttpServletRequest.class);
          session.setRemoteHost(req.getRemoteHost());
          session.setContext(getX());
        }

        session.setLastUsed(new Date());
        session.setUses(session.getUses()+1);

        dao.put(session);

        /*
        TODO: uncomment to activate
        if ( authenticate_ && session.getUserId() == 0 ) {
          System.err.println("*************** NOT LOGGED IN");
          msg.replyWithException(new java.security.AccessControlException("not logged in"));
          return;
        }
        */

        System.err.println("**************************SETTING SESSION*********");
        msg.getLocalAttributes().put("x", getX().put(Session.class, session));
      }
    } catch (Throwable t) {
      t.printStackTrace();
    }

    getDelegate().send(msg);
  }
}

@@ -280,17 +280,16 @@
 quest;%0A%0A
-%0A
 public c
@@ -331,17 +331,16 @@
 xyBox%0A%7B%0A
-%0A
   protec
@@ -618,67 +618,8 @@
 y %7B%0A
-      System.err.println(%22**** SESSIONID: %22 + sessionID);%0A%0A
     
@@ -1184,55 +1184,8 @@
 );%0A%0A
-        /*%0A        TODO: uncomment to activate%0A
     
@@ -1243,71 +1243,8 @@
 ) %7B%0A
-          System.err.println(%22*************** NOT LOGGED IN%22);%0A
     
@@ -1364,101 +1364,8 @@
   %7D%0A
-        */%0A%0A        System.err.println(%22**************************SETTING SESSION*********%22);
 %0A   

Enable Session access control.