Example usage for org.hibernate.stat Statistics getSecondLevelCachePutCount

List of usage examples for org.hibernate.stat Statistics getSecondLevelCachePutCount

Introduction

In this page you can find the example usage for org.hibernate.stat Statistics getSecondLevelCachePutCount.

Prototype

long getSecondLevelCachePutCount();

Source Link

Document

Global number of cacheable entities/collections put in the cache

Usage

From source file:com.hazelcast.hibernate.LocalRegionFactoryDefaultTest.java

License:Open Source License

@Test
public void testEntity() {
    final HazelcastInstance hz = getHazelcastInstance(sf);
    assertNotNull(hz);/*  w  w w . j  av a2 s  . c om*/
    final int count = 100;
    final int childCount = 3;
    insertDummyEntities(count, childCount);
    List<DummyEntity> list = new ArrayList<DummyEntity>(count);
    Session session = sf.openSession();
    try {
        for (int i = 0; i < count; i++) {
            DummyEntity e = (DummyEntity) session.get(DummyEntity.class, (long) i);
            session.evict(e);
            list.add(e);
        }
    } finally {
        session.close();
    }
    session = sf.openSession();
    Transaction tx = session.beginTransaction();
    try {
        for (DummyEntity dummy : list) {
            dummy.setDate(new Date());
            session.update(dummy);
        }
        tx.commit();
    } catch (Exception e) {
        tx.rollback();
        e.printStackTrace();
    } finally {
        session.close();
    }

    Statistics stats = sf.getStatistics();
    assertEquals((childCount + 1) * count, stats.getEntityInsertCount());
    // twice put of entity and properties (on load and update) and once put of collection
    assertEquals((childCount + 1) * count * 2 + count, stats.getSecondLevelCachePutCount());
    assertEquals(childCount * count, stats.getEntityLoadCount());
    assertEquals(count, stats.getSecondLevelCacheHitCount());
    // collection cache miss
    assertEquals(count, stats.getSecondLevelCacheMissCount());
    stats.logSummary();
}

From source file:com.thoughtworks.go.server.service.support.HibernateInformationProvider.java

License:Apache License

@Override
public Map<String, Object> asJson() {
    LinkedHashMap<String, Object> json = new LinkedHashMap<>();
    Statistics statistics = sessionFactory.getStatistics();
    if (!statistics.isStatisticsEnabled()) {
        return json;
    }//from   w  w w.  ja  va 2s.  c  om
    json.put("EntityDeleteCount", statistics.getEntityDeleteCount());
    json.put("EntityInsertCount", statistics.getEntityInsertCount());
    json.put("EntityLoadCount", statistics.getEntityLoadCount());
    json.put("EntityFetchCount", statistics.getEntityFetchCount());
    json.put("EntityUpdateCount", statistics.getEntityUpdateCount());
    json.put("QueryExecutionCount", statistics.getQueryExecutionCount());
    json.put("QueryExecutionMaxTime", statistics.getQueryExecutionMaxTime());
    json.put("QueryExecutionMaxTimeQueryString", statistics.getQueryExecutionMaxTimeQueryString());
    json.put("QueryCacheHitCount", statistics.getQueryCacheHitCount());
    json.put("QueryCacheMissCount", statistics.getQueryCacheMissCount());
    json.put("QueryCachePutCount", statistics.getQueryCachePutCount());
    json.put("FlushCount", statistics.getFlushCount());
    json.put("ConnectCount", statistics.getConnectCount());
    json.put("SecondLevelCacheHitCount", statistics.getSecondLevelCacheHitCount());
    json.put("SecondLevelCacheMissCount", statistics.getSecondLevelCacheMissCount());
    json.put("SecondLevelCachePutCount", statistics.getSecondLevelCachePutCount());
    json.put("SessionCloseCount", statistics.getSessionCloseCount());
    json.put("SessionOpenCount", statistics.getSessionOpenCount());
    json.put("CollectionLoadCount", statistics.getCollectionLoadCount());
    json.put("CollectionFetchCount", statistics.getCollectionFetchCount());
    json.put("CollectionUpdateCount", statistics.getCollectionUpdateCount());
    json.put("CollectionRemoveCount", statistics.getCollectionRemoveCount());
    json.put("CollectionRecreateCount", statistics.getCollectionRecreateCount());
    json.put("StartTime", statistics.getStartTime());
    json.put("SecondLevelCacheRegionNames", statistics.getSecondLevelCacheRegionNames());
    json.put("SuccessfulTransactionCount", statistics.getSuccessfulTransactionCount());
    json.put("TransactionCount", statistics.getTransactionCount());
    json.put("PrepareStatementCount", statistics.getPrepareStatementCount());
    json.put("CloseStatementCount", statistics.getCloseStatementCount());
    json.put("OptimisticFailureCount", statistics.getOptimisticFailureCount());

    LinkedHashMap<String, Object> queryStats = new LinkedHashMap<>();
    json.put("Queries", queryStats);

    String[] queries = statistics.getQueries();
    for (String query : queries) {
        queryStats.put(query, statistics.getQueryStatistics(query));
    }

    LinkedHashMap<String, Object> entityStatistics = new LinkedHashMap<>();
    json.put("EntityStatistics", entityStatistics);

    String[] entityNames = statistics.getEntityNames();
    for (String entityName : entityNames) {
        entityStatistics.put(entityName, statistics.getEntityStatistics(entityName));
    }

    LinkedHashMap<String, Object> roleStatistics = new LinkedHashMap<>();
    json.put("RoleStatistics", roleStatistics);

    String[] roleNames = statistics.getCollectionRoleNames();
    for (String roleName : roleNames) {
        roleStatistics.put(roleName, statistics.getCollectionStatistics(roleName));
    }

    return json;
}

From source file:de.iew.framework.hibernate.statistics.StatisticsLogger.java

License:Apache License

public void logStatistics() {
    Statistics statistics = this.sessionFactory.getStatistics();
    statistics.setStatisticsEnabled(true);
    StringBuilder sb = new StringBuilder("\nStatistics");
    sb.append("\nCloseStatementCount: ").append(statistics.getCloseStatementCount());

    sb.append("\nEntityDeleteCount: ").append(statistics.getEntityDeleteCount());
    sb.append("\nEntityInsertCount: ").append(statistics.getEntityInsertCount());
    sb.append("\nEntityLoadCount: ").append(statistics.getEntityLoadCount());
    sb.append("\nEntityFetchCount: ").append(statistics.getEntityFetchCount());
    sb.append("\nEntityUpdateCount: ").append(statistics.getEntityUpdateCount());
    sb.append("\nQueryExecutionCount: ").append(statistics.getQueryExecutionCount());
    sb.append("\nQueryExecutionMaxTime: ").append(statistics.getQueryExecutionMaxTime());
    sb.append("\nQueryExecutionMaxTimeQueryString: ").append(statistics.getQueryExecutionMaxTimeQueryString());
    sb.append("\nQueryCacheHitCount: ").append(statistics.getQueryCacheHitCount());
    sb.append("\nQueryCacheMissCount: ").append(statistics.getQueryCacheMissCount());
    sb.append("\nQueryCachePutCount: ").append(statistics.getQueryCachePutCount());
    sb.append("\nNaturalIdQueryExecutionCount: ").append(statistics.getNaturalIdQueryExecutionCount());
    sb.append("\nNaturalIdQueryExecutionMaxTime: ").append(statistics.getNaturalIdQueryExecutionMaxTime());
    sb.append("\nNaturalIdQueryExecutionMaxTimeRegion: ")
            .append(statistics.getNaturalIdQueryExecutionMaxTimeRegion());
    sb.append("\nNaturalIdCacheHitCount: ").append(statistics.getNaturalIdCacheHitCount());
    sb.append("\nNaturalIdCacheMissCount: ").append(statistics.getNaturalIdCacheMissCount());
    sb.append("\nNaturalIdCachePutCount: ").append(statistics.getNaturalIdCachePutCount());
    sb.append("\nUpdateTimestampsCacheHitCount: ").append(statistics.getUpdateTimestampsCacheHitCount());
    sb.append("\nUpdateTimestampsCacheMissCount: ").append(statistics.getUpdateTimestampsCacheMissCount());
    sb.append("\nUpdateTimestampsCachePutCount: ").append(statistics.getUpdateTimestampsCachePutCount());
    sb.append("\nFlushCount: ").append(statistics.getFlushCount());
    sb.append("\nConnectCount: ").append(statistics.getConnectCount());
    sb.append("\nSecondLevelCacheHitCount: ").append(statistics.getSecondLevelCacheHitCount());
    sb.append("\nSecondLevelCacheMissCount: ").append(statistics.getSecondLevelCacheMissCount());
    sb.append("\nSecondLevelCachePutCount: ").append(statistics.getSecondLevelCachePutCount());
    sb.append("\nSessionCloseCount: ").append(statistics.getSessionCloseCount());
    sb.append("\nSessionOpenCount: ").append(statistics.getSessionOpenCount());
    sb.append("\nCollectionLoadCount: ").append(statistics.getCollectionLoadCount());
    sb.append("\nCollectionFetchCount: ").append(statistics.getCollectionFetchCount());
    sb.append("\nCollectionUpdateCount: ").append(statistics.getCollectionUpdateCount());
    sb.append("\nCollectionRemoveCount: ").append(statistics.getCollectionRemoveCount());
    sb.append("\nCollectionRecreateCount: ").append(statistics.getCollectionRecreateCount());
    sb.append("\nStartTime: ").append(statistics.getStartTime());
    sb.append("\nQueries: ").append(statistics.getQueries());
    sb.append("\nEntityNames: ").append(statistics.getEntityNames());
    sb.append("\nCollectionRoleNames: ").append(statistics.getCollectionRoleNames());
    sb.append("\nSecondLevelCacheRegionNames: ").append(statistics.getSecondLevelCacheRegionNames());
    sb.append("\nSuccessfulTransactionCount: ").append(statistics.getSuccessfulTransactionCount());
    sb.append("\nTransactionCount: ").append(statistics.getTransactionCount());
    sb.append("\nPrepareStatementCount: ").append(statistics.getPrepareStatementCount());
    sb.append("\nCloseStatementCount: ").append(statistics.getCloseStatementCount());
    sb.append("\nOptimisticFailureCount: ").append(statistics.getOptimisticFailureCount());

    if (log.isDebugEnabled()) {
        log.debug(sb);/*  w ww  .j a  va 2  s  . c om*/
    }

}

From source file:models.papmon.HibernateStat.java

License:Open Source License

public HibernateStat(Date refDate) {
    created = refDate;//from   ww w. ja  v  a  2s  .c om
    Session session = (Session) JPA.em().getDelegate();
    Statistics stats = session.getSessionFactory().getStatistics();
    queryExecutionCount = stats.getQueryExecutionCount();
    queryExecutionMaxTime = stats.getQueryExecutionMaxTime();
    sessionOpenCount = stats.getSessionOpenCount();
    sessionCloseCount = stats.getSessionCloseCount();
    entityLoadCount = stats.getEntityLoadCount();
    entityInsertCount = stats.getEntityInsertCount();
    entityUpdateCount = stats.getEntityUpdateCount();
    entityDeleteCount = stats.getEntityDeleteCount();
    entityFetchCount = stats.getEntityFetchCount();
    queryCacheHitCount = stats.getQueryCacheHitCount();
    queryCacheMissCount = stats.getQueryCacheMissCount();
    queryCachePutCount = stats.getQueryCachePutCount();
    secondLevelCacheHitCount = stats.getSecondLevelCacheHitCount();
    secondLevelCacheMissCount = stats.getSecondLevelCacheMissCount();
    secondLevelCachePutCount = stats.getSecondLevelCachePutCount();
    stats.clear();
}

From source file:net.welen.buzz.typehandler.impl.hibernate.HibernateStatisticsUnitHandler.java

License:Open Source License

public void getValues(BuzzAnswer values) throws TypeHandlerException {
    for (String name : getMeasurableUnits()) {
        boolean debug = LOG.isDebugEnabled();

        // Find the Hibernate Session Factory in JNDI
        SessionFactory sessionFactory = null;

        Object o;/*  ww  w  .  j  a va 2 s .c o  m*/
        try {
            if (debug) {
                LOG.debug("Looking up: " + name);
            }
            o = new InitialContext().lookup(name);
        } catch (NamingException e) {
            throw new TypeHandlerException(e);
        }
        if (debug) {
            LOG.debug("Found class: " + o.getClass().getName());
        }

        if (o.getClass().getName().equals("org.hibernate.ejb.EntityManagerFactoryImpl")) {
            // Hibernate 4
            sessionFactory = ((EntityManagerFactoryImpl) o).getSessionFactory();
        } else {
            // Hibernate 3
            sessionFactory = (SessionFactory) o;
        }

        // Get all values
        Statistics stats = sessionFactory.getStatistics();
        String measurementUnit = getMeasurementUnit();
        values.put(measurementUnit, name, "SessionOpenCount", stats.getSessionOpenCount());
        values.put(measurementUnit, name, "SessionCloseCount", stats.getSessionCloseCount());
        values.put(measurementUnit, name, "FlushCount", stats.getFlushCount());
        values.put(measurementUnit, name, "ConnectCount", stats.getConnectCount());
        values.put(measurementUnit, name, "PrepareStatementCount", stats.getPrepareStatementCount());
        values.put(measurementUnit, name, "CloseStatementCount", stats.getCloseStatementCount());
        values.put(measurementUnit, name, "EntityLoadCount", stats.getEntityLoadCount());
        values.put(measurementUnit, name, "EntityUpdateCount", stats.getEntityUpdateCount());
        values.put(measurementUnit, name, "EntityInsertCount", stats.getEntityInsertCount());
        values.put(measurementUnit, name, "EntityDeleteCount", stats.getEntityDeleteCount());
        values.put(measurementUnit, name, "EntityFetchCount", stats.getEntityFetchCount());
        values.put(measurementUnit, name, "CollectionLoadCount", stats.getCollectionLoadCount());
        values.put(measurementUnit, name, "CollectionUpdateCount", stats.getCollectionUpdateCount());
        values.put(measurementUnit, name, "CollectionRemoveCount", stats.getCollectionRemoveCount());
        values.put(measurementUnit, name, "CollectionRecreateCount", stats.getCollectionRecreateCount());
        values.put(measurementUnit, name, "CollectionFetchCount", stats.getCollectionFetchCount());
        values.put(measurementUnit, name, "SecondLevelCacheHitCount", stats.getSecondLevelCacheHitCount());
        values.put(measurementUnit, name, "SecondLevelCacheMissCount", stats.getSecondLevelCacheMissCount());
        values.put(measurementUnit, name, "SecondLevelCachePutCount", stats.getSecondLevelCachePutCount());
        values.put(measurementUnit, name, "QueryExecutionCount", stats.getQueryExecutionCount());
        values.put(measurementUnit, name, "QueryExecutionMaxTime", stats.getQueryExecutionMaxTime());
        values.put(measurementUnit, name, "QueryCacheHitCount", stats.getQueryCacheHitCount());
        values.put(measurementUnit, name, "QueryCacheMissCount", stats.getQueryCacheMissCount());
        values.put(measurementUnit, name, "QueryCachePutCount", stats.getQueryCachePutCount());
        values.put(measurementUnit, name, "TransactionCount", stats.getTransactionCount());
        values.put(measurementUnit, name, "OptimisticFailureCount", stats.getOptimisticFailureCount());

        // TODO What about?
        // sessionFactory.getStatistics().getEntityStatistics(<parameter from setup? OR loop?>).
        // sessionFactory.getStatistics().getCollectionStatistics(<parameter from setup? OR loop?>)
        // sessionFactory.getStatistics().getQueryStatistics(<<parameter from setup? OR loop?>)
    }
}

From source file:org.cast.cwm.admin.CacheManagementPage.java

License:Open Source License

public CacheManagementPage(PageParameters parameters) {
    super(parameters);

    Statistics statistics = Databinder.getHibernateSessionFactory().getStatistics();

    add(new Label("statisticsEnabled", statistics.isStatisticsEnabled() ? "on" : "off"));

    long hitCount = statistics.getSecondLevelCacheHitCount();
    long missCount = statistics.getSecondLevelCacheMissCount();
    long totalCount = hitCount + missCount;

    add(new Label("slcPut", String.valueOf(statistics.getSecondLevelCachePutCount())));
    add(new Label("slcHit", String.valueOf(hitCount)));
    add(new Label("slcMiss", String.valueOf(missCount)));
    add(new Label("slcHitP", String.valueOf(totalCount > 0 ? Math.round(100d * hitCount / totalCount) : 0)));
    add(new Label("slcMissP", String.valueOf(totalCount > 0 ? Math.round(100d * missCount / totalCount) : 0)));

    CacheManager ehcache = CacheManager.getInstance();
    String[] caches = ehcache.getCacheNames();
    Arrays.sort(caches);//  ww  w .  j a va  2 s.c  o m

    RepeatingView cacheView = new RepeatingView("cacheView");
    add(cacheView);
    for (String name : caches) {
        WebMarkupContainer eView = new WebMarkupContainer(cacheView.newChildId());
        cacheView.add(eView);
        net.sf.ehcache.Cache cache = ehcache.getCache(name);
        int size = cache.getSize();

        eView.add(new Label("name", name));
        eView.add(new Label("items", size > 0 ? String.valueOf(size) : ""));
    }

    add(new ClearCacheLink("clear"));

}

From source file:org.glite.security.voms.admin.core.tasks.LogHibernateStatsTask.java

License:Apache License

@Override
public void run() {

    Statistics stats = HibernateFactory.getFactory().getStatistics();
    if (stats != null) {
        LOG.info("Logging statistics....");
        LOG.info("start time: {}", stats.getStartTime());
        LOG.info("sessions opened: {}", stats.getSessionOpenCount());
        LOG.info("sessions closed: {}", stats.getSessionCloseCount());
        LOG.info("transactions: {}", stats.getTransactionCount());
        LOG.info("successful transactions: {}", stats.getSuccessfulTransactionCount());
        LOG.info("optimistic lock failures: {}", stats.getOptimisticFailureCount());
        LOG.info("flushes: {}", stats.getFlushCount());
        LOG.info("connections obtained: {}", stats.getConnectCount());
        LOG.info("statements prepared: {}", stats.getPrepareStatementCount());
        LOG.info("statements closed: {}", stats.getCloseStatementCount());
        LOG.info("second level cache puts: {}", stats.getSecondLevelCachePutCount());
        LOG.info("second level cache hits: {}", stats.getSecondLevelCacheHitCount());
        LOG.info("second level cache misses: {}", stats.getSecondLevelCacheMissCount());
        LOG.info("entities loaded: {}", stats.getEntityLoadCount());
        LOG.info("entities updated: {}", stats.getEntityUpdateCount());
        LOG.info("entities inserted: {}", stats.getEntityInsertCount());
        LOG.info("entities deleted: {}", stats.getEntityDeleteCount());
        LOG.info("entities fetched (minimize this): {}", stats.getEntityFetchCount());
        LOG.info("collections loaded: {}", stats.getCollectionLoadCount());
        LOG.info("collections updated: {}", stats.getCollectionUpdateCount());
        LOG.info("collections removed: {}", stats.getCollectionRemoveCount());
        LOG.info("collections recreated: {}", stats.getCollectionRecreateCount());
        LOG.info("collections fetched (minimize this): {}", stats.getCollectionFetchCount());
        LOG.info("queries executed to database: {}", stats.getQueryExecutionCount());
        LOG.info("query cache puts: {}", stats.getQueryCachePutCount());
        LOG.info("query cache hits: {}", stats.getQueryCacheMissCount());
        LOG.info("query cache misses: {}", stats.getQueryCacheMissCount());
        LOG.info("max query time: {} ms, for query {}", stats.getQueryExecutionMaxTime(),
                stats.getQueryExecutionMaxTimeQueryString());
    }//w  w w  .j av  a2s  . c om
}

From source file:org.infinispan.test.hibernate.cache.commons.functional.ReadOnlyTest.java

License:LGPL

@Test
public void testInsertClearCacheDeleteEntity() throws Exception {
    final Statistics stats = sessionFactory().getStatistics();
    stats.clear();/* w  w  w .j a v a2s .co  m*/

    final Item item = new Item("chris", "Chris's Item");
    withTxSession(s -> s.persist(item));
    assertEquals(0, stats.getSecondLevelCacheMissCount());
    assertEquals(0, stats.getSecondLevelCacheHitCount());
    assertEquals(1, stats.getSecondLevelCachePutCount());

    log.info("Entry persisted, let's load and delete it.");

    cleanupCache();
    TIME_SERVICE.advance(1);

    withTxSession(s -> {
        Item found = s.load(Item.class, item.getId());
        log.info(stats.toString());
        assertEquals(item.getDescription(), found.getDescription());
        assertEquals(1, stats.getSecondLevelCacheMissCount());
        assertEquals(0, stats.getSecondLevelCacheHitCount());
        assertEquals(2, stats.getSecondLevelCachePutCount());
        s.delete(found);
    });
}

From source file:org.jboss.as.jpa.hibernate4.management.HibernateManagementAdaptor.java

License:Open Source License

private void registerStatisticAttributes(ManagementResourceRegistration jpaHibernateRegistration) {

    /**/*  w ww . ja v  a2s. c  o  m*/
     * Get global number of entity deletes
     * @return entity deletion count
     */
    jpaHibernateRegistration.registerMetric(OPERATION_ENTITY_DELETE_COUNT, new AbstractMetricsHandler() {
        @Override
        void handle(final ModelNode response, final String name, Statistics stats, OperationContext context) {
            response.set(stats.getEntityDeleteCount());
        }
    });

    /**
     * Get global number of entity inserts
     * @return entity insertion count
     */
    jpaHibernateRegistration.registerMetric(OPERATION_ENTITY_INSERT_COUNT, new AbstractMetricsHandler() {
        @Override
        void handle(final ModelNode response, final String name, Statistics stats, OperationContext context) {
            response.set(stats.getEntityInsertCount());
        }
    });

    /**
     * Get global number of entity loads
     * @return entity load (from DB)
     */
    jpaHibernateRegistration.registerMetric(OPERATION_ENTITY_LOAD_COUNT, new AbstractMetricsHandler() {
        @Override
        void handle(final ModelNode response, final String name, Statistics stats, OperationContext context) {
            response.set(stats.getEntityLoadCount());
        }
    });

    /**
     * Get global number of entity fetchs
     * @return entity fetch (from DB)
     */
    jpaHibernateRegistration.registerMetric(OPERATION_ENTITY_FETCH_COUNT, new AbstractMetricsHandler() {
        @Override
        void handle(final ModelNode response, final String name, Statistics stats, OperationContext context) {
            response.set(stats.getEntityFetchCount());
        }
    });

    /**
     * Get global number of entity updates
     * @return entity update
     */
    jpaHibernateRegistration.registerMetric(OPERATION_ENTITY_UPDATE_COUNT, new AbstractMetricsHandler() {
        @Override
        void handle(final ModelNode response, final String name, Statistics stats, OperationContext context) {
            response.set(stats.getEntityUpdateCount());
        }
    });

    /**
     * Get global number of executed queries
     * @return query execution count
     */
    jpaHibernateRegistration.registerMetric(OPERATION_QUERY_EXECUTION_COUNT, new AbstractMetricsHandler() {
        @Override
        void handle(final ModelNode response, final String name, Statistics stats, OperationContext context) {
            response.set(stats.getQueryExecutionCount());
        }
    });

    /**
     * Get the time in milliseconds of the slowest query.
     */
    jpaHibernateRegistration.registerMetric(OPERATION_QUERY_EXECUTION_MAX_TIME, new AbstractMetricsHandler() {
        @Override
        void handle(final ModelNode response, final String name, Statistics stats, OperationContext context) {
            response.set(stats.getQueryExecutionMaxTime());
        }
    });

    /**
     * Get the query string for the slowest query.
     */
    jpaHibernateRegistration.registerMetric(OPERATION_QUERY_EXECUTION_MAX_TIME_QUERY_STRING,
            new AbstractMetricsHandler() {
                @Override
                void handle(final ModelNode response, final String name, Statistics stats,
                        OperationContext context) {
                    String sql = stats.getQueryExecutionMaxTimeQueryString();
                    if (sql != null) {
                        response.set(sql);
                    } else {
                        context.getResult(); // result will be undefined
                    }
                }
            });

    /**
     * Get the global number of cached queries successfully retrieved from cache
     */
    jpaHibernateRegistration.registerMetric(OPERATION_QUERY_CACHE_HIT_COUNT, new AbstractMetricsHandler() {
        @Override
        void handle(final ModelNode response, final String name, Statistics stats, OperationContext context) {
            response.set(stats.getQueryCacheHitCount());
        }
    });

    /**
     * Get the global number of cached queries *not* found in cache
     */
    jpaHibernateRegistration.registerMetric(OPERATION_QUERY_CACHE_MISS_COUNT, new AbstractMetricsHandler() {
        @Override
        void handle(final ModelNode response, final String name, Statistics stats, OperationContext context) {
            response.set(stats.getQueryCacheMissCount());
        }
    });

    /**
     * Get the global number of cacheable queries put in cache
     */
    jpaHibernateRegistration.registerMetric(OPERATION_QUERY_CACHE_PUT_COUNT, new AbstractMetricsHandler() {
        @Override
        void handle(final ModelNode response, final String name, Statistics stats, OperationContext context) {
            response.set(stats.getQueryCachePutCount());
        }
    });

    /**
     * Get the global number of flush executed by sessions (either implicit or explicit)
     */
    jpaHibernateRegistration.registerMetric(OPERATION_FLUSH_COUNT, new AbstractMetricsHandler() {
        @Override
        void handle(final ModelNode response, final String name, Statistics stats, OperationContext context) {
            response.set(stats.getFlushCount());
        }
    });

    /**
     * Get the global number of connections asked by the sessions
     * (the actual number of connections used may be much smaller depending
     * whether you use a connection pool or not)
     */
    jpaHibernateRegistration.registerMetric(OPERATION_CONNECT_COUNT, new AbstractMetricsHandler() {
        @Override
        void handle(final ModelNode response, final String name, Statistics stats, OperationContext context) {
            response.set(stats.getConnectCount());
        }
    });

    /**
     * Global number of cacheable entities/collections successfully retrieved from the cache
     */
    jpaHibernateRegistration.registerMetric(OPERATION_SECOND_LEVEL_CACHE_HIT_COUNT,
            new AbstractMetricsHandler() {
                @Override
                void handle(final ModelNode response, final String name, Statistics stats,
                        OperationContext context) {
                    response.set(stats.getSecondLevelCacheHitCount());
                }
            });

    /**
     * Global number of cacheable entities/collections not found in the cache and loaded from the database.
     */
    jpaHibernateRegistration.registerMetric(OPERATION_SECOND_LEVEL_CACHE_MISS_COUNT,
            new AbstractMetricsHandler() {
                @Override
                void handle(final ModelNode response, final String name, Statistics stats,
                        OperationContext context) {
                    response.set(stats.getSecondLevelCacheMissCount());
                }
            });

    /**
     * Global number of cacheable entities/collections put in the cache
     */
    jpaHibernateRegistration.registerMetric(OPERATION_SECOND_LEVEL_CACHE_PUT_COUNT,
            new AbstractMetricsHandler() {
                @Override
                void handle(final ModelNode response, final String name, Statistics stats,
                        OperationContext context) {
                    response.set(stats.getSecondLevelCachePutCount());
                }
            });

    /**
     * Global number of sessions closed
     */
    jpaHibernateRegistration.registerMetric(OPERATION_SESSION_CLOSE_COUNT, new AbstractMetricsHandler() {
        @Override
        void handle(final ModelNode response, final String name, Statistics stats, OperationContext context) {
            response.set(stats.getSessionCloseCount());
        }
    });

    /**
     * Global number of sessions opened
     */
    jpaHibernateRegistration.registerMetric(OPERATION_SESSION_OPEN_COUNT, new AbstractMetricsHandler() {
        @Override
        void handle(final ModelNode response, final String name, Statistics stats, OperationContext context) {
            response.set(stats.getSessionOpenCount());
        }
    });

    /**
     * Global number of collections loaded
     */
    jpaHibernateRegistration.registerMetric(OPERATION_COLLECTION_LOAD_COUNT, new AbstractMetricsHandler() {
        @Override
        void handle(final ModelNode response, final String name, Statistics stats, OperationContext context) {
            response.set(stats.getCollectionLoadCount());
        }
    });

    /**
     * Global number of collections fetched
     */
    jpaHibernateRegistration.registerMetric(OPERATION_COLLECTION_FETCH_COUNT, new AbstractMetricsHandler() {
        @Override
        void handle(final ModelNode response, final String name, Statistics stats, OperationContext context) {
            response.set(stats.getCollectionFetchCount());
        }
    });

    /**
     * Global number of collections updated
     */
    jpaHibernateRegistration.registerMetric(OPERATION_COLLECTION_UPDATE_COUNT, new AbstractMetricsHandler() {
        @Override
        void handle(final ModelNode response, final String name, Statistics stats, OperationContext context) {
            response.set(stats.getCollectionUpdateCount());
        }
    });

    /**
     * Global number of collections removed
     */
    //even on inverse="true"
    jpaHibernateRegistration.registerMetric(OPERATION_COLLECTION_REMOVE_COUNT, new AbstractMetricsHandler() {
        @Override
        void handle(final ModelNode response, final String name, Statistics stats, OperationContext context) {
            response.set(stats.getCollectionRemoveCount());
        }
    });

    /**
     * Global number of collections recreated
     */
    jpaHibernateRegistration.registerMetric(OPERATION_COLLECTION_RECREATED_COUNT, new AbstractMetricsHandler() {
        @Override
        void handle(final ModelNode response, final String name, Statistics stats, OperationContext context) {
            response.set(stats.getCollectionRecreateCount());
        }
    });

    /**
     * The number of transactions we know to have been successful
     */
    jpaHibernateRegistration.registerMetric(OPERATION_SUCCESSFUL_TRANSACTION_COUNT,
            new AbstractMetricsHandler() {
                @Override
                void handle(final ModelNode response, final String name, Statistics stats,
                        OperationContext context) {
                    response.set(stats.getSuccessfulTransactionCount());
                }
            });

    /**
     * The number of transactions we know to have completed
     */
    jpaHibernateRegistration.registerMetric(OPERATION_COMPLETED_TRANSACTION_COUNT,
            new AbstractMetricsHandler() {
                @Override
                void handle(final ModelNode response, final String name, Statistics stats,
                        OperationContext context) {
                    response.set(stats.getTransactionCount());
                }
            });

    /**
     * The number of prepared statements that were acquired
     */
    jpaHibernateRegistration.registerMetric(OPERATION_PREPARED_STATEMENT_COUNT, new AbstractMetricsHandler() {
        @Override
        void handle(final ModelNode response, final String name, Statistics stats, OperationContext context) {
            response.set(stats.getPrepareStatementCount());
        }
    });

    /**
     * The number of prepared statements that were released
     */
    jpaHibernateRegistration.registerMetric(OPERATION_CLOSE_STATEMENT_COUNT, new AbstractMetricsHandler() {
        @Override
        void handle(final ModelNode response, final String name, Statistics stats, OperationContext context) {
            response.set(stats.getCloseStatementCount());
        }
    });

    /**
     * The number of <tt>StaleObjectStateException</tt>s
     * that occurred
     */
    jpaHibernateRegistration.registerMetric(OPERATION_OPTIMISTIC_FAILURE_COUNT, new AbstractMetricsHandler() {
        @Override
        void handle(final ModelNode response, final String name, Statistics stats, OperationContext context) {
            response.set(stats.getOptimisticFailureCount());
        }
    });

    /**
     * enable/disable statistics attribute
     */
    // void registerReadWriteAttribute(String attributeName, OperationStepHandler readHandler, OperationStepHandler writeHandler, AttributeAccess.Storage storage);
    jpaHibernateRegistration.registerReadWriteAttribute(OPERATION_STATISTICS_ENABLED,
            new AbstractMetricsHandler() { // readHandler
                @Override
                void handle(final ModelNode response, final String name, Statistics stats,
                        OperationContext context) {
                    response.set(stats.isStatisticsEnabled());
                }
            }, StatisticsEnabledWriteHandler.INSTANCE, AttributeAccess.Storage.RUNTIME);

}

From source file:org.jboss.as.test.integration.jpa.secondlevelcache.SFSB2LC.java

License:Open Source License

/**
 * Check if disabling 2LC works as expected
 *///from  w w w .ja  v  a  2s  . c  o  m
public String disabled2LCCheck() {

    EntityManager em = emfNo2LC.createEntityManager();
    Statistics stats = em.unwrap(Session.class).getSessionFactory().getStatistics();
    stats.clear();

    try {
        // check if entities are NOT cached in 2LC
        String[] names = stats.getSecondLevelCacheRegionNames();
        assertEquals("There aren't any 2LC regions.", 0, names.length);

        createEmployee(em, "Martin", "Prague 132", 1);
        assertEquals("There aren't any puts in the 2LC.", 0, stats.getSecondLevelCachePutCount());

        // check if queries are NOT cached in 2LC
        Employee emp = getEmployeeQuery(em, 1);
        assertNotNull("Employee returned", emp);
        assertEquals("There aren't any query puts in the 2LC.", 0, stats.getQueryCachePutCount());

        // cleanup
        em.remove(emp);

    } catch (AssertionError e) {
        return e.getMessage();
    } finally {
        em.close();
    }
    return "OK";
}