/*
(non-Javadoc)

@see org.jdiameter.common.api.app.IAppSessionDataFactory#getAppSessionData (java.lang.Class, java.lang.String)
190260
@Override
  public IShSessionData getAppSessionData(Class<? extends AppSession> clazz, String sessionId) {
    if (clazz.equals(ClientShSession.class)) {
      ShClientSessionDataReplicatedImpl data = new ShClientSessionDataReplicatedImpl(sessionId, this.mobicentsCluster);
      return data;
    }
    else if (clazz.equals(ServerShSession.class)) {
      ShServerSessionDataReplicatedImpl data = new ShServerSessionDataReplicatedImpl(sessionId, this.mobicentsCluster);
      return data;
    }
    throw new IllegalArgumentException();
  }
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();
  }
406020
private void getMultiRowAppData() {
        if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
            LoggingUtil.SESSION_LOGGER_WAS.entering(methodClassName, methodNames[GET_MULTI_ROW_APP_DATA]);
        }
        populatedAppData = true;
        Map<Object, Object> swappable = getSwappableData();
        Hashtable props = (Hashtable) ((DatabaseHashMap) 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);
            }
        }
        if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINER)) {
            LoggingUtil.SESSION_LOGGER_WAS.exiting(methodClassName, methodNames[GET_MULTI_ROW_APP_DATA]);
        }
    }
1259132
@Override
  public ICxDxSessionData getAppSessionData(Class<? extends AppSession> clazz, String sessionId) {
    if (clazz.equals(ClientCxDxSession.class)) {
      ClientCxDxSessionDataLocalImpl data = new ClientCxDxSessionDataLocalImpl();
      data.setSessionId(sessionId);
      return data;
    }
    else if (clazz.equals(ServerCxDxSession.class)) {
      ServerCxDxSessionDataLocalImpl data = new ServerCxDxSessionDataLocalImpl();
      data.setSessionId(sessionId);
      return data;
    }
    throw new IllegalArgumentException(clazz.toString());
  }
484338
private final Session getSession (final String targetName) throws NoSuchSessionException {

        final Session session = sessions.get(targetName);

        if (session != null) {
            return session;
        } else {
            throw new NoSuchSessionException("Session " + targetName + " not found!");
        }
    }
914065
private static ApplicationSession openApplication(ApplicationDefinition appDef, RESTClient restClient) {
        String storageService = appDef.getStorageService();
        if (storageService == null ||
                storageService.length() <= "Service".length() ||
                !storageService.endsWith("Service")) {
            throw new RuntimeException("Unknown storage-service for application '" + appDef.getAppName() + "': " + storageService);
        }
        
        // Using the application's StorageService, attempt to create an instance of the
        // ApplicationSession subclass XxxSession where Xxx is the storage prefix.
        try {
            String prefix = storageService.substring(0, storageService.length() - "Service".length());
            String className = Client.class.getPackage().getName() + "." + prefix + "Session";
            @SuppressWarnings("unchecked")
            Class<ApplicationSession> appClass = (Class<ApplicationSession>) Class.forName(className);
            Constructor<ApplicationSession> constructor = appClass.getConstructor(ApplicationDefinition.class, RESTClient.class);
            ApplicationSession appSession = constructor.newInstance(appDef, restClient);
            return appSession;
        } catch (Exception e) {
            restClient.close();
            throw new RuntimeException("Unable to load session class", e);
        }
    }
532021
@Override
  public IRoSessionData getAppSessionData(Class<? extends AppSession> clazz, String sessionId) {
    if (clazz.equals(ClientRoSession.class)) {
      ClientRoSessionDataLocalImpl data = new ClientRoSessionDataLocalImpl();
      data.setSessionId(sessionId);
      return data;
    }
    else if (clazz.equals(ServerRoSession.class)) {
      ServerRoSessionDataLocalImpl data = new ServerRoSessionDataLocalImpl();
      data.setSessionId(sessionId);
      return data;
    }
    throw new IllegalArgumentException(clazz.toString());
  }
1278916
public int getAppContextSessionCount(PageContext pc) {
	ApplicationContext appContext = pc.getApplicationContext();
	if (pc.getSessionType() == Config.SESSION_TYPE_JEE) return 0;

	Map<String, Scope> context = getSubMap(cfSessionContexts, appContext.getName());
	return getCount(context);
    }
505519
public ISLhSessionData getAppSessionData(Class<? extends AppSession> clazz, String sessionId) {
    if (clazz.equals(ClientSLhSession.class)) {
      ClientSLhSessionDataReplicatedImpl data = new ClientSLhSessionDataReplicatedImpl(sessionId, this.mobicentsCluster,
          this.replicatedSessionDataSource.getContainer());
      return data;
    } else if (clazz.equals(ServerSLhSession.class)) {
      ServerSLhSessionDataReplicatedImpl data = new ServerSLhSessionDataReplicatedImpl(sessionId, this.mobicentsCluster,
          this.replicatedSessionDataSource.getContainer());
      return data;
    }
    throw new IllegalArgumentException();
  }
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;
        }

    }
1068759
public ISession getSession(String id, int version, boolean isSessionAccess) {
        //create local variable - JIT performance improvement
        final boolean isTraceOn = com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled();
        if (isTraceOn && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
            LoggingUtil.SESSION_LOGGER_WAS.entering(methodClassName, methodNames[GET_SESSION], "id = " + id);
            LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[GET_SESSION], "Store = " + this);
        }
        if (inProcessOfStopping) {
            throwException("SessionContext.accessWhenStop");
        }
        BackedSession session = ((BackedHashMap) _sessions).getSession(id, version, isSessionAccess);//why not call this -> ((BackedHashMap)_sessions).getSession(id, version);
        if (isTraceOn && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINER)) {
            LoggingUtil.SESSION_LOGGER_WAS.exiting(methodClassName, methodNames[GET_SESSION], "session = " + session);
        }
        return session;
    }
652325
@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 == ServerRfSession.class) {
        IServerRfSessionData sessionData = (IServerRfSessionData) this.sessionDataFactory.getAppSessionData(ServerRfSession.class, sessionId);
        // FIXME: determine how to get boolean flag!
        ServerRfSessionImpl session = new ServerRfSessionImpl(sessionData, sessionFactory, getServerSessionListener(), getServerContextListener(),
            getStateListener(), messageTimeout, true);

        session.getSessions().get(0).setRequestListener(session);
        appSession = session;
      }
      else if (aClass == ClientRfSession.class) {
        IClientRfSessionData sessionData = (IClientRfSessionData) this.sessionDataFactory.getAppSessionData(ClientRfSession.class, sessionId);
        ClientRfSessionImpl session = new ClientRfSessionImpl(sessionData, sessionFactory, getClientSessionListener(), getClientContextListener(),
            getStateListener(), this.getApplicationId());

        session.getSessions().get(0).setRequestListener(session);
        appSession = session;
      }
      else {
        throw new IllegalArgumentException("Wrong session class: " + aClass + ". Supported[" + ClientRfSession.class + "," + ServerRfSession.class + "]");
      }
    }
    catch (Exception e) {
      logger.error("Failure to obtain new Rf Session.", e);
    }

    return appSession;
  }
613323
@SuppressWarnings(value="unchecked")
	public Iterator<?> getSessions() {
		if(!isValid()) {
			throw new IllegalStateException("SipApplicationSession already invalidated !");
		}
		Set<MobicentsSipSession> sipSessions = getSipSessions(false);
		Set<HttpSession> httpSessions = getHttpSessions();
		Set protocolSessions = new HashSet();
		protocolSessions.addAll(httpSessions);
		protocolSessions.addAll(sipSessions);
		return protocolSessions.iterator();
	}
1029957
@Override
  public AppSession getNewSession(String sessionId, Class<? extends AppSession> aClass, ApplicationId applicationId, Object[] args) {
    AppSession appSession = null;

    if (aClass == ClientCxDxSession.class) {
      if (sessionId == null) {
        if (args != null && args.length > 0 && args[0] instanceof Request) {
          Request request = (Request) args[0];
          sessionId = request.getSessionId();
        }
        else {
          sessionId = this.sessionFactory.getSessionId();
        }
      }

      IClientCxDxSessionData sessionData = (IClientCxDxSessionData) this.sessionDataFactory.getAppSessionData(ClientCxDxSession.class, sessionId);
      sessionData.setApplicationId(applicationId);
      CxDxClientSessionImpl clientSession = new CxDxClientSessionImpl(sessionData, this.getMessageFactory(), this.sessionFactory, this
          .getClientSessionListener());

      iss.addSession(clientSession);
      clientSession.getSessions().get(0).setRequestListener(clientSession);
      appSession = clientSession;
    }
    else if (aClass == ServerCxDxSession.class) {
      if (sessionId == null) {
        if (args != null && args.length > 0 && args[0] instanceof Request) {
          Request request = (Request) args[0];
          sessionId = request.getSessionId();
        }
        else {
          sessionId = this.sessionFactory.getSessionId();
        }
      }
      IServerCxDxSessionData sessionData = (IServerCxDxSessionData) this.sessionDataFactory.getAppSessionData(ServerCxDxSession.class, sessionId);
      sessionData.setApplicationId(applicationId);
      CxDxServerSessionImpl serverSession = new CxDxServerSessionImpl(sessionData, getMessageFactory(), sessionFactory, this.getServerSessionListener());

      iss.addSession(serverSession);
      serverSession.getSessions().get(0).setRequestListener(serverSession);
      appSession = serverSession;
    }
    else {
      throw new IllegalArgumentException("Wrong session class: " + aClass + ". Supported[" + ServerCxDxSession.class + "," + ClientCxDxSession.class + "]");
    }

    return appSession;
  }
219671
private SessionData loadSession() {

        synchronized (sharedLock) {
            SharedPreferences sharedPreferences = getSharedPreferences();
            String id = sharedPreferences.getString(KEY_PROFILE_ID, null);
            if (!TextUtils.isEmpty(id)) {
                sharedLock.notifyAll();
                return new SessionData()
                        .setProfileId(id)
                        .setSessionId(sharedPreferences.getString(KEY_SESSION_ID, null))
                        .setAccessToken(sharedPreferences.getString(KEY_ACCESS_TOKEN, null))
                        .setExpiresOn(sharedPreferences.getLong(KEY_EXPIRES_ON, 0));
            }
            sharedLock.notifyAll();
        }

        return null;
    }
428387
@Override
  public AppsResponse getApps(WebResource resource, ResourcePath<Apps> appsResponsePath) {
    return resource.path(appsResponsePath.getPath()).get(AppsResponse.class);
  }
1274070
@Override
    public void onApplicationEvent(HttpSessionDestroyedEvent event) {
        final HttpSession session = ((HttpSessionDestroyedEvent) event).getSession();
        @SuppressWarnings("unchecked")
        final Map<String, PortletSession> portletSessions =
                (Map<String, PortletSession>) session.getAttribute(PORTLET_SESSIONS_MAP);
        if (portletSessions == null) {
            return;
        }

        /*
         * Since (at least) Tomcat 7.0.47, this method has the potential to
         * generate a StackOverflowError because PortletSession.invalidate()
         * will trigger another HttpSessionDestroyedEvent, which means this
         * method will be called again.  I don't know if this behavior is a bug
         * in Tomcat or Spring, if this behavior is entirely proper, or if the
         * reality somewhere in between.
         *
         * For the present, let's put a token in the HttpSession (which is
         * available from the event object) as soon as we start invalidating it.
         * We'll then ignore sessions that already have this token.
         */
        if (session.getAttribute(ALREADY_INVALIDATING_SESSION_ATTRIBUTE) != null) {
            // We're already invalidating;  don't do it again
            return;
        }
        session.setAttribute(ALREADY_INVALIDATING_SESSION_ATTRIBUTE, Boolean.TRUE);

        for (final Map.Entry<String, PortletSession> portletSessionEntry :
                portletSessions.entrySet()) {
            final String contextPath = portletSessionEntry.getKey();
            final PortletSession portletSession = portletSessionEntry.getValue();
            try {
                portletSession.invalidate();
            } catch (IllegalStateException e) {
                this.logger.info(
                        "PortletSession with id '"
                                + portletSession.getId()
                                + "' for context '"
                                + contextPath
                                + "' has already been invalidated.");
            } catch (Exception e) {
                this.logger.warn(
                        "Failed to invalidate PortletSession with id '"
                                + portletSession.getId()
                                + "' for context '"
                                + contextPath
                                + "'",
                        e);
            }
        }
    }