<commit_before>/**
 * JBoss, Home of Professional Open Source.
 * Copyright 2014-2019 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jboss.pnc.model.utils;

import java.text.DecimalFormat;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.stream.Stream;

import org.hibernate.stat.CacheRegionStatistics;
import org.hibernate.stat.CollectionStatistics;
import org.hibernate.stat.EntityStatistics;
import org.hibernate.stat.Statistics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HibernateStatsUtils {

    private static final Logger logger = LoggerFactory.getLogger(HibernateStatsUtils.class);

    public static String ENTITY_STATS_PREFIX = "hibernate-orm.entity.";
    public static String REGION_STATS_PREFIX = "hibernate-orm.region.";
    public static String COLLECTION_STATS_PREFIX = "hibernate-orm.collection.";

    private static DecimalFormat df2 = new DecimalFormat("#.##");

    /**
     * Get all the Hibernate Entities statistics aggregated in a sorted Map
     * 
     * @param statistics
     * @return a sorted map containing all the Hibernate entities stats
     */
    public static SortedMap<String, Map<String, HibernateMetric>> getSecondLevelCacheEntitiesStats(Statistics statistics) {

        SortedMap<String, Map<String, HibernateMetric>> entitiesStatMap = new TreeMap<String, Map<String, HibernateMetric>>();

        if (statistics.isStatisticsEnabled()) {
            String[] entityNames = statistics.getEntityNames();
            Stream.of(entityNames).forEach(eN -> {
                EntityStatistics entityStat = statistics.getEntityStatistics(eN);
                SortedMap<String, HibernateMetric> entityStatMap = new TreeMap<String, HibernateMetric>();

                // Entity cache stats
                entityStatMap.put("cache.region.name", createHibernateMetricItem("cacheRegionName",
                        "The name of the region where this data is cached.", entityStat.getCacheRegionName()));
                entityStatMap.put("cache.hit.count", createHibernateMetricItem("cacheHitCount",
                        "The number of successful cache look-ups for this data from its configured cache region since the last Statistics clearing.",
                        entityStat.getCacheHitCount()));
                entityStatMap.put("cache.miss.count", createHibernateMetricItem("cacheMissCount",
                        "The number of unsuccessful cache look-ups for this data from its configured cache region since the last Statistics clearing.",
                        entityStat.getCacheMissCount()));
                entityStatMap.put("cache.put.count", createHibernateMetricItem("cachePutCount",
                        "The number of times this data has been into its configured cache region since the last Statistics clearing.",
                        entityStat.getCachePutCount()));
                double hitsRatio = (entityStat.getCacheHitCount() + entityStat.getCacheMissCount()) != 0
                        ? ((double) entityStat.getCacheHitCount()
                                / (entityStat.getCacheHitCount() + entityStat.getCacheMissCount()) * 100)
                        : -1;
                entityStatMap.put("cache.hit.ratio", createHibernateMetricItem("cacheHitRatio",
                        "The ratio of successful cache look-ups for this data from its configured cache region since the last Statistics clearing.",
                        df2.format(hitsRatio)));

                // Entity stats
                entityStatMap.put("fetch.count",
                        createHibernateMetricItem("fetchCount",
                                "Number of times (since last Statistics clearing) this entity has been fetched.",
                                entityStat.getFetchCount()));
                entityStatMap.put("insert.count",
                        createHibernateMetricItem("insertCount",
                                "Number of times (since last Statistics clearing) this entity has been inserted.",
                                entityStat.getInsertCount()));
                entityStatMap.put("delete.count",
                        createHibernateMetricItem("deleteCount",
                                "Number of times (since last Statistics clearing) this entity has been deleted.",
                                entityStat.getDeleteCount()));
                entityStatMap.put("load.count",
                        createHibernateMetricItem("loadCount",
                                "Number of times (since last Statistics clearing) this entity has been loaded.",
                                entityStat.getLoadCount()));
                entityStatMap.put("optimistic.failure.count", createHibernateMetricItem("optimisticFailureCount",
                        "Number of times (since last Statistics clearing) this entity has experienced an optimistic lock failure.",
                        entityStat.getOptimisticFailureCount()));
                entityStatMap.put("update.count",
                        createHibernateMetricItem("updateCount",
                                "Number of times (since last Statistics clearing) this entity has been updated.",
                                entityStat.getUpdateCount()));

                entitiesStatMap.put(ENTITY_STATS_PREFIX + eN, entityStatMap);
            });
        }

        return entitiesStatMap;
    }

    /**
     * Get all the Hibernate Entities second level cache statistics aggregated in a sorted Map
     * 
     * @param statistics
     * @return a sorted map containing all the Hibernate second level cache statistics
     */
    public static SortedMap<String, Map<String, HibernateMetric>> getSecondLevelCacheRegionsStats(Statistics statistics) {

        SortedMap<String, Map<String, HibernateMetric>> secondLevelCachesStatMap = new TreeMap<String, Map<String, HibernateMetric>>();

        if (statistics.isStatisticsEnabled()) {
            String[] cacheRegionNames = statistics.getSecondLevelCacheRegionNames();
            Stream.of(cacheRegionNames).forEach(crN -> {
                try {
                    CacheRegionStatistics sLCStats = statistics.getDomainDataRegionStatistics(crN);
                    SortedMap<String, HibernateMetric> sLCStatMap = new TreeMap<String, HibernateMetric>();

                    sLCStatMap.put("second-level-cache.cache.region.name", createHibernateMetricItem("regionName",
                            "The name of the region where this data is cached.", sLCStats.getRegionName()));

                    sLCStatMap.put("second-level-cache.element.count.in.memory",
                            createHibernateMetricItem("elementCountInMemory",
                                    "The number of elements currently in memory within the cache provider.",
                                    sLCStats.getElementCountInMemory() != CacheRegionStatistics.NO_EXTENDED_STAT_SUPPORT_RETURN
                                            ? sLCStats.getElementCountInMemory()
                                            : -1));
                    sLCStatMap.put("second-level-cache.element.count.on.disk",
                            createHibernateMetricItem("elementCountOnDisk",
                                    "The number of elements currently stored to disk within the cache provider.",
                                    sLCStats.getElementCountOnDisk() != CacheRegionStatistics.NO_EXTENDED_STAT_SUPPORT_RETURN
                                            ? sLCStats.getElementCountOnDisk()
                                            : -1));
                    sLCStatMap.put("second-level-cache.size.in.memory",
                            createHibernateMetricItem("sizeInMemory",
                                    "The size that the in-memory elements take up within the cache provider.",
                                    sLCStats.getSizeInMemory() != CacheRegionStatistics.NO_EXTENDED_STAT_SUPPORT_RETURN
                                            ? sLCStats.getSizeInMemory()
                                            : -1));

                    sLCStatMap.put("second-level-cache.hit.count", createHibernateMetricItem("hitCount",
                            "The number of successful cache look-ups against the region since the last Statistics clearing.",
                            sLCStats.getHitCount()));
                    sLCStatMap.put("second-level-cache.miss.count", createHibernateMetricItem("missCount",
                            "The number of unsuccessful cache look-ups against the region since the last Statistics clearing.",
                            sLCStats.getMissCount()));
                    double secondLvlCacheHitsRatio = (sLCStats.getHitCount() + sLCStats.getMissCount()) != 0
                            ? ((double) sLCStats.getHitCount() / (sLCStats.getHitCount() + sLCStats.getMissCount()) * 100)
                            : -1;
                    sLCStatMap.put("second-level-cache.hit.ratio", createHibernateMetricItem("hitRatio",
                            "The ratio of successful cache look-ups against the region since the last Statistics clearing.",
                            df2.format(secondLvlCacheHitsRatio)));
                    sLCStatMap.put("second-level-cache.put.count",
                            createHibernateMetricItem("putCount",
                                    "The number of cache puts into the region since the last Statistics clearing.",
                                    sLCStats.getPutCount()));

                    secondLevelCachesStatMap.put(REGION_STATS_PREFIX + crN, sLCStatMap);
                } catch (IllegalArgumentException e) {
                    logger.error("The region name could not be resolved: {}", e);
                }
            });
        }

        return secondLevelCachesStatMap;
    }

    /**
     * Get all the Hibernate collections statistics aggregated in a sorted Map
     * 
     * @param statistics
     * @return a sorted map containing all the Hibernate collections statistics
     */
    public static SortedMap<String, Map<String, HibernateMetric>> getSecondLevelCacheCollectionsStats(Statistics statistics) {

        SortedMap<String, Map<String, HibernateMetric>> collectionsStatMap = new TreeMap<String, Map<String, HibernateMetric>>();

        if (statistics.isStatisticsEnabled()) {
            String[] collectionRoleNames = statistics.getCollectionRoleNames();
            Stream.of(collectionRoleNames).forEach(crN -> {
                CollectionStatistics cStats = statistics.getCollectionStatistics(crN);
                SortedMap<String, HibernateMetric> cStatMap = new TreeMap<String, HibernateMetric>();

                // Collection cache stats
                cStatMap.put("cache.region.name", createHibernateMetricItem("cacheRegionName",
                        "The name of the region where this data is cached.", cStats.getCacheRegionName()));

                cStatMap.put("cache.hit.count", createHibernateMetricItem("cacheHitCount",
                        "The number of successful cache look-ups for this data from its configured cache region since the last Statistics clearing.",
                        cStats.getCacheHitCount()));<commit_msg>Remove logging of missing region caches to reduce noise in the logs<commit_after>/**
 * JBoss, Home of Professional Open Source.
 * Copyright 2014-2019 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jboss.pnc.model.utils;

import java.text.DecimalFormat;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.stream.Stream;

import org.hibernate.stat.CacheRegionStatistics;
import org.hibernate.stat.CollectionStatistics;
import org.hibernate.stat.EntityStatistics;
import org.hibernate.stat.Statistics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HibernateStatsUtils {

    private static final Logger logger = LoggerFactory.getLogger(HibernateStatsUtils.class);

    public static String ENTITY_STATS_PREFIX = "hibernate-orm.entity.";
    public static String REGION_STATS_PREFIX = "hibernate-orm.region.";
    public static String COLLECTION_STATS_PREFIX = "hibernate-orm.collection.";

    private static DecimalFormat df2 = new DecimalFormat("#.##");

    /**
     * Get all the Hibernate Entities statistics aggregated in a sorted Map
     * 
     * @param statistics
     * @return a sorted map containing all the Hibernate entities stats
     */
    public static SortedMap<String, Map<String, HibernateMetric>> getSecondLevelCacheEntitiesStats(Statistics statistics) {

        SortedMap<String, Map<String, HibernateMetric>> entitiesStatMap = new TreeMap<String, Map<String, HibernateMetric>>();

        if (statistics.isStatisticsEnabled()) {
            String[] entityNames = statistics.getEntityNames();
            Stream.of(entityNames).forEach(eN -> {
                EntityStatistics entityStat = statistics.getEntityStatistics(eN);
                SortedMap<String, HibernateMetric> entityStatMap = new TreeMap<String, HibernateMetric>();

                // Entity cache stats
                entityStatMap.put("cache.region.name", createHibernateMetricItem("cacheRegionName",
                        "The name of the region where this data is cached.", entityStat.getCacheRegionName()));
                entityStatMap.put("cache.hit.count", createHibernateMetricItem("cacheHitCount",
                        "The number of successful cache look-ups for this data from its configured cache region since the last Statistics clearing.",
                        entityStat.getCacheHitCount()));
                entityStatMap.put("cache.miss.count", createHibernateMetricItem("cacheMissCount",
                        "The number of unsuccessful cache look-ups for this data from its configured cache region since the last Statistics clearing.",
                        entityStat.getCacheMissCount()));
                entityStatMap.put("cache.put.count", createHibernateMetricItem("cachePutCount",
                        "The number of times this data has been into its configured cache region since the last Statistics clearing.",
                        entityStat.getCachePutCount()));
                double hitsRatio = (entityStat.getCacheHitCount() + entityStat.getCacheMissCount()) != 0
                        ? ((double) entityStat.getCacheHitCount()
                                / (entityStat.getCacheHitCount() + entityStat.getCacheMissCount()) * 100)
                        : -1;
                entityStatMap.put("cache.hit.ratio", createHibernateMetricItem("cacheHitRatio",
                        "The ratio of successful cache look-ups for this data from its configured cache region since the last Statistics clearing.",
                        df2.format(hitsRatio)));

                // Entity stats
                entityStatMap.put("fetch.count",
                        createHibernateMetricItem("fetchCount",
                                "Number of times (since last Statistics clearing) this entity has been fetched.",
                                entityStat.getFetchCount()));
                entityStatMap.put("insert.count",
                        createHibernateMetricItem("insertCount",
                                "Number of times (since last Statistics clearing) this entity has been inserted.",
                                entityStat.getInsertCount()));
                entityStatMap.put("delete.count",
                        createHibernateMetricItem("deleteCount",
                                "Number of times (since last Statistics clearing) this entity has been deleted.",
                                entityStat.getDeleteCount()));
                entityStatMap.put("load.count",
                        createHibernateMetricItem("loadCount",
                                "Number of times (since last Statistics clearing) this entity has been loaded.",
                                entityStat.getLoadCount()));
                entityStatMap.put("optimistic.failure.count", createHibernateMetricItem("optimisticFailureCount",
                        "Number of times (since last Statistics clearing) this entity has experienced an optimistic lock failure.",
                        entityStat.getOptimisticFailureCount()));
                entityStatMap.put("update.count",
                        createHibernateMetricItem("updateCount",
                                "Number of times (since last Statistics clearing) this entity has been updated.",
                                entityStat.getUpdateCount()));

                entitiesStatMap.put(ENTITY_STATS_PREFIX + eN, entityStatMap);
            });
        }

        return entitiesStatMap;
    }

    /**
     * Get all the Hibernate Entities second level cache statistics aggregated in a sorted Map
     * 
     * @param statistics
     * @return a sorted map containing all the Hibernate second level cache statistics
     */
    public static SortedMap<String, Map<String, HibernateMetric>> getSecondLevelCacheRegionsStats(Statistics statistics) {

        SortedMap<String, Map<String, HibernateMetric>> secondLevelCachesStatMap = new TreeMap<String, Map<String, HibernateMetric>>();

        if (statistics.isStatisticsEnabled()) {
            String[] cacheRegionNames = statistics.getSecondLevelCacheRegionNames();
            Stream.of(cacheRegionNames).forEach(crN -> {
                try {
                    CacheRegionStatistics sLCStats = statistics.getDomainDataRegionStatistics(crN);
                    SortedMap<String, HibernateMetric> sLCStatMap = new TreeMap<String, HibernateMetric>();

                    sLCStatMap.put("second-level-cache.cache.region.name", createHibernateMetricItem("regionName",
                            "The name of the region where this data is cached.", sLCStats.getRegionName()));

                    sLCStatMap.put("second-level-cache.element.count.in.memory",
                            createHibernateMetricItem("elementCountInMemory",
                                    "The number of elements currently in memory within the cache provider.",
                                    sLCStats.getElementCountInMemory() != CacheRegionStatistics.NO_EXTENDED_STAT_SUPPORT_RETURN
                                            ? sLCStats.getElementCountInMemory()
                                            : -1));
                    sLCStatMap.put("second-level-cache.element.count.on.disk",
                            createHibernateMetricItem("elementCountOnDisk",
                                    "The number of elements currently stored to disk within the cache provider.",
                                    sLCStats.getElementCountOnDisk() != CacheRegionStatistics.NO_EXTENDED_STAT_SUPPORT_RETURN
                                            ? sLCStats.getElementCountOnDisk()
                                            : -1));
                    sLCStatMap.put("second-level-cache.size.in.memory",
                            createHibernateMetricItem("sizeInMemory",
                                    "The size that the in-memory elements take up within the cache provider.",
                                    sLCStats.getSizeInMemory() != CacheRegionStatistics.NO_EXTENDED_STAT_SUPPORT_RETURN
                                            ? sLCStats.getSizeInMemory()
                                            : -1));

                    sLCStatMap.put("second-level-cache.hit.count", createHibernateMetricItem("hitCount",
                            "The number of successful cache look-ups against the region since the last Statistics clearing.",
                            sLCStats.getHitCount()));
                    sLCStatMap.put("second-level-cache.miss.count", createHibernateMetricItem("missCount",
                            "The number of unsuccessful cache look-ups against the region since the last Statistics clearing.",
                            sLCStats.getMissCount()));
                    double secondLvlCacheHitsRatio = (sLCStats.getHitCount() + sLCStats.getMissCount()) != 0
                            ? ((double) sLCStats.getHitCount() / (sLCStats.getHitCount() + sLCStats.getMissCount()) * 100)
                            : -1;
                    sLCStatMap.put("second-level-cache.hit.ratio", createHibernateMetricItem("hitRatio",
                            "The ratio of successful cache look-ups against the region since the last Statistics clearing.",
                            df2.format(secondLvlCacheHitsRatio)));
                    sLCStatMap.put("second-level-cache.put.count",
                            createHibernateMetricItem("putCount",
                                    "The number of cache puts into the region since the last Statistics clearing.",
                                    sLCStats.getPutCount()));

                    secondLevelCachesStatMap.put(REGION_STATS_PREFIX + crN, sLCStatMap);
                } catch (IllegalArgumentException e) {
                    //logger.error("The region name could not be resolved: {}", e);
                }
            });
        }

        return secondLevelCachesStatMap;
    }

    /**
     * Get all the Hibernate collections statistics aggregated in a sorted Map
     * 
     * @param statistics
     * @return a sorted map containing all the Hibernate collections statistics
     */
    public static SortedMap<String, Map<String, HibernateMetric>> getSecondLevelCacheCollectionsStats(Statistics statistics) {

        SortedMap<String, Map<String, HibernateMetric>> collectionsStatMap = new TreeMap<String, Map<String, HibernateMetric>>();

        if (statistics.isStatisticsEnabled()) {
            String[] collectionRoleNames = statistics.getCollectionRoleNames();
            Stream.of(collectionRoleNames).forEach(crN -> {
                CollectionStatistics cStats = statistics.getCollectionStatistics(crN);
                SortedMap<String, HibernateMetric> cStatMap = new TreeMap<String, HibernateMetric>();

                // Collection cache stats
                cStatMap.put("cache.region.name", createHibernateMetricItem("cacheRegionName",
                        "The name of the region where this data is cached.", cStats.getCacheRegionName()));

                cStatMap.put("cache.hit.count", createHibernateMetricItem("cacheHitCount",
                        "The number of successful cache look-ups for this data from its configured cache region since the last Statistics clearing.",
                        cStats.getCacheHitCount()));
{'fraction_non_alphanumeric': 0.08141385375659603, 'fraction_numerical': 0.00251277326409247, 'mean_word_length': 2.0867373319544984, 'pattern_counts': {'":': 0, '<': 51, '<?xml version=': 0, '>': 57, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 50, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6988673', 'n_tokens_mistral': 5566, 'n_tokens_neox': 5201, 'n_words': 1470}