compute session id for JDBC operations
767802
@NotNull
    public static String computeSessionId(@NotNull final String aString) {
        final byte[] byteData = DigestUtils.sha256(aString.getBytes());
        final StringBuilder sb = new StringBuilder("SQLQuery:");

        for (final byte aByteData : byteData) {
            final String hex = Integer.toHexString(0xFF & aByteData);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }
894437
def get_db_version(session):
    
    value = session.query(ProgramInformation.value).filter(ProgramInformation.name == "db_version").scalar()
    return int(value)
994820
public String getSessionid(boolean create) {
        String sessionid = getCookie(SESSIONID_NAME, null);
        if (create && (sessionid == null || sessionid.isEmpty())) {
            sessionid = context.createSessionid();
            this.newsessionid = sessionid;
        }
        return sessionid;
    }
188735
def get_session_data( username, password_verifier, salt, client_public, private, preset):
    """"""
    session = SRPServerSession(
        SRPContext(username, prime=preset[0], generator=preset[1]),
        hex_from_b64(password_verifier), private=private)

    session.process(client_public, salt, base64=True)

    click.secho('Server session key: %s' % session.key_b64)
    click.secho('Server session key proof: %s' % session.key_proof_b64)
    click.secho('Server session key hash: %s' % session.key_proof_hash_b64)
402876
def _conn_string_adodbapi(self, db_key, instance=None, conn_key=None, db_name=None):
        ''' 
        '''
        if instance:
            _, host, username, password, database, _ = self._get_access_info(instance, db_key, db_name)
        elif conn_key:
            _, host, username, password, database, _ = conn_key.split(":")

        p = self._get_adoprovider(instance)
        conn_str = 'Provider={};Data Source={};Initial Catalog={};'.format(p, host, database)

        if username:
            conn_str += 'User ID={};'.format(username)
        if password:
            conn_str += 'Password={};'.format(password)
        if not username and not password:
            conn_str += 'Integrated Security=SSPI;'
        return conn_str
1187968
public String getID() {
        byte[] genBytes = new byte[_byteArraySize];
        synchronized(_random) {
            _random.nextBytes(genBytes);
        }
        String id = convertSessionIdBytesToSessionId(genBytes, _sessionIDLength);
        if (logger.isLoggable(Level.FINE)) {
            logger.logp(Level.FINE, methodClassName, "getSessionID", "sessionID=" + id);
        }
        return id;
    }
1342095
def get_appium_sessionId(self):
        """"""
        self._info("Appium Session ID: " + self._current_application().session_id)
        return self._current_application().session_id
309272
private String getSessionId(final HttpSession sess) {
    try {
      if (sess == null) {
        return "NO-SESSIONID";
      } else {
        return sess.getId();
      }
    } catch (Throwable t) {
      return "SESSION-ID-EXCEPTION";
    }
  }
911149
BackedSession retrieveSession(String id, int versionId, BackedSession inMemSess) {
        //create local variable - JIT performance improvement
        final boolean isTraceOn = com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled();
        boolean useTheInMemSess = false;
        long lastAccessedTimeOnLocalCopy = 0;
        if (inMemSess != null && inMemSess.isValid()) {
            lastAccessedTimeOnLocalCopy = inMemSess.getCurrentAccessTime();
        }
        long lastAccessTimeOnBackendCopy = 0;

        if (isTraceOn && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINER)) {
            StringBuffer sb = new StringBuffer("{").append(id).append(",").append(versionId).append(",").append(lastAccessedTimeOnLocalCopy).append("}");
            LoggingUtil.SESSION_LOGGER_WAS.entering(methodClassName, methodNames[RETRIEVE_SESSION], sb.toString());
        }
        BackedSession sess = null;
        sess = (BackedSession) superGet(id);
        if (sess != null) {
            if (isTraceOn && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINER)) {
                LoggingUtil.SESSION_LOGGER_WAS.exiting(methodClassName, methodNames[RETRIEVE_SESSION], "Found session in local cache.");
            }
            return sess;
        }

        if (isPresentInRecentlyInvalidatedList(id)) {
            if (isTraceOn && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINER)) {
                LoggingUtil.SESSION_LOGGER_WAS.exiting(methodClassName, methodNames[RETRIEVE_SESSION], "null - Id present in recently invalidated list.");
            }
            return null;
        }

        sess = readFromExternal(id);

        //Make sure only one copy of session object is in cache
        //and the same copy is returned to concurrent requests
        //entering here.
        boolean cacheIdUpdate = false;
        if (sess != null) {
            lastAccessTimeOnBackendCopy = sess.getCurrentAccessTime();
            BackedSession thrownOutSess = null;
            synchronized (this) {
                BackedSession ds = (BackedSession) superGet(id);
                if (ds == null) {
                    if (!_isApplicationSessionHashMap) { // don't update versionId for appSessions as this could update it twice.  We don't have a good solution for appSessions yet.
                        cacheIdUpdate = true;
                    }
                    //If it is Time-based or manual writes, we could have not updated the backend yet.  If we retrieve an
                    //old version from the backend, have another server update the backend with this version #, then we
                    //update the backend with this version #, both servers could think that they have a valid id in their
                    //local cache.  We want to do the lastAccessTimes check for endOfService writes so that we don't thrash
                    //on a failover.
                    //PK47847 allows us to check the lastAccessTimes for !EOS writes.  The customer should be on one machine or have their times set to be identical.
                    //before we always updated the cache ... must maintain behavior
                    if (_smc.getEnableEOSWrite() || _smc.getOptimizeCacheIdIncrements()) {
                        if (lastAccessedTimeOnLocalCopy == lastAccessTimeOnBackendCopy ||
                                ((lastAccessedTimeOnLocalCopy > lastAccessTimeOnBackendCopy) && _smc.getOptimizeCacheIdIncrements())) {
                            //use the in-memory copy && don't update the cache
                            //when the lastAccessedTimeOnLocalCopy>lastAccessTimeOnBackendCopy we
                            //only want to use the in-memory copy (even when using EOS) when the property is set
                            if (isTraceOn && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
                                LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[RETRIEVE_SESSION], "Using in-memory session instead of retrieved.");
                            }
                            cacheIdUpdate = false;
                            sess = inMemSess;
                            useTheInMemSess = true;
                        }
                    }
                    thrownOutSess = (BackedSession) superPut(id, sess);
                    //update to current version ... if cacheIdUpdate is true, we will increment from this value
                    sess.setVersion(versionId);
                    sess.setIsNew(false);
                } //end if (ds=null)
                else {
                    //Make sure we have only one instance
                    sess = ds;
                }
            }
            if (thrownOutSess != null && !useTheInMemSess)
                this.passivateSession(thrownOutSess);
        } else {
            if (isTraceOn && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINER)) {
                LoggingUtil.SESSION_LOGGER_WAS.exiting(methodClassName, methodNames[RETRIEVE_SESSION], "Session is not found on backend");
            }
            return null;
        }

        synchronized (sess) {
            long nowTime = System.currentTimeMillis();
            long prevLastAccess = sess.getCurrentAccessTime(); // cmd 200713

            //Update the row with current timestamp
            int rowCount = -1;
            if (prevLastAccess < nowTime) {
                rowCount = updateLastAccessTime(sess, nowTime);
            } else {
                //if this request was served by an another clone on a different
                //machine then it is possible that nowTime of system is less
                //than lastaccesstime in session, if there  is time diff between
                //boxes
                nowTime = prevLastAccess;
            }

            if (rowCount == 0) {
                superRemove(sess.getId());
                sess = null;
                if (isTraceOn && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINER)) {
                    LoggingUtil.SESSION_LOGGER_WAS.exiting(methodClassName, methodNames[RETRIEVE_SESSION], "null - updateLastAccessTime failed.");
                }
                return sess;
            }

            sess.updateLastAccessTime(nowTime);
            sess.setLastWriteLastAccessTime(nowTime);

            sess.initSession(_iStore);
            if ((!useTheInMemSess) &&
                    (sess.getSwappableListeners(BackedSession.HTTP_SESSION_ACTIVATION_LISTENER) ||
                    SessionManagerConfig.is_zOS())) { // cmd 420285 must call for zOS to re-establish affinity
                getStoreCallback().sessionDidActivate(sess); // call activation listeners
            }
        }

        if (cacheIdUpdate) {
            updateCacheId(sess);
        }
        if (isTraceOn && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINER)) {
            LoggingUtil.SESSION_LOGGER_WAS.exiting(methodClassName, methodNames[RETRIEVE_SESSION], "session found");
        }
        return sess;
    }
226976
@Override
    public boolean idExists(String id) {
        if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) {
            LoggingUtil.SESSION_LOGGER_CORE.entering(methodClassName, methodNames[ID_EXISTS], id);
        }

        Object sessInUse;
        boolean found = false;

        SessionManagerRegistry _sessionManagerRegistry = SessionManagerRegistry.getSessionManagerRegistry();
        // Since the session manager can be configured per application, we need to
        // look at
        // each entry individually since some of the contexts can have database/mtm
        // persistence
        // enabled while others are using memory

        // Look in memory first for improved performance
        Enumeration vEnum = _sessionManagerRegistry.getSessionManagers();
        IStore tempStore;
        while (vEnum.hasMoreElements() && !found) {
            IGenericSessionManager sm = (IGenericSessionManager) vEnum.nextElement();
            if (sm == null) // || sm == this)
                continue;
            tempStore = sm.getIStore();
            if (tempStore == this)
                continue; // don't bother checking our own store
            sessInUse = tempStore.getFromMemory(id);
            if (sessInUse != null)
                found = true;
        }

        if (found) {
            if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINER)) {
                String s = "Found in Cache/Mem";
                LoggingUtil.SESSION_LOGGER_CORE.exiting(methodClassName, methodNames[ID_EXISTS], s);
            }
            return found;
        }

        // Check our current external store first.
        // This is probably the most likely
        // Also, if the sessionId has been recently invalidated and
        // checkRecentlyInvalidList is true, we should return true without checking
        // other backends.
        found = this.isPresentInExternalStore(id);
        if (found) {
            if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) {
                LoggingUtil.SESSION_LOGGER_CORE.exiting(methodClassName, methodNames[ID_EXISTS], Boolean.valueOf(found));
            }
            return found;
        }

        // Search the persistent stores for the sessionid
        Enumeration enum3 = _sessionManagerRegistry.getSessionManagers();
        while (enum3.hasMoreElements()) {
            IGenericSessionManager sm = (IGenericSessionManager) enum3.nextElement();
            if (sm == null) // || sm == this)
                continue;
            else {
                tempStore = sm.getIStore();
                if (tempStore == this)
                    continue; // don't bother checking our own store as we already checked
                              // it above
                found = tempStore.isPresentInExternalStore(id);
                if (found) {
                    break;
                }
            }
        }

        if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINER)) {
            String s = "After persistent store scan returning: " + found;
            LoggingUtil.SESSION_LOGGER_CORE.exiting(methodClassName, methodNames[ID_EXISTS], s);
        }

        return found;
    }
531994
Table SYSTEM_USERS() {

        Table t = sysTables[SYSTEM_USERS];

        if (t == null) {
            t = createBlankTable(sysTableHsqlNames[SYSTEM_USERS]);

            addColumn(t, "USER_NAME", SQL_IDENTIFIER);
            addColumn(t, "ADMIN", Type.SQL_BOOLEAN);
            addColumn(t, "INITIAL_SCHEMA", SQL_IDENTIFIER);

            // order: USER
            // true PK
            HsqlName name = HsqlNameManager.newInfoSchemaObjectName(
                sysTableHsqlNames[SYSTEM_USERS].name, false,
                SchemaObject.INDEX);

            t.createPrimaryKey(name, new int[]{ 0 }, true);

            return t;
        }

        PersistentStore store = database.persistentStoreCollection.getStore(t);

        // Intermediate holders
        HsqlArrayList users;
        User          user;
        Object[]      row;
        HsqlName      initialSchema;

        // Initialization
        users = database.getUserManager().listVisibleUsers(session);

        // Do it.
        for (int i = 0; i < users.size(); i++) {
            row           = t.getEmptyRowData();
            user          = (User) users.get(i);
            initialSchema = user.getInitialSchema();
            row[0]        = user.getNameString();
            row[1]        = ValuePool.getBoolean(user.isAdmin());
            row[2]        = ((initialSchema == null) ? null
                                                     : initialSchema.name);

            t.insertSys(store, row);
        }

        return t;
    }
716027
def generate_session_id(self):
        """"""
        secret_key = self._config.secret_key
        while True:
            rand = os.urandom(16)
            now = time.time()
            session_id = sha1(utf8("%s%s%s%s" % (
                rand, now, self.handler.request.remote_ip, secret_key)))
            session_id = session_id.hexdigest()
            if session_id not in self.store:
                break

        return session_id
837849
private int numberOfSessionsInTransaction(String xferId) {
		int sessionCount = 0;
		List<String> sessions = transactionSessions.get(xferId);

		if(sessions != null)
			sessionCount = sessions.size();

		return sessionCount;
	}
1306155
protected BackedSession readFromExternal(String id) {

        PreparedStatement s = null;
        String appName = getIStore().getId();
        Connection con = getConnection(false);

        if (con == null) {
            if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
                LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[READ_FROM_EXTERNAL], "unable to get con when processing session " + id);
            }
            return null;
        }

        DatabaseSession sess = null;

        try {
            sess = readPrimitives(id, appName, con);
        } catch (Throwable th) {
            //            if (isStaleConnectionException(th)) {
            //                com.ibm.ws.ffdc.FFDCFilter.processException(th, "com.ibm.ws.session.store.db.DatabaseHashMap.readFromExternal", "1608", sess);
            //                LoggingUtil.SESSION_LOGGER_WAS.logp(Level.WARNING, methodClassName, methodNames[READ_FROM_EXTERNAL], "StaleConnectionException");
            //            } else {
            com.ibm.ws.ffdc.FFDCFilter.processException(th, "com.ibm.ws.session.store.db.DatabaseHashMap.readFromExternal", "1611", sess);
            LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[READ_FROM_EXTERNAL], "DatabaseHashMap.selectAndLockError");
            LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[READ_FROM_EXTERNAL], "CommonMessage.sessionid", id);
            LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[READ_FROM_EXTERNAL], "CommonMessage.exception", th);
            //            }
        } finally {
            if (s != null) {
                closeStatement(s);
            }
            closeConnection(con); //findbugs 106329
        }
        return sess;
    }
783330
@Override
	public String execute(Connection<?> connection) {
		String localUserId = UUID.randomUUID().toString();
		logger.debug("Local User ID is: {}", localUserId);
		return localUserId;
	}
330171
public String getRequestedSessionId(HttpServletRequest _request)
  {
    SessionAffinityContext sac = getSessionAffinityContext(_request);
      
    if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) {
      LoggingUtil.SESSION_LOGGER_CORE.entering(methodClassName, methodNames[GET_REQUESTED_SESSION_ID], sac.isFirstSessionIdValid());
    }

    String reqSessId = sac.getRequestedSessionID();

    // if we have multiple session ids, the "requested" one is either the
    // first one that is valid, or if none are valid, the first one in the list
    boolean idIsValid = _coreHttpSessionManager.isRequestedSessionIDValid(reqSessId, 0);

    // getSession may or may not have been called. We need to check if the first
    // id is valid and if not, then check if we need to update the allSessionIds
    // list
    if (reqSessId != null && !idIsValid && !sac.isAllSessionIdsSetViaSet()
                    || !sac.isAllSessionIdsSetViaSet() && !sac.isFirstSessionIdValid()) { //PM89885 added || condition
      List allSessionIds = _sam.getAllCookieValues(_request);
      sac.setAllSessionIds(allSessionIds);
    }

    if (sac.getNumSessionIds() > 1)
    {
      if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE))
      {
        LoggingUtil.SESSION_LOGGER_CORE.logp(Level.FINE, methodClassName, methodNames[GET_REQUESTED_SESSION_ID], "multiple incoming ids");
      }
      while (!idIsValid && _sam.setNextId(sac))
      {
        reqSessId = sac.getRequestedSessionID();
        idIsValid = _coreHttpSessionManager.isRequestedSessionIDValid(reqSessId, 0);
      }
      if (!idIsValid)
      {
        if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE))
        {
          LoggingUtil.SESSION_LOGGER_CORE.logp(Level.FINE, methodClassName, methodNames[GET_REQUESTED_SESSION_ID], "none valid - return first");
        }
        reqSessId = sac.getFirstRequestedSessionID();
      }
    } else if (!idIsValid && !sac.isFirstSessionIdValid()){
        // Only session available is the one sent from the client so return that one
        if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) {
          LoggingUtil.SESSION_LOGGER_CORE.logp(Level.FINE, methodClassName, methodNames[GET_REQUESTED_SESSION_ID], "return the only one id sent from client");
        }
        reqSessId = sac.getFirstRequestedSessionID();
    }
    if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE))
    {
      LoggingUtil.SESSION_LOGGER_CORE.exiting(methodClassName, methodNames[GET_REQUESTED_SESSION_ID], reqSessId);
    }
    return reqSessId;
  }
63842
def _session_key(self):
        """"""

        if not hasattr(self, "_cached_session_key"):
            session_id_bytes = self.get_secure_cookie("session_id")
            session_id = None

            if session_id_bytes:
                try:
                    session_id = session_id_bytes.decode('utf-8')
                except:
                    pass

            if not session_id:
                session_id = oz.redis_sessions.random_hex(20)

            session_time = oz.settings["session_time"]
            kwargs = dict(
                name="session_id",
                value=session_id.encode('utf-8'),
                domain=oz.settings.get("cookie_domain"),
                httponly=True,
            )
            if session_time:
                kwargs["expires_days"] = round(session_time/60/60/24)

            self.set_secure_cookie(**kwargs)

            password_salt = oz.settings["session_salt"]
            self._cached_session_key = "session:%s:v4" % oz.redis_sessions.password_hash(session_id, password_salt=password_salt)

        return self._cached_session_key