Generate session id hash if it doesn't exist in TraceeBackend and configuration asks for one

@param backend   Currently used TraceeBackend
@param sessionId Current http sessionId
965561
public static void generateSessionIdIfNecessary(final TraceeBackend backend, final String sessionId) {
		if (backend != null && !backend.containsKey(TraceeConstants.SESSION_ID_KEY) && backend.getConfiguration().shouldGenerateSessionId()) {
			backend.put(TraceeConstants.SESSION_ID_KEY, Utilities.createAlphanumericHash(sessionId, backend.getConfiguration().generatedSessionIdLength()));
		}
	}
1088858
public void createSession(String sessionId) {
        boolean newSession = sessionId == null;
        sessionId = newSession ? newSessionId() : sessionId;
        SessionController controller = sessions.get(sessionId);
        
        if (controller == null) {
            controller = SessionController.create(sessionId, newSession);
            sessions.put(sessionId, controller);
        }
    }
34067
public synchronized ID addOnline(final USER user, final ID sessionId)
	{
		sessionIdToUser.put(sessionId, user);
		return usersOnline.put(user, sessionId);
	}
1269373
public static void setCurrentTraceId(String id) {
    if (id == null) {
      traceId.remove();
    } else {
      traceId.set(id);
    }
  }
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;
    }
260372
protected function validateBrokerSessionId(string $sessionId)
    {
        $matches = null;

        if (!preg_match('/^SSO-(\w*+)-(\w*+)-([a-z0-9]*+)$/', $this->getBrokerSessionId(), $matches)) {
            $this->fail('Invalid session id');
        }

        if ($this->generateSessionId($matches[1], $matches[2]) != $sessionId) {
            $this->fail('Checksum failed: Client IP address may have changed');
        }

        return $matches[1];
    }
596344
private void passivateSession(BackedSession sess) {
        synchronized (sess) { // Keep PropertyWriter thread from sneaking in..

            if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
                LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[PASSIVATE_SESSION], "check for Passivation Listener for session");
            }

            // note that sessionCacheDiscard was called by LRUHashMap.put when he had to eject the oldest
            getStoreCallback().sessionWillPassivate(sess);

            if (_smc.getEnableTimeBasedWrite() || _smc.getPersistSessionAfterPassivation()) {
                // Since removing from the cache... Need to write the session to the database
                //  Don't bother checking if this session is in the service method
                //  as it is the oldest entry in the cache.
                // Need to also write the session if passivate updated any attributes.
                if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
                    if (_smc.getEnableTimeBasedWrite()) {
                        LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[PASSIVATE_SESSION],
                                                            "Removing oldest entry from cache with TimeBasedWrits. Write it! " + sess.getId() + " " + getAppName());
                    } else {
                        LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[PASSIVATE_SESSION],
                                                            "Persisting the session after it was passivated. " + sess.getId() + " " + getAppName());
                    }
                }
                sess.removingSessionFromCache = true;
                sess.sync();
                sess.removingSessionFromCache = false;
            }
        }
    }
933540
@Nonnull
    public String createLockName( @Nonnull final String sessionId ) {
        if ( sessionId == null ) {
            throw new IllegalArgumentException( "The sessionId must not be null." );
        }
        return "lock:" + _storageKeyFormat.format(sessionId);
    }
996381
protected void onAfterDeleteFromMemcached( @Nonnull final String sessionId ) {
        final long start = System.currentTimeMillis();

        final String validityInfoKey = _sessionIdFormat.createValidityInfoKeyName( sessionId );
        _storage.delete( validityInfoKey );

        if (_storeSecondaryBackup) {
            try {
                _storage.delete(_sessionIdFormat.createBackupKey(sessionId));
                _storage.delete(_sessionIdFormat.createBackupKey(validityInfoKey));
            } catch (Exception e) {
                _log.info("Could not delete backup data for session " + sessionId + " (not critical, data will be evicted by memcached automatically).", e);
            }
        }

        _stats.registerSince( NON_STICKY_AFTER_DELETE_FROM_MEMCACHED, start );
    }
10492
public void setStateBackend(StateBackend backend) {
		if (backend != null) {
			try {
				InstantiationUtil.writeObjectToConfig(backend, this.config, STATE_BACKEND);
			} catch (Exception e) {
				throw new StreamTaskException("Could not serialize stateHandle provider.", e);
			}
		}
	}
153974
private byte[] createApplicationId(String userDir, String serverName, String hostName) {
        final boolean traceOn = TraceComponent.isAnyTracingEnabled();
        if (tc.isEntryEnabled())
            Tr.entry(tc, "createApplicationId", new Object[] { userDir, serverName, hostName });
        byte[] result;

        try {
            // tWAS - Create a dummy IOR based on this host's IP address and server's port
            // tWAS - Note: the object must be remoteable, so use Current as an example.
            // tWAS - String s = CORBAUtils.getORB().object_to_string(CurrentImpl.instance());
            // On Liberty concatenate the user directory, the server name and the host name. Then add in the time.
            String s = userDir + serverName + hostName + System.currentTimeMillis();
            // Create a 20-byte hash value using a secure one-way hash function
            result = java.security.MessageDigest.getInstance("SHA").digest(s.getBytes());
        } catch (Throwable t) {
            FFDCFilter.processException(t, "com.ibm.ws.transaction.createApplicationId", "608", this);
            String tempStr = "j" + (System.currentTimeMillis() % 9997) + ":" + userDir + hostName;
            result = tempStr.getBytes();
        }

        if (traceOn && tc.isEntryEnabled())
            Tr.exit(tc, "createApplicationId", Util.toHexString(result));
        return result;
    }
500716
protected void setIdForRelocate( final String id ) {

        if ( this.id == null ) {
            throw new IllegalStateException( "There's no session id set." );
        }
        if ( this.manager == null ) {
            throw new IllegalStateException( "There's no manager set." );
        }

        /*
         * and mark it as a node-failure-session, so that remove(session) does
         * not try to remove it from memcached... (the session is removed and
         * added when the session id is changed)
         */
        setNote( MemcachedSessionService.NODE_FAILURE, Boolean.TRUE );
        manager.remove( this );
        removeNote( MemcachedSessionService.NODE_FAILURE );
        this.id = id;
        manager.add( this );

    }
1314688
@Override
    public String changeSessionId() {
        WebApp webapp = ((WebAppDispatcherContext) this._dispatchContext).getWebApp();
        
        HttpSession thisSession = ((SRTRequestContext31)_requestContext).generateNewId(webapp);
        
        return thisSession.getId();
    }
1014709
private static String getServerIdString(String id) {

        if (id.contains(CmsADEManager.CLIENT_ID_SEPERATOR)) {
            id = id.substring(0, id.indexOf(CmsADEManager.CLIENT_ID_SEPERATOR));
        }
        return id;
    }
1247054
public String getID() {
        byte[] genBytes = new byte[_byteArraySize];
        synchronized (_random) {
            _random.nextBytes(genBytes);
        }
        String id = convertSessionIdBytesToSessionId(genBytes, _sessionIDLength);
        if (tc.isDebugEnabled()) {
            Tr.debug(tc, "sessionID=" + id);
        }
        return id;
    }
945940
@Override
    public Session newSession(String id) {
        long created = System.currentTimeMillis();
        Session session = sessionCache.newSession(id, created, (defaultMaxIdleSecs > 0 ? defaultMaxIdleSecs * 1000L : -1));
        try {
            sessionCache.put(id, session);
            sessionsCreatedStats.increment();

            for (SessionListener listener : sessionListeners) {
                listener.sessionCreated(session);
            }

            return session;
        } catch (Exception e) {
            log.warn("Failed to create a new session", e);
            return null;
        }
    }
50189
def append_session_id_parameter
      return unless request # for test process
      return unless apply_trans_sid?
      return unless jpmobile_session_id

      response.body = response.body.gsub(%r{(</form>)}i, sid_hidden_field_tag + '\1')
    end