/*
(non-Javadoc)

@see org.jdiameter.common.api.app.IAppSessionDataFactory#getAppSessionData(java.lang.Class, java.lang.String)
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();
  }
1321421
private ClientCCASession getRoSession() throws InternalException {
    return ((ISessionFactory) super.sessionFactory).getNewAppSession(null, roAppId, ClientCCASession.class, null);
  }
376361
@ReadOperation
    public Map<String, Object> getSsoSessions(final String type) {
        val sessionsMap = new HashMap<String, Object>(1);
        val option = SsoSessionReportOptions.valueOf(type);
        val activeSsoSessions = getActiveSsoSessions(option);
        sessionsMap.put("activeSsoSessions", activeSsoSessions);
        val totalTicketGrantingTickets = new AtomicLong();
        val totalProxyGrantingTickets = new AtomicLong();
        val totalUsageCount = new AtomicLong();
        val uniquePrincipals = new HashSet<Object>();
        for (val activeSsoSession : activeSsoSessions) {
            if (activeSsoSession.containsKey(SsoSessionAttributeKeys.IS_PROXIED.toString())) {
                val isProxied = Boolean.valueOf(activeSsoSession.get(SsoSessionAttributeKeys.IS_PROXIED.toString()).toString());
                if (isProxied) {
                    totalProxyGrantingTickets.incrementAndGet();
                } else {
                    totalTicketGrantingTickets.incrementAndGet();
                    val principal = activeSsoSession.get(SsoSessionAttributeKeys.AUTHENTICATED_PRINCIPAL.toString()).toString();
                    uniquePrincipals.add(principal);
                }
            } else {
                totalTicketGrantingTickets.incrementAndGet();
                val principal = activeSsoSession.get(SsoSessionAttributeKeys.AUTHENTICATED_PRINCIPAL.toString()).toString();
                uniquePrincipals.add(principal);
            }
            val uses = Long.parseLong(activeSsoSession.get(SsoSessionAttributeKeys.NUMBER_OF_USES.toString()).toString());
            totalUsageCount.getAndAdd(uses);
        }
        sessionsMap.put("totalProxyGrantingTickets", totalProxyGrantingTickets);
        sessionsMap.put("totalTicketGrantingTickets", totalTicketGrantingTickets);
        sessionsMap.put("totalTickets", totalTicketGrantingTickets.longValue() + totalProxyGrantingTickets.longValue());
        sessionsMap.put("totalPrincipals", uniquePrincipals.size());
        sessionsMap.put("totalUsageCount", totalUsageCount);
        return sessionsMap;
    }
747539
public static final void getActivitySessions(ActivitySessionAttribute[] asAttrs,
                                                 int type,
                                                 String[] methodNames,
                                                 Class<?>[][] methodParamTypes,
                                                 List<ActivitySessionMethod> asAttrList,
                                                 String ejbName,
                                                 boolean usesBeanManagedAS)
    {
        final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
        if (isTraceOn && tc.isEntryEnabled())
            Tr.entry(tc, "getActivitySessions", (Object[])asAttrs);

        if (!usesBeanManagedAS) { // d127328

            if (isTraceOn && tc.isDebugEnabled())
                Tr.debug(tc, "Bean is CMAS");

            if (asAttrList != null) {
                if (isTraceOn && tc.isDebugEnabled())
                    Tr.debug(tc, "asAttrList non-null");

                // array to keep track of what kind of style last set the method-specific behavior
                int[] highestStyleOnMethod = new int[methodNames.length];

                // Elements of highestStyleOnMethod[] are initialized to zero by Java rules.

                // i : asAttrList loop
                // j : MethodElements loop
                // k : Method loop

                for (int i = 0; i < asAttrList.size(); ++i) {
                    ActivitySessionMethod asMethod = asAttrList.get(i);
                    ActivitySessionAttribute asAttr = asMethod.getActivitySessionAttribute();
                    @SuppressWarnings("unchecked")
                    List<com.ibm.ws.javaee.dd.ejb.Method> methodElements = asMethod.getMethodElements();
                    for (int j = 0; j < methodElements.size(); ++j) {
                        com.ibm.ws.javaee.dd.ejb.Method me = methodElements.get(j);
                        if (isTraceOn && tc.isDebugEnabled()) {
                            trace(me, me.getInterfaceTypeValue() == com.ibm.ws.javaee.dd.ejb.Method.INTERFACE_TYPE_UNSPECIFIED ?
                                            "Interface type unspecified" :
                                            "Interface type: " + me.getInterfaceTypeValue());
                        }
                        // Is this method element for the bean we are processing?
                        if ((me.getEnterpriseBeanName()).equals(ejbName)) {
                            String meName = me.getMethodName().trim();
                            int meType = me.getInterfaceTypeValue();

                            if (meName.equals("*")) {
                                if (meType == com.ibm.ws.javaee.dd.ejb.Method.INTERFACE_TYPE_UNSPECIFIED) {
                                    // style type 1 -- wildcard on all bean methods
                                    if (isTraceOn && tc.isDebugEnabled())
                                        Tr.debug(tc, "Style type 1 - all bean methods:", asAttr);
                                    for (int k = 0; k < methodNames.length; ++k) {
                                        if (highestStyleOnMethod[k] <= 1) {
                                            asAttrs[k] = asAttr;
                                            highestStyleOnMethod[k] = 1;
                                        }
                                    }

                                } else if (meType == type) { //LIDB2257.19
                                    // style type 2 -- wildcard on home or remote interface methods
                                    if (isTraceOn && tc.isDebugEnabled())
                                        Tr.debug(tc, "Style type 2 - home/remote methods only:", asAttr);
                                    for (int k = 0; k < methodNames.length; ++k) {
                                        if (highestStyleOnMethod[k] <= 2) {
                                            asAttrs[k] = asAttr;
                                            highestStyleOnMethod[k] = 2;
                                        }
                                    }
                                }
                            } else if (meType == com.ibm.ws.javaee.dd.ejb.Method.INTERFACE_TYPE_UNSPECIFIED || meType == type) { //LIDB2257.19
                                // It is not a wildcard, and either has an unspecified
                                // type, or is of the right type (Remote/Home/Local),
                                // so check for a method name match.             d123321
                                for (int k = 0; k < methodNames.length; ++k) {
                                    if (meName.equals(methodNames[k])) {
                                        List<String> meParms = me.getMethodParamList();
                                        if (meParms == null) {
                                            // style type 3 - matching method name, no signature
                                            //                specified
                                            if (isTraceOn && tc.isDebugEnabled())
                                                Tr.debug(tc, "Style type 3 - method name only:", asAttr);
                                            if (highestStyleOnMethod[k] <= 3) {
                                                asAttrs[k] = asAttr;
                                                highestStyleOnMethod[k] = 3;
                                            }
                                        } else {
                                            if (DDUtil.methodParamsMatch(meParms, methodParamTypes[k])) {
                                                // style type 4 - matching method name and signature
                                                if (isTraceOn && tc.isDebugEnabled())
                                                    Tr.debug(tc, "Style type 4 - method name and signature:", asAttr);
                                                asAttrs[k] = asAttr;
                                                highestStyleOnMethod[k] = 4;
                                            } // method parms match specified parms
                                        } // method parms were specified
                                    } // methodExtension name matches method name
                                } // method loop (k)
                            } // if/then/else for meName='*'
                        } // enterpriseBean name matches parm in methodExtension
                    } // methodElements loop (j)
                } // asAttrList loop (i)
            } // asAttrList != null

        } else if (usesBeanManagedAS) {
            if (isTraceOn && tc.isDebugEnabled())
                Tr.debug(tc, "Bean is BMAS -- all methods will be set to AS_BEAN_MANAGED");
            for (int i = 0; i < asAttrs.length; i++) {
                asAttrs[i] = ActivitySessionAttribute.AS_BEAN_MANAGED;
            }
        }

        if (isTraceOn && tc.isEntryEnabled())
            Tr.exit(tc, "getActivitySessions");

        return;
    }
28156
public SipApplicationSession getApplicationSessionById(String applicationSessionId, boolean isContainerManaged) {
		if(logger.isDebugEnabled()) {
			logger.debug("getApplicationSessionById - applicationSessionId=" + applicationSessionId);
		}
		if(applicationSessionId == null) {
			throw new NullPointerException("the given id is null !");
		}
		SipApplicationSessionKey applicationSessionKey;
		try {
			applicationSessionKey = SessionManagerUtil.parseSipApplicationSessionKey(applicationSessionId);
		} catch (ParseException e) {
			logger.error("the given application session id : " + applicationSessionId + 
					" couldn't be parsed correctly ",e);
			return null;
		}
		if(applicationSessionKey.getApplicationName().equals(sipContext.getApplicationName())) {
			MobicentsSipApplicationSession sipApplicationSession = sipContext.getSipManager().getSipApplicationSession(applicationSessionKey, false);
			if(sipApplicationSession == null) {
				return null;
			} else {
				// 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, isContainerManaged);
				return sipApplicationSession.getFacade();
			}
		} else {
			logger.warn("the given application session id : " + applicationSessionId + 
					" tried to be retrieved from incorret application " + sipContext.getApplicationName());
			return null;
		}
	}
449048
@Override
  public IGxSessionData getAppSessionData(Class<? extends AppSession> clazz, String sessionId) {
    if (clazz.equals(ClientGxSession.class)) {
      ClientGxSessionDataLocalImpl data = new ClientGxSessionDataLocalImpl();
      data.setSessionId(sessionId);
      return data;
    }
    else if (clazz.equals(ServerGxSession.class)) {
      ServerGxSessionDataLocalImpl data = new ServerGxSessionDataLocalImpl();
      data.setSessionId(sessionId);
      return data;
    }
    throw new IllegalArgumentException(clazz.toString());
  }
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();
  }
588945
private byte[] serializeAppData(BackedSession d2) {
        if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
            LoggingUtil.SESSION_LOGGER_WAS.entering(methodClassName, methodNames[SERIALIZE_APP_DATA]);
        }
        // return either the byte array input stream for the app
        // data or a vector of byte array input streams if their is a
        // row for each piece of app data
        ByteArrayOutputStream baos = null;
        ObjectOutputStream oos = null;
        byte[] objbuf = null;

        try {
            Map<Object, Object> ht = null;
            if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
                LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[SERIALIZE_APP_DATA], "get swappableData and convert to byte array");
            }
            synchronized (d2) {
                ht = d2.getSwappableData();
            }

            // serialize session (app data only) into byte array buffer
            baos = new ByteArrayOutputStream();
            oos = createObjectOutputStream(baos);
            oos.writeObject(ht);
            oos.flush();
            objbuf = baos.toByteArray();
            if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
                LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[SERIALIZE_APP_DATA], "success - size of byte array is " + objbuf.length);
            }

            oos.close();
            baos.close();
        } catch (ConcurrentModificationException cme) {
            LoggingUtil.SESSION_LOGGER_WAS.logp(Level.INFO, methodClassName, methodNames[SERIALIZE_APP_DATA], "DatabaseHashMap.deferWrite", /* + d2.deferWriteUntilNextTick */
                                                d2.getId());
        } catch (Exception e) {
            com.ibm.ws.ffdc.FFDCFilter.processException(e, "com.ibm.ws.session.store.db.DatabaseHashMap.commonSetup", "2052", d2);
            LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[SERIALIZE_APP_DATA], "DatabaseHashMap.commonSetupError");
            LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[SERIALIZE_APP_DATA], "CommonMessage.exception", e);
        }
        if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINER)) {
            LoggingUtil.SESSION_LOGGER_WAS.exiting(methodClassName, methodNames[SERIALIZE_APP_DATA]);
        }
        return objbuf;
    }
19303
private Session getCFSessionScope(PageContext pc, RefBoolean isNew) throws PageException {

	ApplicationContext appContext = pc.getApplicationContext();
	// get Context
	Map<String, Scope> context = getSubMap(cfSessionContexts, appContext.getName());

	// get Session
	boolean isMemory = false;
	String storage = appContext.getSessionstorage();
	if (StringUtil.isEmpty(storage, true)) {
	    storage = ConfigImpl.DEFAULT_STORAGE_SESSION;
	    isMemory = true;
	}
	else if ("ram".equalsIgnoreCase(storage)) {
	    storage = "memory";
	    isMemory = true;
	}
	else if ("registry".equalsIgnoreCase(storage)) {
	    storage = "file";
	}
	else {
	    storage = storage.toLowerCase();
	    if ("memory".equals(storage)) isMemory = true;
	}

	Session existing = (Session) context.get(pc.getCFID());
	if (existing != null && (existing.isExpired() || !(existing instanceof StorageScope))) existing = null; // second should not happen

	Session session = appContext.getSessionCluster() ? null : existing;

	if (session == null || !(session instanceof StorageScope) || !((StorageScope) session).getStorage().equalsIgnoreCase(storage)) {
	    // not necessary to check session in the same way, because it is overwritten anyway
	    if (isMemory) {
		if (existing != null) session = existing;
		else session = SessionMemory.getInstance(pc, isNew, getLog());
	    }
	    else if ("file".equals(storage)) {
		session = SessionFile.getInstance(appContext.getName(), pc, getLog());
	    }
	    else if ("cookie".equals(storage)) session = SessionCookie.getInstance(appContext.getName(), pc, getLog());
	    else {
		DataSource ds = pc.getDataSource(storage, null);
		if (ds != null && ds.isStorage()) {
		    if (INVIDUAL_STORAGE_KEYS) {
			try {
			    session = (Session) IKStorageScopeSupport.getInstance(Scope.SCOPE_SESSION, new IKHandlerDatasource(), appContext.getName(), storage, pc, existing,
				    getLog());
			}
			catch (PageException pe) {
			    session = SessionDatasource.getInstance(storage, pc, getLog(), null);
			}
		    }
		    else session = SessionDatasource.getInstance(storage, pc, getLog(), null);
		}
		else {
		    if (INVIDUAL_STORAGE_KEYS) {
			try {
			    session = (Session) IKStorageScopeSupport.getInstance(Scope.SCOPE_SESSION, new IKHandlerCache(), appContext.getName(), storage, pc, existing, getLog());
			}
			catch (PageException pe) {
			    session = SessionCache.getInstance(storage, appContext.getName(), pc, existing, getLog(), null);
			}
		    }
		    else session = SessionCache.getInstance(storage, appContext.getName(), pc, existing, getLog(), null);
		}

		if (session == null) {
		    // datasource not enabled for storage
		    if (ds != null) {
			if (!ds.isStorage()) throw new ApplicationException("datasource [" + storage + "] is not enabled to be used as session storage, "
				+ "you have to enable it in the Lucee administrator or define key \"storage=true\" for datasources defined in the application event handler.");
			throw new ApplicationException("datasource [" + storage
				+ "] could not be reached for session storage. Please make sure the datasource settings are correct, and the datasource is available.");
		    }
		    CacheConnection cc = CacheUtil.getCacheConnection(pc, storage, null);
		    if (cc != null) throw new ApplicationException(
			    "cache [" + storage + "] is not enabled to be used  as a session/client storage, you have to enable it in the Lucee administrator.");

		    throw new ApplicationException("there is no cache or datasource with name [" + storage + "] defined.");
		}
	    }
	    if (session instanceof StorageScope) ((StorageScope) session).setStorage(storage);
	    context.put(pc.getCFID(), session);
	    isNew.setValue(true);
	}
	else {
	    getLog().log(Log.LEVEL_INFO, "scope-context", "use existing session scope for " + appContext.getName() + "/" + pc.getCFID() + " from storage " + storage);
	}
	session.touchBeforeRequest(pc);
	return session;
    }
1361061
public ISLgSessionData getAppSessionData(Class<? extends AppSession> clazz, String sessionId) {
    if (clazz.equals(ClientSLgSession.class)) {
      ClientSLgSessionDataReplicatedImpl data = new ClientSLgSessionDataReplicatedImpl(sessionId, this.mobicentsCluster,
          this.replicatedSessionDataSource.getContainer());
      return data;
    } else if (clazz.equals(ServerSLgSession.class)) {
      ServerSLgSessionDataReplicatedImpl data = new ServerSLgSessionDataReplicatedImpl(sessionId, this.mobicentsCluster,
          this.replicatedSessionDataSource.getContainer());
      return data;
    }
    throw new IllegalArgumentException();
  }
851389
@Trivial // return value contains customer data
    @FFDCIgnore(Exception.class) //manually logged
    Object getAllValues(BackedSession sess) {
        @SuppressWarnings("static-access")
        final boolean hideValues = _smc.isHideSessionValues();
        final boolean trace = TraceComponent.isAnyTracingEnabled();

        if (trace && tc.isEntryEnabled())
            Tr.entry(this, tc, "getAllValues", sess);

        String id = sess.getId();

        long startTime = System.nanoTime();
        long readSize = 0;
        Hashtable<String, Object> h = new Hashtable<String, Object>();

        try {

            if (trace && tc.isDebugEnabled())
                tcInvoke(tcSessionMetaCache, "get", id);

            ArrayList<?> list = sessionMetaCache.get(id);

            if (trace && tc.isDebugEnabled())
                tcReturn(tcSessionMetaCache, "get", list);

            Set<String> propIds = list == null ? null : new SessionInfo(list).getSessionPropertyIds();

            if (propIds != null) {
                for (String propId : propIds) {
                    // If an attribute is already in appDataRemovals or appDataChanges, then the attribute was already retrieved from the cache.  Skip retrieval from the cache here.
                    if (sess.appDataRemovals != null && sess.appDataRemovals.containsKey(propId)) {
                        if (trace && tc.isDebugEnabled())
                            Tr.debug(this, tc, "Found property " + propId + " in appDataRemovals, skipping query for this prop");
                        continue;
                    } else if (sess.appDataChanges != null && sess.appDataChanges.containsKey(propId)) {
                        if (trace && tc.isDebugEnabled())
                            Tr.debug(this, tc, "Found property " + propId + " in appDataChanges, skipping query for this prop");
                        continue;
                    }

                    String attributeKey = createSessionAttributeKey(id, propId);

                    if (trace && tc.isDebugEnabled())
                        tcInvoke(tcSessionAttrCache, "get", attributeKey);

                    byte[] b = sessionAttributeCache.get(attributeKey);

                    if (b == null) {
                        if (trace && tc.isDebugEnabled())
                            tcReturn(tcSessionAttrCache, "get", "null");
                    } else {
                        Object value;
                        try {
                            value = deserialize(b);
                            readSize += b.length;

                            if (trace && tc.isDebugEnabled())
                                if (hideValues)
                                    tcReturn(tcSessionAttrCache, "get", "byte[" + b.length + "]");
                                else
                                    tcReturn(tcSessionAttrCache, "get", b, value);
                        } catch (Exception x) {
                            if (trace && tc.isDebugEnabled())
                                tcReturn(tcSessionAttrCache, "get", hideValues ? ("byte[" + b.length + "]") : b);

                            FFDCFilter.processException(x, getClass().getName(), "91", sess, new Object[] { hideValues ? "byte[" + b.length + "]" : TypeConversion.limitedBytesToString(b) });
                            throw x;
                        }                   
                        if (value != null) {
                            h.put(propId, value);
                        }
                    }
                }
            }

            SessionStatistics pmiStats = _iStore.getSessionStatistics();
            if (pmiStats != null) {
                pmiStats.readTimes(readSize, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime));
            }
        } catch (Exception ex) {
            FFDCFilter.processException(ex, "com.ibm.ws.session.store.cache.CacheHashMap.getAllValues", "448", this, new Object[] { sess });
            Tr.error(tc, "LOAD_VALUE_ERROR", ex);
            throw new RuntimeException(Tr.formatMessage(tc, "INTERNAL_SERVER_ERROR"));
        }

        if (trace && tc.isEntryEnabled())
            Tr.exit(this, tc, "getAllValues", hideValues ? h.keySet() : h);
        return h;
    }
707678
public SipApplicationSession getApplicationSession(boolean create) {
		if(logger.isDebugEnabled()) {
			logger.debug("getApplicationSession - create=" + create);
		}

		MobicentsSipApplicationSession sipApplicationSession = getSipApplicationSession(create);
		if(sipApplicationSession == null) {
			return null;
		} else {
			return sipApplicationSession.getFacade();
		}
	}
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;
    }
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;
	}
206208
private Session getJSessionScope(PageContext pc, RefBoolean isNew) throws PageException {
	HttpSession httpSession = pc.getSession();
	ApplicationContext appContext = pc.getApplicationContext();
	Object session = null;// this is from type object, because it is possible that httpSession return object from
	// prior restart

	int s = (int) appContext.getSessionTimeout().getSeconds();
	if (maxSessionTimeout < s) maxSessionTimeout = s;

	if (httpSession != null) {
	    httpSession.setMaxInactiveInterval(maxSessionTimeout + 60);
	    session = httpSession.getAttribute(appContext.getName());
	}
	else {
	    Map<String, Scope> context = getSubMap(cfSessionContexts, appContext.getName());
	    session = context.get(pc.getCFID());
	}

	JSession jSession = null;
	if (session instanceof JSession) {
	    jSession = (JSession) session;
	    try {
		if (jSession.isExpired()) {
		    jSession.touch();
		}
		info(getLog(), "use existing JSession for " + appContext.getName() + "/" + pc.getCFID());

	    }
	    catch (ClassCastException cce) {
		error(getLog(), cce);
		// if there is no HTTPSession
		if (httpSession == null) return getCFSessionScope(pc, isNew);

		jSession = new JSession();
		httpSession.setAttribute(appContext.getName(), jSession);
		isNew.setValue(true);
	    }
	}
	else {
	    // if there is no HTTPSession
	    if (httpSession == null) return getCFSessionScope(pc, isNew);

	    info(getLog(), "create new JSession for " + appContext.getName() + "/" + pc.getCFID());
	    jSession = new JSession();
	    httpSession.setAttribute(appContext.getName(), jSession);
	    isNew.setValue(true);
	    Map<String, Scope> context = getSubMap(cfSessionContexts, appContext.getName());
	    context.put(pc.getCFID(), jSession);
	}
	jSession.touchBeforeRequest(pc);
	return jSession;
    }
92530
protected synchronized IHttpSessionContext createSessionContext(
                                                                  String appName,
                                                                  boolean distributableWebApp, boolean allowDispatchRemoteInclude, 
                                                                  WebApp sc, ClassLoader appCl,
                                                                  SessionManagerConfig smc, String j2eeName,
                                                                  boolean sessionSharing, String applicationSessionAppName) throws Throwable {

        if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) {
            LoggingUtil.SESSION_LOGGER_CORE.entering(methodClassName, methodNames[CREATE_SESSION_CONTEXT]);
        }
        // ensure no other thread just finished creating
        IHttpSessionContext sessCtx = (IHttpSessionContext)scrSessionContexts.get(appName);
        if (sessCtx == null) {
            WebAppConfiguration webAppConfig=sc.getConfiguration();
            SessionApplicationParameters sap = new SessionApplicationParameters(appName, 
                                                                                webAppConfig.isModuleSessionTimeoutSet(),
                                                                                webAppConfig.getSessionTimeout(),
                                                                                distributableWebApp, 
                                                                                allowDispatchRemoteInclude, 
                                                                                sc, 
                                                                                appCl, 
                                                                                j2eeName, 
                                                                                webAppConfig.getSessionCookieConfig(), 
                                                                                webAppConfig.isModuleSessionTrackingModeSet(), 
                                                                                webAppConfig.getSessionTrackingMode());
            if(webAppConfig.getSessionCookieConfig()!=null) {
                webAppConfig.setHasProgrammaticCookieConfig(); // in tWAS, this happens in SessionApplicationParameters(...)
            }
            
            //if session sharing or Servlet21Compatibility (the var sessionSharing should be true) - don't create appSession
            //and calls to getIBMApplicationSession will return null
            if (!sessionSharing) {
                sap.setHasApplicationSession(true);
                sap.setApplicationSessionName(applicationSessionAppName);
            }
            sessCtx = createSessionContextObject(smc, sap);
            scrSessionContexts.put(appName, sessCtx);
        }
        if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) {
            LoggingUtil.SESSION_LOGGER_CORE.exiting(methodClassName, methodNames[CREATE_SESSION_CONTEXT]);
        }
        return sessCtx;
    }
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());
  }