public String registerSession ( User user , int expireDays ) throws PersistenceException { // look for an existing session for this user final String query = "select authcode from sessions where userId = " + user . userId ; String authcode = execute ( new Operation < String > ( ) { public String invoke ( Connection conn , DatabaseLiaison liaison ) throws PersistenceException , SQLException { Statement stmt = conn . createStatement ( ) ; try { ResultSet rs = stmt . executeQuery ( query ) ; while ( rs . next ( ) ) { return rs . getString ( 1 ) ; } return null ; } finally { JDBCUtil . close ( stmt ) ; } } } ) ; // figure out when to expire the session Calendar cal = Calendar . getInstance ( ) ; cal . add ( Calendar . DATE , expireDays ) ; Date expires = new Date ( cal . getTime ( ) . getTime ( ) ) ; // if we found one, update its expires time and reuse it if ( authcode != null ) { update ( "update sessions set expires = '" + expires + "' where " + "authcode = '" + authcode + "'" ) ; } else { // otherwise create a new one and insert it into the table authcode = UserUtil . genAuthCode ( user ) ; update ( "insert into sessions (authcode, userId, expires) values('" + authcode + "', " + user . userId + ", '" + expires + "')" ) ; } return authcode ; }
Creates a new session for the specified user and returns the randomly generated session identifier for that session . If a session entry already exists for the specified user it will be reused .