/* (non-Javadoc)
@see org.jdiameter.common.api.app.IAppSessionDataFactory#getAppSessionData(java.lang.Class, java.lang.String)
518657
@Override
  public IAccSessionData getAppSessionData(Class<? extends AppSession> clazz, String sessionId) {
    if (clazz.equals(ClientAccSession.class)) {
      ClientAccSessionDataLocalImpl data = new ClientAccSessionDataLocalImpl();
      data.setSessionId(sessionId);
      return data;
    }
    else if (clazz.equals(ServerAccSession.class)) {
      ServerAccSessionDataLocalImpl data = new ServerAccSessionDataLocalImpl();
      data.setSessionId(sessionId);
      return data;
    }
    throw new IllegalArgumentException(clazz.toString());
  }
1000174
public IHttpSessionContext getSessionContext(DeployedModule webModuleConfig, WebApp ctx, 
                                                 String vhostName,  ArrayList sessionRelatedListeners[]) throws Throwable {  
        if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) {
            LoggingUtil.SESSION_LOGGER_CORE.entering(methodClassName, methodNames[GET_SESSION_CONTEXT]);
        }
        if (!initialized)
            initialize(); 
        
        boolean sessionSharing = getSharing(ctx);

        //gets the appropriate appKey to use as a key for the sessionContexts
        //This takes into consideration sessionSharing
        String appKey = getAppKey(vhostName, webModuleConfig, sessionSharing, false);//sessionSharing);
        String appSessionAppKey = getAppKey(vhostName, webModuleConfig, sessionSharing, true); //true is to tell us to use either the applevel or BLA level

        SessionManagerConfig smc = getSMC(webModuleConfig); 

        // cmd LIDB2842 - start block
        //  Use global sessions only if session management config has
        //  not been overridden at the EAR or WAR level.  If the session
        //  management config HAS been overridden, issue info message and
        //  give the app its own context so its sessions will not be global.
        //  This behavior was necessary because the admin application requires
        //  its own config to ensure it always runs session-in-memory.
        //
        if ((_globalSessionContext) && (smc.isUsingWebContainerSM())) {
            appKey = "GLOBAL_HTTP_SESSION_CONTEXT";
            sessionSharing = true;
        } else if (_globalSessionContext) {
            String parm[] = { appKey};
            LoggingUtil.SESSION_LOGGER_CORE.logp(Level.INFO, methodClassName, methodNames[GET_SESSION_CONTEXT], "SessionContextRegistry.SessionNotGlobalForWebApp", parm);
        }

        //cloning to support programmatic session cookie configuration
        //always clone!!!
        smc = smc.clone();
        //don't set here as we're still using the base config - just changing the cookie/url properties
        //smc.setUsingWebContainerSM(false);
        if (smc.isUseContextRootForSessionCookiePath()) {
            //setting the cookie path to the context path
            if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) {
                LoggingUtil.SESSION_LOGGER_CORE.logp(Level.FINE, methodClassName, methodNames[GET_SESSION_CONTEXT], "Setting the cookie path to \""+ctx.getContextPath()+"\" for application - "+ appKey);
            }
            smc.setSessionCookiePath(ctx.getContextPath());
        }
        if (!ctx.getConfiguration().isModuleSessionTrackingModeSet()) {
            EnumSet<SessionTrackingMode> trackingModes = EnumSet.noneOf(SessionTrackingMode.class);
            if (smc.getEnableCookies()) {
                trackingModes.add(SessionTrackingMode.COOKIE);
            }
            if (smc.getEnableUrlRewriting()) {
                trackingModes.add(SessionTrackingMode.URL);
            }
            if (smc.useSSLId()) {
                trackingModes.add(SessionTrackingMode.SSL);
            }
            ctx.getConfiguration().setDefaultSessionTrackingMode(trackingModes);
        }

        IHttpSessionContext iSctx = (IHttpSessionContext) scrSessionContexts.get(appKey);

        if (iSctx != null) {
            LoggingUtil.SESSION_LOGGER_CORE.logp(Level.INFO, methodClassName, methodNames[GET_SESSION_CONTEXT], "SessionContextRegistry.existingContext", appKey);
            SessionContext wsCtx = (SessionContext) iSctx;
            if (sessionSharing)
                wsCtx.incrementRefCount();
        } else {
            LoggingUtil.SESSION_LOGGER_CORE.logp(Level.INFO, methodClassName, methodNames[GET_SESSION_CONTEXT], "SessionContextRegistry.newContext", appKey);
            ClassLoader sessionClassLoader = getSessionClassLoader(webModuleConfig);
            iSctx = createSessionContext(
                                         appKey,
                                         isDistributable(webModuleConfig),
                                         isAllowDispatchRemoteInclude(webModuleConfig),
                                         ctx,
                                         sessionClassLoader,
                                         smc,
                                         getJ2EEName(webModuleConfig),
                                         sessionSharing,
                                         appSessionAppKey);
        }

        //make sure they are the same object
        ctx.getConfiguration().setSessionCookieConfig(iSctx.getWASSessionConfig().getSessionCookieConfig());
        //clone in SessionContext does not update this smc object but the _smc object in SessionContext
        //ctx.getConfiguration().setSessionManagerConfigBase(smc);
        ctx.getConfiguration().setSessionManagerConfig(iSctx.getWASSessionConfig());

        ArrayList sessionListeners = sessionRelatedListeners[0];  
        ArrayList sessionAttrListeners = sessionRelatedListeners[1];  
        ArrayList sessionIdListeners = sessionRelatedListeners[2];  // Servlet 3.1 

        String j2eeName = null;
        if ((_globalSessionContext && sessionSharing) || ((SessionContext)iSctx)._sap.getHasApplicationSession()) {
            // for global session, pass j2eename with listeners so we can stop listeners for each app
            j2eeName = getJ2EEName(webModuleConfig); 
        }
        //  add listeners to session context
        SessionContext sessCtx = (SessionContext)iSctx;
        sessCtx.addHttpSessionListener(sessionListeners, j2eeName);  
        
        // Servlet 3.1
        if (!sessionIdListeners.isEmpty()) {
           addHttpSessionIdListeners(sessionIdListeners, j2eeName, sessCtx);      
        }
        sessCtx.addHttpSessionAttributeListener(sessionAttrListeners, j2eeName);  
        
        if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) {
            LoggingUtil.SESSION_LOGGER_CORE.exiting(methodClassName, methodNames[GET_SESSION_CONTEXT], iSctx);
        }
        return iSctx;
    }
779752
@Override
    public HttpSession getSession() {
        try {
            collaborator.preInvoke(componentMetaData);
            return request.getSession();
        } finally {
            collaborator.postInvoke();
        }
    }
626619
public void initializeSession()
    {
        ApplicationSessionInitializer asi = getApplicationSessionInitializer();
        if (asi != null)
        {
            asi.initializeSession();
            Map<String, Object> sessionAttributes = asi.getSessionAttributes();
            if (sessionAttributes != null)
            {
                    setSessionAttributes(sessionAttributes);
            }
            propertyChangeSupport.firePropertyChange(SESSION_ATTRIBUTES, null, sessionAttributes);
        }
    }
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;
    }
1178558
public MobicentsSipApplicationSession getApplicationSession(boolean create) {		
		
		//First check if the http session has the app session id in its attributes		
		SipApplicationSessionKey key = null;
		// need to check if the session is still valid
		if(httpSession.isValidIntern()) {	
			key = (SipApplicationSessionKey) httpSession.getAttribute(APPLICATION_SESSION_ID_ATTRIBUTE_NAME); 
		}
		SipContext sipContext = (SipContext)sipManager.getContainer();
		if(key != null) {
			MobicentsSipApplicationSession sipAppSession = sipManager.getSipApplicationSession(key, false);
			if (sipAppSession != null) {
				// make sure to acquire this app session and add it to the set of app sessions we monitor in the context of the application
				// to release them all when we exit application code
				sipContext.enterSipApp(sipAppSession, null, true, true);
				return sipAppSession;
			} else {
				if(logger.isDebugEnabled()) {
					logger.debug(key + " found in http session " + httpSession.getId() + " but not present in the manager. already invalidated ? creating new sip application session");
				}
			}
		}
		
		//Otherwise proceed as normally
		
		//the application session if currently associated is returned,
		MobicentsSipApplicationSession sipApplicationSession =
			sipManager.findSipApplicationSession(httpSession);
		if(sipApplicationSession == null && create) {
			//however if no application session is associated it is created, 
			//associated with the HttpSession and returned.
			
			//not needed anymore since the sipappsesionkey is not a callid anymore but a rnadom uuid
//			ExtendedListeningPoint listeningPoint = 
//				sipNetworkInterfaceManager.getExtendedListeningPoints().next();						
			SipApplicationSessionKey sipApplicationSessionKey = SessionManagerUtil.getSipApplicationSessionKey(
					sipContext.getApplicationName(), 
					null,
					null);
			
			sipApplicationSession = 
				sipManager.getSipApplicationSession(sipApplicationSessionKey, true);
			
			// Store the App Session ID in the HTTP sessions to recover it from there when it's transfered to a new node.
			httpSession.setAttribute(APPLICATION_SESSION_ID_ATTRIBUTE_NAME, 
					sipApplicationSession.getKey());
			sipApplicationSession.addHttpSession(httpSession);			
		}
		if(sipApplicationSession != null) {
			// make sure to acquire this app session and add it to the set of app sessions we monitor in the context of the application
			// to release them all when we exit application code
			sipContext.enterSipApp(sipApplicationSession, null, true, true);
			return sipApplicationSession.getFacade();
		} else {
			return null;
		}
//		return sipApplicationSession;
	}
1339397
public IHttpSessionContext getSessionContext(DeployedModule moduleConfig, WebApp webApp, String host, ArrayList[] listeners) throws Throwable {
        try {
            return getSessionRegistry().getSessionContext(moduleConfig, webApp, host, listeners);
        } catch (Throwable e) {
            //Translated to SRVE8059E: An unexpected exception occurred when trying to retrieve the session context
            logger.logp(Level.SEVERE, CLASS_NAME, "getSessionContext", nls.getString("unable.to.get.sessionContext"), e); /* 283348.1 */
            return null;
        }

    }
1177307
@Override
	public synchronized List<RecordSessionUrl> getUrlsForType (int type) throws DatabaseException {
    	try {
			psGetAlluRLSForType.setInt(1, type);
			try (ResultSet rs = psGetAlluRLSForType.executeQuery()) {
				List<RecordSessionUrl> result = new ArrayList<>();
				while (rs.next()) {
					result.add(new RecordSessionUrl(rs.getLong(URLID), rs.getInt(TYPE), rs.getString(URL)));
				}
				return result;
			}
		} catch (SQLException e) {
			throw new DatabaseException(e);
		}
    }
148715
@SuppressWarnings("rawtypes")
    private void getMultiRowAppData() {
        populatedAppData = true;
        Map<Object, Object> swappable = getSwappableData();
        Hashtable props = (Hashtable) ((CacheHashMap) getSessions()).getAllValues(this);
        if (props != null) {
            Enumeration kys = props.keys();
            while (kys.hasMoreElements()) {
                Object key = kys.nextElement();
                swappable.put(key, props.get(key));
            }
            synchronized (_attributeNames) {
                refillAttrNames(swappable);
            }
        }
    }
909588
@Override
    public Object getSession(ServletRequest request, ServletResponse response, SessionAffinityContext affinityContext, boolean create) {

        /*
         * Check to see if the request provides a JSESSIONID cookie
         */
        String sessionID = _sam.getInUseSessionID(request, affinityContext);
        int sessionVersion = _sam.getInUseSessionVersion(request, affinityContext); // affinityContext.getRequestedSessionVersion();
        ISession session = null;

        /*
         * If the sessionID is not null, this may be a request with an existing
         * session.
         */
        if (sessionID != null) {
            session = (ISession) getSession(sessionID, sessionVersion, true, null);
            if (session == null && affinityContext.isRequestedSessionIDFromCookie() // perform allIds call and reset sac
                            && !affinityContext.isAllSessionIdsSetViaSet()){  //PM89885 add another check for isAllSessionIdsSetViaSet since we may have done a set in HttpSessionContextImpl.getIHttpSession
                List allSessionIds = _sam.getAllCookieValues(request);
                affinityContext.setAllSessionIds(allSessionIds);
            }
        }

        while ((session == null) && (_sam.setNextId(affinityContext))) {
            sessionID = _sam.getInUseSessionID(request, affinityContext);
            sessionVersion = _sam.getInUseSessionVersion(request, affinityContext); // affinityContext.getRequestedSessionVersion();
            session = (ISession) getSession(sessionID, sessionVersion, true, null);
        }

        /*
         * If the session is null, create a new one if required. The session manager
         * will check
         * to see if an alternate webmodule has a session created using
         * this session id. If not, the session object returned may have a different
         * session id from the one supplied.
         */
        if ((session == null) && create) {
            boolean reuseThisID = false;
            if (_store.getShouldReuseId() || affinityContext.isResponseIdSet() || affinityContext.isRequestedSessionIDFromSSL()) {
                reuseThisID = true;
            }
            session = createISession(sessionID, sessionVersion, reuseThisID);
        }

        return adaptAndSetCookie(request, response, affinityContext, session);

    }
999603
@Override
  public IAccSessionData getAppSessionData(Class<? extends AppSession> clazz, String sessionId) {
    if (clazz.equals(ClientAccSession.class)) {
      ClientAccSessionDataReplicatedImpl data =
          new ClientAccSessionDataReplicatedImpl(sessionId, this.mobicentsCluster, this.replicatedSessionDataSource.getContainer());
      return data;
    }
    else if (clazz.equals(ServerAccSession.class)) {
      ServerAccSessionDataReplicatedImpl data = new ServerAccSessionDataReplicatedImpl(sessionId, this.mobicentsCluster);
      return data;
    }
    throw new IllegalArgumentException();
  }
52658
@Override
    public Session getSession() {
        return state.get() > GlobalState.INITIALISING ? new Session(dataMgr.getSessionDAO().session()) : new Session();
    }
1246659
public HttpSession getSelectedSession() {
		final int selectedRow = this.sessionsTable.getSelectedRow();
		if (selectedRow == -1) {
			// No row selected
			return null;
		}
		final int rowIndex = sessionsTable.convertRowIndexToModel(selectedRow);
		return this.sessionsModel.getHttpSessionAt(rowIndex);
	}
412305
private void getSingleRowAppData() {
        if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINER)) {
            LoggingUtil.SESSION_LOGGER_WAS.entering(methodClassName, methodNames[GET_SINGLE_ROW_APP_DATA]);
        }
        populatedAppData = true;
        Hashtable swappable = (Hashtable) ((DatabaseHashMap) getSessions()).getValue(getId(), this);
        setSwappableData(swappable);
        synchronized (_attributeNames) {
            refillAttrNames(swappable);
        }
        if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINER)) {
            LoggingUtil.SESSION_LOGGER_WAS.exiting(methodClassName, methodNames[GET_SINGLE_ROW_APP_DATA]);
        }
    }
1002763
@Override
  public ICxDxSessionData getAppSessionData(Class<? extends AppSession> clazz, String sessionId) {
    if (clazz.equals(ClientCxDxSession.class)) {
      ClientCxDxSessionDataReplicatedImpl data =
          new ClientCxDxSessionDataReplicatedImpl(sessionId, this.mobicentsCluster, this.replicatedSessionDataSource.getContainer());
      return data;
    }
    else if (clazz.equals(ServerCxDxSession.class)) {
      ServerCxDxSessionDataReplicatedImpl data =
          new ServerCxDxSessionDataReplicatedImpl(sessionId, this.mobicentsCluster, this.replicatedSessionDataSource.getContainer());
      return data;
    }
    throw new IllegalArgumentException();
  }
580158
@Override
  public AppSession getSession(String sessionId, Class<? extends AppSession> aClass) {
    if (sessionId == null) {
      throw new IllegalArgumentException("SessionId must not be null");
    }
    if (!this.iss.exists(sessionId)) {
      return null;
    }
    AppSession appSession = null;
    try {
      if (aClass == ClientAccSession.class) {
        IClientAccSessionData data = (IClientAccSessionData) this.sessionDataFactory.getAppSessionData(ClientAccSession.class, sessionId);
        ClientAccSessionImpl clientSession =
            new ClientAccSessionImpl(data, sessionFactory, getClientSessionListener(), getClientContextListener(), getStateListener());

        clientSession.getSessions().get(0).setRequestListener(clientSession);
        appSession = clientSession;
      }
      else if (aClass == ServerAccSession.class) {
        ServerAccSessionImpl serverSession = null;
        IServerAccSessionData data = (IServerAccSessionData) this.sessionDataFactory.getAppSessionData(ServerAccSession.class, sessionId);

        //here we use shorter con, since some data is already present.
        serverSession = new ServerAccSessionImpl(data, sessionFactory,  getServerSessionListener(), getServerContextListener(), getStateListener());
        serverSession.getSessions().get(0).setRequestListener(serverSession);
        appSession = serverSession;
      }
      else {
        throw new IllegalArgumentException("Wrong session class: " + aClass + ". Supported[" + ClientAccSession.class + "," + ServerAccSession.class + "]");
      }
    }
    catch (Exception e) {
      logger.error("Failure to obtain new Accounting Session.", e);
    }

    return appSession;
  }
1159862
public ChatRoomListResult getAppChatRoomInfo(int start, int count)
            throws APIConnectionException, APIRequestException {
        return _chatRoomClient.getAppChatRoomInfo(start, count);
    }