Collects statistics about database connection memory usage.

@param dbStatsList The list to populate.
323536
void collectDbStats(ArrayList<com.couchbase.lite.internal.database.sqlite.SQLiteDebug.DbStats> dbStatsList) {
        // Get information about the main database.
        int lookaside = nativeGetDbLookaside(mConnectionPtr);
        long pageCount = 0;
        long pageSize = 0;
        try {
            pageCount = executeForLong("PRAGMA page_count;", null, null);
            pageSize = executeForLong("PRAGMA page_size;", null, null);
        } catch (com.couchbase.lite.internal.database.sqlite.exception.SQLiteException ex) {
            // Ignore.
        }
        dbStatsList.add(getMainDbStatsUnsafe(lookaside, pageCount, pageSize));
    }
788310
public static void collectStats(final StatsCollector collector) {
    collector.record("connectionmgr.connections", channels.size(), "type=open");
    collector.record("connectionmgr.connections", connections_rejected,
        "type=rejected");
    collector.record("connectionmgr.connections", connections_established, 
        "type=total");
    collector.record("connectionmgr.exceptions", exceptions_closed, 
        "type=closed");
    collector.record("connectionmgr.exceptions", exceptions_reset, 
        "type=reset");
    collector.record("connectionmgr.exceptions", exceptions_timeout, 
        "type=timeout");
    collector.record("connectionmgr.exceptions", exceptions_unknown, 
        "type=unknown");
  }
202971
async def dbpoolStats(self, *args, **kwargs):
        

        return await self._makeApiCall(self.funcinfo["dbpoolStats"], *args, **kwargs)
621120
private void updateMemoryPoolMetrics() {
    for (MemoryPoolMXBean memoryPoolMXBean : memoryPoolMXBeanList) {
      String normalizedKeyName = memoryPoolMXBean.getName().replaceAll("[^\\w]", "-");
      MemoryUsage peakUsage = memoryPoolMXBean.getPeakUsage();
      if (peakUsage != null) {
        jvmPeakUsagePerMemoryPool.safeScope(normalizedKeyName + "-used")
            .setValue(ByteAmount.fromBytes(peakUsage.getUsed()).asMegabytes());
        jvmPeakUsagePerMemoryPool.safeScope(normalizedKeyName + "-committed")
            .setValue(ByteAmount.fromBytes(peakUsage.getCommitted()).asMegabytes());
        jvmPeakUsagePerMemoryPool.safeScope(normalizedKeyName + "-max")
            .setValue(ByteAmount.fromBytes(peakUsage.getMax()).asMegabytes());
      }

      MemoryUsage collectionUsage = memoryPoolMXBean.getCollectionUsage();
      if (collectionUsage != null) {
        jvmCollectionUsagePerMemoryPool.safeScope(normalizedKeyName + "-used")
            .setValue(ByteAmount.fromBytes(collectionUsage.getUsed()).asMegabytes());
        jvmCollectionUsagePerMemoryPool.safeScope(normalizedKeyName + "-committed")
            .setValue(ByteAmount.fromBytes(collectionUsage.getCommitted()).asMegabytes());
        jvmCollectionUsagePerMemoryPool.safeScope(normalizedKeyName + "-max")
            .setValue(ByteAmount.fromBytes(collectionUsage.getMax()).asMegabytes());
      }

      MemoryUsage estimatedUsage = memoryPoolMXBean.getUsage();
      if (estimatedUsage != null) {
        jvmEstimatedUsagePerMemoryPool.safeScope(normalizedKeyName + "-used")
            .setValue(ByteAmount.fromBytes(estimatedUsage.getUsed()).asMegabytes());
        jvmEstimatedUsagePerMemoryPool.safeScope(normalizedKeyName + "-committed")
            .setValue(ByteAmount.fromBytes(estimatedUsage.getCommitted()).asMegabytes());
        jvmEstimatedUsagePerMemoryPool.safeScope(normalizedKeyName + "-max")
            .setValue(ByteAmount.fromBytes(estimatedUsage.getMax()).asMegabytes());
      }
    }
  }
327915
public static void visitStatistics (@Nonnull final IStatisticsVisitorCallback aCallback)
  {
    ValueEnforcer.notNull (aCallback, "Callback");

    // For all cache handler
    ICommonsList <String> aHandlers = StatisticsManager.getAllCacheHandler ().getSorted (Comparator.naturalOrder ());
    for (final String sName : aHandlers)
    {
      final IStatisticsHandlerCache aHandler = StatisticsManager.getCacheHandler (sName);
      aCallback.onCache (sName, aHandler);
    }

    // For all timer handler
    aHandlers = StatisticsManager.getAllTimerHandler ().getSorted (Comparator.naturalOrder ());
    for (final String sName : aHandlers)
    {
      final IStatisticsHandlerTimer aHandler = StatisticsManager.getTimerHandler (sName);
      aCallback.onTimer (sName, aHandler);
    }

    // For all keyed timer handler
    aHandlers = StatisticsManager.getAllKeyedTimerHandler ().getSorted (Comparator.naturalOrder ());
    for (final String sName : aHandlers)
    {
      final IStatisticsHandlerKeyedTimer aHandler = StatisticsManager.getKeyedTimerHandler (sName);
      aCallback.onKeyedTimer (sName, aHandler);
    }

    // For all size handler
    aHandlers = StatisticsManager.getAllSizeHandler ().getSorted (Comparator.naturalOrder ());
    for (final String sName : aHandlers)
    {
      final IStatisticsHandlerSize aHandler = StatisticsManager.getSizeHandler (sName);
      aCallback.onSize (sName, aHandler);
    }

    // For all keyed size handler
    aHandlers = StatisticsManager.getAllKeyedSizeHandler ().getSorted (Comparator.naturalOrder ());
    for (final String sName : aHandlers)
    {
      final IStatisticsHandlerKeyedSize aHandler = StatisticsManager.getKeyedSizeHandler (sName);
      aCallback.onKeyedSize (sName, aHandler);
    }

    // For all counter handler
    aHandlers = StatisticsManager.getAllCounterHandler ().getSorted (Comparator.naturalOrder ());
    for (final String sName : aHandlers)
    {
      final IStatisticsHandlerCounter aHandler = StatisticsManager.getCounterHandler (sName);
      aCallback.onCounter (sName, aHandler);
    }

    // For all keyed counter handler
    aHandlers = StatisticsManager.getAllKeyedCounterHandler ().getSorted (Comparator.naturalOrder ());
    for (final String sName : aHandlers)
    {
      final IStatisticsHandlerKeyedCounter aHandler = StatisticsManager.getKeyedCounterHandler (sName);
      aCallback.onKeyedCounter (sName, aHandler);
    }
  }
543573
private WSJdbcConnection[] resizeHandleList() {
        System.arraycopy(handlesInUse,
                         0,
                         handlesInUse = new WSJdbcConnection[
                                         maxHandlesInUse > numHandlesInUse ?
                                                         maxHandlesInUse :
                                                         (maxHandlesInUse = numHandlesInUse * 2)],
                         0,
                         numHandlesInUse);

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            Tr.debug(this, tc, 
                     "Handle limit increased to: " + maxHandlesInUse);

        return handlesInUse;
    }
1320008
public void cleanDataSources() {

        Hashtable<String, List<String>> removedDsKeyTable = null;

        //gather all the empty ds's key, can't remove item while iterate
        Enumeration<String> allPoolKeys = dbmsPoolTable.keys();
        while (allPoolKeys.hasMoreElements()) {
            String dbPoolKey = allPoolKeys.nextElement();
            Hashtable<String, DataSource> dsTable = dbmsPoolTable.get(dbPoolKey);
            Enumeration<String> allDsKeys = dsTable.keys();
            while (allDsKeys.hasMoreElements()) {
                String dsKey = allDsKeys.nextElement();
                DataSource ds = dsTable.get(dsKey);

                //c3p0 impl
                if (ds != null && ds instanceof PooledDataSource) {
                    PooledDataSource pDs = (PooledDataSource) ds;
                    int conCount;
                    try {
                        conCount = pDs.getNumConnectionsAllUsers();
                    } catch (SQLException e) {
//                  todo      logger.error
//                                ("Failed to get total number of connections for datasource. dbmsPoolKey = "
//                                        + dbPoolKey, e);
                        continue;
                    }
                    //no connections
                    if (conCount == 0) {
                        List<String> removedList = null;
                        if (removedDsKeyTable == null) {
                            removedDsKeyTable = new Hashtable<>();
                        } else {
                            removedList = removedDsKeyTable.get(dbPoolKey);
                        }

                        if (removedList == null) {
                            removedList = new ArrayList<>();
                            removedList.add(dsKey);
                            removedDsKeyTable.put(dbPoolKey, removedList);
                        } else {
                            removedList.add(dsKey);
                        }
                    }
                }
            }
        }

        //have empty ds
        if (removedDsKeyTable != null && !removedDsKeyTable.isEmpty()) {
            Enumeration<String> removedPoolKeys = removedDsKeyTable.keys();
            while (removedPoolKeys.hasMoreElements()) {
                String removedPoolKey = removedPoolKeys.nextElement();
                PooledDataSourceProvider provider = this.getProvider(removedPoolKey);
                List<String> removedDsList = removedDsKeyTable.get(removedPoolKey);
                Hashtable<String, DataSource> dsTable = dbmsPoolTable.get(removedPoolKey);
                for (String dsKey : removedDsList) {
                    DataSource removedDs = dsTable.remove(dsKey);
                    try {
                        provider.closePooledDataSource(removedDs);
                    } catch (SQLException e) {
                        //can't show the dsKey since it has encrypted password there
//                  todo      logger.error("Failed to close datadsource in dmbs poolKey = "
//                                + removedPoolKey, e);
                        continue;
                    }

                    //tracing
//                todo    if (logger.isDebugEnabled()) {
//                        logger.debug("Removed one datasource in dbms poolKey = "
//                                + removedPoolKey);
//                    }
                }
                //don't have any ds for the pool key
                if (dsTable.isEmpty()) {
                    dbmsPoolTable.remove(removedPoolKey);
                    //tracing
//              todo      if (logger.isDebugEnabled()) {
//                        logger.debug("Removed dbms poolKey = " + removedPoolKey);
//                    }
                }
            }
        }
    }
239458
public void setPolicyComplianceStatusList(java.util.Collection<PolicyComplianceStatus> policyComplianceStatusList) {
        if (policyComplianceStatusList == null) {
            this.policyComplianceStatusList = null;
            return;
        }

        this.policyComplianceStatusList = new java.util.ArrayList<PolicyComplianceStatus>(policyComplianceStatusList);
    }
459532
public function query_db($pagesize, $useinitialsbar = true) {
        global $DB;

        list($countsql, $countparams) = $this->get_sql_and_params(true);
        list($sql, $params) = $this->get_sql_and_params();
        $total = $DB->count_records_sql($countsql, $countparams);
        $this->pagesize($pagesize, $total);
        if ($this->is_downloading()) {
            $histories = $DB->get_records_sql($sql, $params);
        } else {
            $histories = $DB->get_records_sql($sql, $params, $this->pagesize * $this->page, $this->pagesize);
        }
        foreach ($histories as $history) {
            $this->rawdata[] = $history;
        }
        // Set initial bars.
        if ($useinitialsbar) {
            $this->initialbars($total > $pagesize);
        }
    }
233210
public void add(Rec fieldList) throws DBException
    {
        Record record = (Record)fieldList;
        if (((this.getRecord().getOpenMode() & DBConstants.OPEN_REFRESH_AND_LOCK_ON_CHANGE_STRATEGY) != DBConstants.OPEN_REFRESH_AND_LOCK_ON_CHANGE_STRATEGY)
            || (record.isRefreshedRecord()))
                this.restoreMainRecord(record, true);
        super.add(record);
    }
1020767
public java.util.List<DBInstanceStatusInfo> getStatusInfos() {
        if (statusInfos == null) {
            statusInfos = new com.amazonaws.internal.SdkInternalList<DBInstanceStatusInfo>();
        }
        return statusInfos;
    }
1060379
public void setDBInfoList(FSArray v) {
    if (ManualDescriptor_Type.featOkTst && ((ManualDescriptor_Type)jcasType).casFeat_dBInfoList == null)
      jcasType.jcas.throwFeatMissing("dBInfoList", "de.julielab.jules.types.pubmed.ManualDescriptor");
    jcasType.ll_cas.ll_setRefValue(addr, ((ManualDescriptor_Type)jcasType).casFeatCode_dBInfoList, jcasType.ll_cas.ll_getFSRef(v));}
1206154
private void statBasedSelectMetricHistory(final LinkedList<InMemoryHistoryNode> selectedLists)
      throws ClassCastException {
    logger.debug("selecting snapshots which are far away from mean value");
    final DescriptiveStatistics descStats = getDescriptiveStatistics(selectedLists);
    final Double mean = descStats.getMean();
    final Double std = descStats.getStandardDeviation();

    final Iterator<InMemoryHistoryNode> ite = selectedLists.iterator();
    while (ite.hasNext()) {
      final InMemoryHistoryNode currentNode = ite.next();
      final double value = ((Number) currentNode.getValue()).doubleValue();
      // remove all elements which lies in 95% value band
      if (value < mean + this.standardDeviationFactor * std
          && value > mean - this.standardDeviationFactor * std) {
        ite.remove();
      }
    }
  }
790802
public void cacheStatusObjects() {

        cachedStatusObjects = new HashMap<String, byte[]>();

        String statusCode;
        IoBuffer out = IoBuffer.allocate(256);
        out.setAutoExpand(true);

        for (String s : statusObjects.keySet()) {
            statusCode = s;
            StatusObject statusObject = statusObjects.get(statusCode);
            if (statusObject instanceof RuntimeStatusObject) {
                continue;
            }
            serializeStatusObject(out, statusObject);
            out.flip();
            if (log.isTraceEnabled()) {
                log.trace(HexDump.formatHexDump(out.getHexDump()));
            }
            byte[] cachedBytes = new byte[out.limit()];
            out.get(cachedBytes);
            out.clear();
            cachedStatusObjects.put(statusCode, cachedBytes);
        }
        out.free();
        out = null;
    }
1023065
protected void writeConnectionIdEntry(StringBuilder sb, ExecutionInfo execInfo, List<QueryInfo> queryInfoList) {
        sb.append("Connection:");
        sb.append(execInfo.getConnectionId());
        sb.append(", ");
    }
1265706
void statsCloseConnection(long duration,int requests)
    {
        synchronized(_statsLock)
        {
            _connections++;
            _connectionsOpen--;
            _connectionsDurationTotal+=duration;
            if (_connectionsOpen<0)
                _connectionsOpen=0;
            if (_connectionsOpen<_connectionsOpenMin)
                _connectionsOpenMin=_connectionsOpen;
            if (_connectionsDurationMin==0 || duration<_connectionsDurationMin)
                _connectionsDurationMin=duration;
            if (duration>_connectionsDurationMax)
                _connectionsDurationMax=duration;
            if (_connectionsRequestsMin==0 || requests<_connectionsRequestsMin)
                _connectionsRequestsMin=requests;
            if (requests>_connectionsRequestsMax)
                _connectionsRequestsMax=requests;
        }
    }
617604
public void add(Rec fieldList) throws DBException
    {
        Record record = (Record)fieldList;
        int iErrorCode = DBConstants.NORMAL_RETURN;
        if ((record.getOpenMode() & DBConstants.OPEN_READ_ONLY) != 0)
            throw new DatabaseException(DBConstants.ERROR_READ_ONLY);
        boolean[] rgbSaveEnabled = null;
        try   {
            if (record.getEditMode() != Constants.EDIT_ADD)
            {
                if (record.getEditMode() == Constants.EDIT_IN_PROGRESS)
                    if ((record.getOpenMode() & DBConstants.OPEN_REFRESH_AND_LOCK_ON_CHANGE_STRATEGY) == DBConstants.OPEN_REFRESH_AND_LOCK_ON_CHANGE_STRATEGY)
                { // Special case - Add with refresh/update on add
                    iErrorCode = record.handleRecordChange(DBConstants.ADD_TYPE);
                    if (iErrorCode != DBConstants.NORMAL_RETURN)
                        throw new DatabaseException(iErrorCode);
                    rgbSaveEnabled = record.setEnableListeners(false);      // Don't trigger any UPDATE listeners
                    if (record.isModified())
                        this.set(record);
                    record.setEnableListeners(rgbSaveEnabled);
                    rgbSaveEnabled = null;
                    iErrorCode = record.handleRecordChange(DBConstants.AFTER_ADD_TYPE);
                    if (iErrorCode != DBConstants.NORMAL_RETURN)
                        throw new DatabaseException(iErrorCode);
                    return;
                }
                throw new DatabaseException(DBConstants.INVALID_RECORD);
            }
            CounterField fldCounter = (CounterField)record.getCounterField();
            if (fldCounter != null)
                if (!DBConstants.FALSE.equalsIgnoreCase(this.getProperty(SQLParams.AUTO_SEQUENCE_ENABLED))) // Auto seq is enabled:
            {       // Just in case you had some data in the counter (it will be cleared).
                boolean[] rgbEnabled = fldCounter.setEnableListeners(false);
                fldCounter.setData(null);
                fldCounter.setEnableListeners(rgbEnabled);
            }
            iErrorCode = record.handleRecordChange(DBConstants.ADD_TYPE);
            if (iErrorCode != DBConstants.NORMAL_RETURN)
                throw new DatabaseException(iErrorCode);
            if (record.getEditMode() != Constants.EDIT_ADD)
            {   // It is possible that the add behavior wrote and refreshed the record, in that case, I need to update.
                if ((record.getEditMode() == Constants.EDIT_IN_PROGRESS) || (record.getEditMode() == Constants.EDIT_CURRENT))
                { // Special case - Add with refresh/update on add
                    rgbSaveEnabled = record.setEnableListeners(false);      // Don't trigger any UPDATE listeners
                    if (record.isModified())
                        this.set(record);
                    record.setEnableListeners(rgbSaveEnabled);
                    rgbSaveEnabled = null;
                    iErrorCode = record.handleRecordChange(DBConstants.AFTER_ADD_TYPE);
                    if (iErrorCode != DBConstants.NORMAL_RETURN)
                        throw new DatabaseException(iErrorCode);
                    return;
                }
                throw new DatabaseException(DBConstants.INVALID_RECORD);
            }
            this.fieldsToData(record);
            this.setLastModHint(record);
            this.doAdd(record);
            m_iRecordStatus |= DBConstants.RECORD_INVALID;
        } catch (DBException ex)    {
            if (rgbSaveEnabled != null)
                record.setEnableListeners(rgbSaveEnabled);
            if (ex.getErrorCode() == DBConstants.DUPLICATE_KEY)
            {   // If duplicate key, don't invalidate the record.
                iErrorCode = this.getRecord().handleErrorReturn(DBConstants.AFTER_ADD_TYPE, ex.getErrorCode()); // Give the listeners a chance to fix the error.
                if (iErrorCode == DBConstants.NORMAL_RETURN)
                    return;
            }
//x            else
//x                record.setEditMode(Constants.EDIT_NONE);
            throw ex;
        }
        iErrorCode = record.handleRecordChange(DBConstants.AFTER_ADD_TYPE);
        if (iErrorCode != DBConstants.NORMAL_RETURN)
            throw new DatabaseException(iErrorCode);
        record.setEditMode(Constants.EDIT_NONE);    // Unknown status after an add
        if ((record.getOpenMode() & DBConstants.OPEN_REFRESH_AND_LOCK_ON_CHANGE_STRATEGY) == DBConstants.OPEN_REFRESH_AND_LOCK_ON_CHANGE_STRATEGY)
            return;   // Will need these to refresh record
        m_objectID = null;
        m_dataSource = null;
    }