Auto-attach StatsStorage if an unknown session ID is passed as URL path parameter in multi-session mode
@param statsStorageProvider function that returns a StatsStorage containing the given session ID
423063
public void autoAttachStatsStorageBySessionId(Function<String, StatsStorage> statsStorageProvider) {
        if (statsStorageProvider != null) {
            this.statsStorageLoader = new StatsStorageLoader(statsStorageProvider);
        }
    }
1256632
@Override
	public synchronized RecordSessionUrl insert(int type, String url) throws DatabaseException {
    	SqlPreparedStatementWrapper psInsert = null;
        try {
        	psInsert = DbSQL.getSingleton().getPreparedStatement("sessionurl.ps.insert");
			psInsert.getPs().setInt(1, type);
			psInsert.getPs().setString(2, url);
			psInsert.getPs().executeUpdate();
			
			long id;
			try (ResultSet rs = psInsert.getLastInsertedId()) {
				rs.next();
				id = rs.getLong(1);
			}
			return read(id);
		} catch (SQLException e) {
			throw new DatabaseException(e);
		} finally {
			DbSQL.getSingleton().releasePreparedStatement(psInsert);
		}
    }
143177
static URL getStorageConfigURL() throws ConfigurationException
    {
        String configUrl = System.getProperty("cassandra.config");
        if (configUrl == null)
            configUrl = DEFAULT_CONFIGURATION;

        URL url;
        try
        {
            url = new URL(configUrl);
            url.openStream().close(); // catches well-formed but bogus URLs
        }
        catch (Exception e)
        {
            ClassLoader loader = DatabaseDescriptor.class.getClassLoader();
            url = loader.getResource(configUrl);
            if (url == null)
            {
                String required = "file:" + File.separator + File.separator;
                if (!configUrl.startsWith(required))
                    throw new ConfigurationException("Expecting URI in variable: [cassandra.config].  Please prefix the file with " + required + File.separator +
                            " for local files or " + required + "<server>" + File.separator + " for remote files. Aborting. If you are executing this from an external tool, it needs to set Config.setClientMode(true) to avoid loading configuration.");
                throw new ConfigurationException("Cannot locate " + configUrl + ".  If this is a local file, please confirm you've provided " + required + File.separator + " as a URI prefix.");
            }
        }

        return url;
    }
396561
void setRequestedSessionId(String pathParams)
    {
        _requestedSessionId=null;
        
        // try cookies first
        if (_servletHandler.isUsingCookies())
        {
            Cookie[] cookies=_httpRequest.getCookies();
            if (cookies!=null && cookies.length>0)
            {
                for (int i=0;i<cookies.length;i++)
                {
                    if (SessionManager.__SessionCookie.equalsIgnoreCase(cookies[i].getName()))
                    {
                        if (_requestedSessionId!=null)
                        {
                            // Multiple jsessionid cookies. Probably due to
                            // multiple paths and/or domains. Pick the first
                            // known session or the last defined cookie.
                            SessionManager manager = _servletHandler.getSessionManager();
                            if (manager!=null && manager.getHttpSession(_requestedSessionId)!=null)
                                break;
                            log.debug("multiple session cookies");
                        }
                        
                        _requestedSessionId=cookies[i].getValue();
                        _sessionIdState = __SESSIONID_COOKIE;
                        if(log.isDebugEnabled())log.debug("Got Session "+_requestedSessionId+" from cookie");
                    }
                }
            }
        }
            
        // check if there is a url encoded session param.
        if (pathParams!=null && pathParams.startsWith(SessionManager.__SessionURL))
        {
            String id =
                pathParams.substring(SessionManager.__SessionURL.length()+1);
            if(log.isDebugEnabled())log.debug("Got Session "+id+" from URL");
            
            if (_requestedSessionId==null)
            {
                _requestedSessionId=id;
                _sessionIdState = __SESSIONID_URL;
            }
            else if (!id.equals(_requestedSessionId))
                log.debug("Mismatched session IDs");
        }
        
        if (_requestedSessionId == null)
            _sessionIdState = __SESSIONID_NONE;        
    }
41730
private void linkSession(long csid, long sessionID) {

        LongKeyIntValueHashMap scsMap;

        scsMap = (LongKeyIntValueHashMap) sessionUseMap.get(sessionID);

        if (scsMap == null) {
            scsMap = new LongKeyIntValueHashMap();

            sessionUseMap.put(sessionID, scsMap);
        }

        int count = scsMap.get(csid, 0);

        scsMap.put(csid, count + 1);

        if (count == 0) {
            useMap.put(csid, useMap.get(csid, 0) + 1);
        }
    }
430313
Node getUsersStorageNode(Session session) throws PathNotFoundException, RepositoryException
   {
      return (Node)session.getItem(service.getStoragePath() + "/" + JCROrganizationServiceImpl.STORAGE_JOS_USERS);
   }
945951
@Override
  public IGxSessionData getAppSessionData(Class<? extends AppSession> clazz, String sessionId) {
    if (clazz.equals(ClientGxSession.class)) {
      ClientGxSessionDataReplicatedImpl data =
          new ClientGxSessionDataReplicatedImpl(sessionId, this.mobicentsCluster, this.replicatedSessionDataSource.getContainer());
      return data;
    }
    else if (clazz.equals(ServerGxSession.class)) {
      ServerGxSessionDataReplicatedImpl data = new ServerGxSessionDataReplicatedImpl(sessionId, this.mobicentsCluster);
      return data;
    }
    throw new IllegalArgumentException();
  }
864521
def AddDatastore(self, urn):
    
    if urn not in self._datastores:
      self._datastores.add(urn)
      return True
    return False
438759
private void readParamsFromRegistryService(SessionProvider sessionProvider) throws PathNotFoundException,
            RepositoryException
   {
      String entryPath = RegistryService.EXO_SERVICES + "/" + SERVICE_NAME + "/" + "workspace";
      RegistryEntry registryEntry = registryService.getEntry(sessionProvider, entryPath);
      Document doc = registryEntry.getDocument();
      Element element = doc.getDocumentElement();
      repoWorkspaceName = getAttributeSmart(element, "value");

      entryPath = RegistryService.EXO_SERVICES + "/" + SERVICE_NAME + "/" + "rootNode";
      registryEntry = registryService.getEntry(sessionProvider, entryPath);
      doc = registryEntry.getDocument();
      element = doc.getDocumentElement();
      rootNodePath = getAttributeSmart(element, "value");

      LOG.info("Workspace from RegistryService: " + repoWorkspaceName);
      LOG.info("RootNode from RegistryService: " + rootNodePath);
   }
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());
  }
898777
public static void setDefaultStorageFileProvider ()
  {
    setStorageFileProvider (aMetadata -> {
      final LocalDateTime aNow = PDTFactory.getCurrentLocalDateTime ();
      final String sFilename = StringHelper.getConcatenatedOnDemand (PDTIOHelper.getLocalDateTimeForFilename (aNow),
                                                                     "-",
                                                                     aMetadata.getErrorID ()) +
                               ".xml";
      return WebFileIO.getDataIO ()
                      .getFile ("internal-errors/" +
                                aNow.getYear () +
                                "/" +
                                StringHelper.getLeadingZero (aNow.getMonthValue (), 2) +
                                "/" +
                                sFilename);
    });
  }
154741
function buildLoginUrl(connectionConfig)
{
  var queryParams =
  [
    { name: 'warehouse',    value: connectionConfig.getWarehouse() },
    { name: 'databaseName', value: connectionConfig.getDatabase() },
    { name: 'schemaName',   value: connectionConfig.getSchema() },
    { name: 'roleName',     value: connectionConfig.getRole() }
  ];

  var queryStringObject = {};
  for (var index = 0, length = queryParams.length; index < length; index++)
  {
    var queryParam = queryParams[index];
    if (Util.string.isNotNullOrEmpty(queryParam.value))
    {
      queryStringObject[queryParam.name] = queryParam.value;
    }
  }

  return Url.format(
  {
    pathname : '/session/v1/login-request',
    search   : QueryString.stringify(queryStringObject)
  });
}
819823
@Sensitive
    private String getStoredReq(HttpServletRequest req, ReferrerURLCookieHandler referrerURLHandler) {
        String storedReq = referrerURLHandler.getReferrerURLFromCookies(req, ReferrerURLCookieHandler.REFERRER_URL_COOKIENAME);
        if (storedReq != null) {
            if (storedReq.equals("/"))
                storedReq = "";
            else if (storedReq.startsWith("/"))
                storedReq = storedReq.substring(1);
        } else {
            storedReq = "";
        }
        return storedReq;
    }
477186
private void verifyOrAddStore(String clusterURL,
                                  String keySchema,
                                  String valueSchema) {
        String newStoreDefXml = VoldemortUtils.getStoreDefXml(
                storeName,
                props.getInt(BUILD_REPLICATION_FACTOR, 2),
                props.getInt(BUILD_REQUIRED_READS, 1),
                props.getInt(BUILD_REQUIRED_WRITES, 1),
                props.getNullableInt(BUILD_PREFERRED_READS),
                props.getNullableInt(BUILD_PREFERRED_WRITES),
                props.getString(PUSH_FORCE_SCHEMA_KEY, keySchema),
                props.getString(PUSH_FORCE_SCHEMA_VALUE, valueSchema),
                description,
                owners);

        log.info("Verifying store against cluster URL: " + clusterURL + "\n" + newStoreDefXml.toString());
        StoreDefinition newStoreDef = VoldemortUtils.getStoreDef(newStoreDefXml);

        try {
            adminClientPerCluster.get(clusterURL).storeMgmtOps.verifyOrAddStore(newStoreDef, "BnP config/data",
                enableStoreCreation, this.storeVerificationExecutorService);
        } catch (UnreachableStoreException e) {
            log.info("verifyOrAddStore() failed on some nodes for clusterURL: " + clusterURL + " (this is harmless).", e);
            // When we can't reach some node, we just skip it and won't create the store on it.
            // Next time BnP is run while the node is up, it will get the store created.
        } // Other exceptions need to bubble up!

        storeDef = newStoreDef;
    }
367119
private CloseableDataStore createDataStoreWithHostDiscovery(final URI location, String apiKey, MetricRegistry metricRegistry) {
        // Get the service factory for this cluster.
        String cluster = LocationUtil.getClusterForLocation(location);
        MultiThreadedServiceFactory<AuthDataStore> dataStoreFactory = createDataStoreServiceFactory(cluster, metricRegistry);

        // If the host discovery uses ZooKeeper -- that is, it doesn't used fixed hosts -- create a Curator for it.
        final Optional<CuratorFramework> curator = LocationUtil.getCuratorForLocation(location);
        HostDiscovery hostDiscovery = LocationUtil.getHostDiscoveryForLocation(location, curator, dataStoreFactory.getServiceName(), metricRegistry);

        final AuthDataStore authDataStore = ServicePoolBuilder.create(AuthDataStore.class)
                .withHostDiscovery(hostDiscovery)
                .withServiceFactory(dataStoreFactory)
                .withCachingPolicy(ServiceCachingPolicyBuilder.getMultiThreadedClientPolicy())
                .withMetricRegistry(metricRegistry)
                .buildProxy(new ExponentialBackoffRetry(5, 50, 1000, TimeUnit.MILLISECONDS));

        // Set the CloseableDataStore's close() method to close the service pool proxy and, if it was required, the curator.
        Runnable onClose = new Runnable() {
            @Override
            public void run() {
                _log.info("Closing service pool and ZooKeeper connection for {}", location);
                ServicePoolProxies.close(authDataStore);
                if (curator.isPresent()) {
                    try {
                        Closeables.close(curator.get(), true);
                    } catch (IOException e) {
                        // Won't happen, already caught
                    }
                }
            }
        };

        DataStore dataStore = DataStoreAuthenticator.proxied(authDataStore).usingCredentials(apiKey);
        return asCloseableDataStore(dataStore, Optional.of(onClose));
    }
678589
private void readParamsFromRegistryService(SessionProvider sessionProvider) throws PathNotFoundException,
      RepositoryException, RepositoryConfigurationException
   {

      String entryPath = RegistryService.EXO_SERVICES + "/" + SERVICE_NAME + "/" + ADMIN_INDENTITY;
      RegistryEntry registryEntry = registryService.getEntry(sessionProvider, entryPath);
      Document doc = registryEntry.getDocument();
      Element element = doc.getDocumentElement();
      adminIdentity = getAttributeSmart(element, "value");

      LOG.info("Admin identity is read from RegistryService");

      try
      {
         entryPath = RegistryService.EXO_SERVICES + "/" + SERVICE_NAME + "/" + DEFAULT_INDENTITY;
         registryEntry = registryService.getEntry(sessionProvider, entryPath);
         doc = registryEntry.getDocument();
         element = doc.getDocumentElement();
         defaultIdentity= getAttributeSmart(element, "value");

         LOG.info("Default identity is read from RegistryService");
      }
      catch (PathNotFoundException e)
      {
         LOG.debug("The admin identity exists but not the default identity, so we will recreate it");
         registryService.removeEntry(sessionProvider, RegistryService.EXO_SERVICES + "/" + SERVICE_NAME);
         throw e;
      }

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