/* (non-Javadoc)
@see org.jdiameter.common.api.app.IAppSessionDataFactory#getAppSessionData(java.lang.Class, java.lang.String)
977986
@Override
  public ICCASessionData getAppSessionData(Class<? extends AppSession> clazz, String sessionId) {
    if (clazz.equals(ClientCCASession.class)) {
      ClientCCASessionDataLocalImpl data = new ClientCCASessionDataLocalImpl();
      data.setSessionId(sessionId);
      return data;
    }
    else if (clazz.equals(ServerCCASession.class)) {
      ServerCCASessionDataLocalImpl data = new ServerCCASessionDataLocalImpl();
      data.setSessionId(sessionId);
      return data;
    }
    throw new IllegalArgumentException(clazz.toString());
  }
52658
@Override
    public Session getSession() {
        return state.get() > GlobalState.INITIALISING ? new Session(dataMgr.getSessionDAO().session()) : new Session();
    }
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;
    }
779752
@Override
    public HttpSession getSession() {
        try {
            collaborator.preInvoke(componentMetaData);
            return request.getSession();
        } finally {
            collaborator.postInvoke();
        }
    }
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);
		}
    }
873474
@Override
  public BaseSession getSession(String sessionId) {
    if (this.localDataSource.exists(sessionId)) {
      return this.localDataSource.getSession(sessionId);
    }
    else if (!this.localMode && this.existReplicated(sessionId)) {
      this.makeLocal(sessionId);
      return this.localDataSource.getSession(sessionId);
    }

    return null;
  }
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;
    }
917990
protected Object getSessionValue(String pName, boolean securityInfo) {
        if (pName.equals(SECURITY_PROP_NAME) && (securityInfo == false)) {
            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_VALUE], "attempt to retrieve security info failed");
            }
            return null;
        }
        return super.getAttribute(pName);
    }
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());
  }
329578
protected Object getAllValues(BackedSession sess) {
        if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
            LoggingUtil.SESSION_LOGGER_WAS.entering(methodClassName, methodNames[GET_ALL_VALUES]);
        }

        Connection conn = getConnection(false);
        String id = sess.getId();

        if (conn == null) {
            if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
                LoggingUtil.SESSION_LOGGER_WAS.exiting(methodClassName, methodNames[GET_ALL_VALUES], null);
            }
            return null;
        }

        long startTime = System.currentTimeMillis();
        long readSize = 0;

        PreparedStatement s = null;
        ResultSet rs = null;
        Hashtable h = new Hashtable();
        try {
            s = conn.prepareStatement(findProps);
            s.setString(1, id);
            s.setString(2, id);
            s.setString(3, getAppName());
            rs = s.executeQuery();

            if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
                LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[GET_ALL_VALUES], "querying database for properties");
            }

            while (rs.next()) {

                // start PM36949: If an attribute is already in appDataRemovals or appDataChanges, then the attribute was already retrieved from the db.  Skip retrieval from the db here.
                if (sess.appDataRemovals != null && sess.appDataRemovals.containsKey(rs.getString(DatabaseHashMap.propCol))) { //

                    if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
                        LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[GET_ALL_VALUES], "Found property: "
                                                                                                                      + rs.getString(DatabaseHashMap.propCol)
                                                                                                                      + " in appDataRemovals, skipping db query for this prop");
                    }
                    continue;

                } else if (sess.appDataChanges != null && sess.appDataChanges.containsKey(rs.getString(DatabaseHashMap.propCol))) {

                    if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
                        LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[GET_ALL_VALUES], "Found property: "
                                                                                                                      + rs.getString(DatabaseHashMap.propCol)
                                                                                                                      + " in appDataChanges, skipping db query for this prop");
                    }
                    continue;
                } // end PM36949

                byte[] b = rs.getBytes(smallCol);
                if (b == null) {
                    b = rs.getBytes(medCol);
                }
                if (b == null) {
                    b = rs.getBytes(lgCol);
                }

                ByteArrayInputStream bais = new ByteArrayInputStream(b);
                BufferedInputStream bis = new BufferedInputStream(bais);
                Object obj = null;
                try {
                    obj = ((DatabaseStore) getIStore()).getLoader().loadObject(bis);
                    readSize += b.length;
                } catch (ClassNotFoundException ce) {
                    com.ibm.ws.ffdc.FFDCFilter.processException(ce, "com.ibm.ws.session.store.db.DatabaseHashMapMR.getAllValues", "864", sess);
                    LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[GET_ALL_VALUES], "DatabaseHashMapMR.getSwappableListenersErr");
                    LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[GET_ALL_VALUES], "CommonMessage.sessionid", id);
                    LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[GET_ALL_VALUES], "CommonMessage.exception", ce);
                }

                bis.close();
                bais.close();

                if (obj != null) {
                    if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
                        LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[GET_ALL_VALUES],
                                                            "put prop in mSwappableData: " + rs.getString(DatabaseHashMap.propCol));
                    }
                    h.put(rs.getString(propCol), obj);
                }
            }
            SessionStatistics pmiStats = _iStore.getSessionStatistics();
            if (pmiStats != null) {
                pmiStats.readTimes(readSize, System.currentTimeMillis() - startTime);
            }
        } catch (SQLException se) {
            com.ibm.ws.ffdc.FFDCFilter.processException(se, "com.ibm.ws.session.store.db.DatabaseHashMapMR.getAllValues", "885", sess);
            LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[GET_ALL_VALUES], "DatabaseHashMapMR.checkListErr");
            LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[GET_ALL_VALUES], "CommonMessage.object", sess.toString());
            LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[GET_ALL_VALUES], "CommonMessage.exception", se);
        } catch (Exception e) {
            com.ibm.ws.ffdc.FFDCFilter.processException(e, "com.ibm.ws.session.store.db.DatabaseHashMapMR.getAllValues", "892", sess);
            LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[GET_ALL_VALUES], "DatabaseHashMapMR.checkListErr");
            LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[GET_ALL_VALUES], "CommonMessage.object", sess.toString());
            LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[GET_ALL_VALUES], "CommonMessage.exception", e);
        } finally {
            if (rs != null)
                closeResultSet(rs);
            if (s != null)
                closeStatement(s);
            closeConnection(conn);
        }
        if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
            LoggingUtil.SESSION_LOGGER_WAS.exiting(methodClassName, methodNames[GET_ALL_VALUES], h);
        }
        return h;
    }
1159862
public ChatRoomListResult getAppChatRoomInfo(int start, int count)
            throws APIConnectionException, APIRequestException {
        return _chatRoomClient.getAppChatRoomInfo(start, count);
    }
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;
	}
967539
@Override
  public AppSession getNewSession(String sessionId, Class<? extends AppSession> aClass, ApplicationId applicationId, Object[] args) {
    try {
      // FIXME: add proper handling for SessionId
      if (aClass == ClientShSession.class) {
        ShClientSessionImpl clientSession = null;

        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();
          }
        }

        IShClientSessionData sessionData = (IShClientSessionData) this.sessionDataFactory.getAppSessionData(ClientShSession.class, sessionId);
        sessionData.setApplicationId(applicationId);
        clientSession = new ShClientSessionImpl(sessionData, this.getMessageFactory(), sessionFactory, this.getClientShSessionListener());
        sessionDataSource.addSession(clientSession);
        clientSession.getSessions().get(0).setRequestListener(clientSession);
        return clientSession;
      }
      else if (aClass == ServerShSession.class) {
        ShServerSessionImpl serverSession = null;

        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();
          }
        }
        IShServerSessionData sessionData = (IShServerSessionData) this.sessionDataFactory.getAppSessionData(ServerShSession.class, sessionId);
        sessionData.setApplicationId(applicationId);
        serverSession = new ShServerSessionImpl(sessionData, this.getMessageFactory(), sessionFactory, getServerShSessionListener());
        sessionDataSource.addSession(serverSession);
        serverSession.getSessions().get(0).setRequestListener(serverSession);
        return serverSession;
      }
      else {
        throw new IllegalArgumentException("Wrong session class: [" + aClass + "]. Supported[" + ClientShSession.class + "]");
      }
    }
    catch (IllegalArgumentException iae) {
      throw iae;
    }
    catch (Exception e) {
      logger.error("Failure to obtain new Sh Session.", e);
    }

    return null;
  }
1272945
@Override
  public IRfSessionData getAppSessionData(Class<? extends AppSession> clazz, String sessionId) {
    if (clazz.equals(ClientRfSession.class)) {
      ClientRfSessionDataReplicatedImpl data =
          new ClientRfSessionDataReplicatedImpl(sessionId, this.mobicentsCluster, this.replicatedSessionDataSource.getContainer());
      return data;
    }
    else if (clazz.equals(ServerRfSession.class)) {
      ServerRfSessionDataReplicatedImpl data = new ServerRfSessionDataReplicatedImpl(sessionId, this.mobicentsCluster);
      return data;
    }
    throw new IllegalArgumentException();
  }
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();
	}
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();
  }
641794
public SipApplicationSession getApplicationSession() {
		MobicentsSipApplicationSession sipApplicationSession = getSipApplicationSession();
		if(sipApplicationSession == null) {
			return null;
		} else {
			return sipApplicationSession.getFacade();
		}
	}