Example usage for org.hibernate.stat SecondLevelCacheStatistics getPutCount

List of usage examples for org.hibernate.stat SecondLevelCacheStatistics getPutCount

Introduction

In this page you can find the example usage for org.hibernate.stat SecondLevelCacheStatistics getPutCount.

Prototype

long getPutCount();

Source Link

Document

The number of cache puts into the region since the last Statistics clearing

Usage

From source file:com.francetelecom.clara.cloud.scalability.helper.StatisticsHelper.java

License:Apache License

private static void secondLevelStats(Statistics stats, String name) {
    logger.info("Second level statistics for " + name);

    SecondLevelCacheStatistics slStats = stats.getSecondLevelCacheStatistics(name);

    logger.info("  Elements in memory : " + slStats.getElementCountInMemory());
    logger.info("  Element on disk : " + slStats.getElementCountOnDisk());
    logger.info("  Entries : " + slStats.getEntries());
    logger.info("  Hit count : " + slStats.getHitCount());
    logger.info("  Miss count : " + slStats.getMissCount());
    logger.info("  Put count : " + slStats.getPutCount());
    logger.info("  Memory size : " + slStats.getSizeInMemory());
}

From source file:com.hibernateinstrumentator.jboss.StatisticsService.java

License:Apache License

@Override
public Map<String, Object> getSecondLevelCacheStatisticsMap(String regionName) {

    Map<String, Object> m = null;
    SecondLevelCacheStatistics slcs = super.getSecondLevelCacheStatistics(regionName);
    if (slcs != null) {
        m = new HashMap<String, Object>();
        m.put("elementCountInMemory", slcs.getElementCountInMemory());
        m.put("elementCountOnDisk", slcs.getElementCountOnDisk());
        m.put("entries", slcs.getEntries());
        m.put("hitCount", slcs.getHitCount());
        m.put("missCount", slcs.getMissCount());
        m.put("putCount", slcs.getPutCount());
        m.put("sizeInMemory", slcs.getSizeInMemory());
    }/*  w w  w  . j av  a 2s  .c om*/

    return m;
}

From source file:com.openkm.servlet.admin.HibernateStatsServlet.java

License:Open Source License

/**
 * View log/*  w ww .  j a  va2s. c o  m*/
 */
private void view(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("view({}, {})", request, response);
    refresh();

    // Query Statistics
    List<Map<String, String>> qStats = new ArrayList<Map<String, String>>();
    for (String query : queryStatistics.keySet()) {
        QueryStatistics queryStats = queryStatistics.get(query);
        Map<String, String> stat = new HashMap<String, String>();
        stat.put("query", query);
        //stat.put("tquery", HibernateUtil.toSql(query));
        stat.put("executionCount", Long.toString(queryStats.getExecutionCount()));
        stat.put("executionRowCount", Long.toString(queryStats.getExecutionRowCount()));
        stat.put("executionMaxTime", Long.toString(queryStats.getExecutionMaxTime()));
        stat.put("executionMinTime", Long.toString(queryStats.getExecutionMinTime()));
        stat.put("executionAvgTime", Long.toString(queryStats.getExecutionAvgTime()));
        stat.put("executionTotalTime",
                Long.toString(queryStats.getExecutionAvgTime() * queryStats.getExecutionCount()));
        stat.put("cacheHitCount", Long.toString(queryStats.getCacheHitCount()));
        stat.put("cacheMissCount", Long.toString(queryStats.getCacheMissCount()));
        stat.put("cachePutCount", Long.toString(queryStats.getCachePutCount()));
        qStats.add(stat);
    }

    // Entity Statistics
    List<Map<String, String>> eStats = new ArrayList<Map<String, String>>();
    for (String entity : entityStatistics.keySet()) {
        EntityStatistics entityStats = entityStatistics.get(entity);
        Map<String, String> stat = new HashMap<String, String>();
        stat.put("entity", entity);
        stat.put("loadCount", Long.toString(entityStats.getLoadCount()));
        stat.put("fetchCount", Long.toString(entityStats.getFetchCount()));
        stat.put("insertCount", Long.toString(entityStats.getInsertCount()));
        stat.put("updateCount", Long.toString(entityStats.getUpdateCount()));
        stat.put("deleteCount", Long.toString(entityStats.getDeleteCount()));
        stat.put("optimisticFailureCount", Long.toString(entityStats.getOptimisticFailureCount()));
        eStats.add(stat);
    }

    // Collection Statistics
    List<Map<String, String>> cStats = new ArrayList<Map<String, String>>();
    for (String collection : collectionStatistics.keySet()) {
        CollectionStatistics collectionStats = collectionStatistics.get(collection);
        Map<String, String> stat = new HashMap<String, String>();
        stat.put("collection", collection);
        stat.put("loadCount", Long.toString(collectionStats.getLoadCount()));
        stat.put("fetchCount", Long.toString(collectionStats.getFetchCount()));
        stat.put("updateCount", Long.toString(collectionStats.getUpdateCount()));
        stat.put("recreateCount", Long.toString(collectionStats.getRecreateCount()));
        stat.put("removeCount", Long.toString(collectionStats.getRemoveCount()));
        cStats.add(stat);
    }

    // 2nd Level Cache Statistics
    long totalSizeInMemory = 0;
    List<Map<String, String>> slcStats = new ArrayList<Map<String, String>>();
    for (String cache : secondLevelCacheStatistics.keySet()) {
        SecondLevelCacheStatistics cacheStats = secondLevelCacheStatistics.get(cache);
        totalSizeInMemory += cacheStats.getSizeInMemory();
        Map<String, String> stat = new HashMap<String, String>();
        stat.put("cache", cache);
        stat.put("putCount", Long.toString(cacheStats.getPutCount()));
        stat.put("hitCount", Long.toString(cacheStats.getHitCount()));
        stat.put("missCount", Long.toString(cacheStats.getMissCount()));
        stat.put("elementCountInMemory", Long.toString(cacheStats.getElementCountInMemory()));
        stat.put("sizeInMemory", Long.toString(cacheStats.getSizeInMemory()));
        stat.put("elementCountOnDisk", Long.toString(cacheStats.getElementCountOnDisk()));
        slcStats.add(stat);
    }

    ServletContext sc = getServletContext();
    sc.setAttribute("generalStats", generalStatistics);
    sc.setAttribute("queryStats", qStats);
    sc.setAttribute("entityStats", eStats);
    sc.setAttribute("collectionStats", cStats);
    sc.setAttribute("secondLevelCacheStats", slcStats);
    sc.setAttribute("totalSizeInMemory", totalSizeInMemory);
    sc.setAttribute("statsEnabled", HibernateUtil.getSessionFactory().getStatistics().isStatisticsEnabled());
    sc.getRequestDispatcher("/admin/hibernate_stats.jsp").forward(request, response);

    // Activity log
    UserActivity.log(request.getRemoteUser(), "ADMIN_HIBERNATE_STATS", null, null, null);

    log.debug("view: void");
}

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

License:Open Source License

public void getValues(BuzzAnswer values) throws TypeHandlerException {
    for (String tmp : getMeasurableUnits()) {
        String name = tmp.split("" + SEPARATOR)[0];
        String region = tmp.split("" + SEPARATOR)[1];

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

        boolean debug = LOG.isDebugEnabled();

        Object o;/*from ww  w.ja v a2  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 for the SecondLevelCacheRegion
        SecondLevelCacheStatistics stats = sessionFactory.getStatistics().getSecondLevelCacheStatistics(region);
        LOG.debug("Got SecondLevelCacheStatistics for region: " + region + " " + stats);
        String measurementUnit = getMeasurementUnit();

        try {
            values.put(measurementUnit, name + SEPARATOR + region, "ElementCountInMemory",
                    stats.getElementCountInMemory());
            values.put(measurementUnit, name + SEPARATOR + region, "ElementCountOnDisk",
                    stats.getElementCountOnDisk());
            values.put(measurementUnit, name + SEPARATOR + region, "HitCount", stats.getHitCount());
            values.put(measurementUnit, name + SEPARATOR + region, "MissCount", stats.getMissCount());
            values.put(measurementUnit, name + SEPARATOR + region, "PutCount", stats.getPutCount());
            values.put(measurementUnit, name + SEPARATOR + region, "SizeInMemory", stats.getSizeInMemory());
        } catch (IncompatibleClassChangeError e) {
            // Newer versions of SecondLevelCacheStatistics is not an Object anymore. It's an interface
            // so we use Reflection in that case (otherwise we need to recompile Buzz for the specific
            // version if Hibernate.
            LOG.debug("SecondLevelCacheStatistics is an Interface. Using Reflection");

            Class<?> statsClass = stats.getClass();
            try {
                values.put(measurementUnit, name + SEPARATOR + region, "ElementCountInMemory",
                        statsClass.getMethod("getElementCountInMemory", (Class<?>) null)
                                .invoke(stats, (Object[]) null).toString());
                values.put(measurementUnit, name + SEPARATOR + region, "ElementCountOnDisk",
                        statsClass.getMethod("getElementCountOnDisk", (Class<?>) null)
                                .invoke(stats, (Object[]) null).toString());
                values.put(measurementUnit, name + SEPARATOR + region, "HitCount", statsClass
                        .getMethod("getHitCount", (Class<?>) null).invoke(stats, (Object[]) null).toString());
                values.put(measurementUnit, name + SEPARATOR + region, "MissCount", statsClass
                        .getMethod("getMissCount", (Class<?>) null).invoke(stats, (Object[]) null).toString());
                values.put(measurementUnit, name + SEPARATOR + region, "PutCount", statsClass
                        .getMethod("getPutCount", (Class<?>) null).invoke(stats, (Object[]) null).toString());
                values.put(measurementUnit, name + SEPARATOR + region, "SizeInMemory",
                        statsClass.getMethod("getSizeInMemory", (Class<?>) null).invoke(stats, (Object[]) null)
                                .toString());
            } catch (SecurityException ex) {
                throw new TypeHandlerException(ex);
            } catch (NoSuchMethodException ex) {
                throw new TypeHandlerException(ex);
            } catch (IllegalArgumentException ex) {
                throw new TypeHandlerException(ex);
            } catch (IllegalAccessException ex) {
                throw new TypeHandlerException(ex);
            } catch (InvocationTargetException ex) {
                throw new TypeHandlerException(ex);
            }
        }
    }
}

From source file:org.bedework.calcore.hibernate.DbStatistics.java

License:Apache License

private static void secondLevelStats(Collection<StatsEntry> c, Statistics dbStats, String name) {
    c.add(new StatsEntry("Second level statistics for " + name));

    SecondLevelCacheStatistics slStats = dbStats.getSecondLevelCacheStatistics(name);

    c.add(new StatsEntry("Elements in memory", slStats.getElementCountInMemory()));
    c.add(new StatsEntry("Element on disk", slStats.getElementCountOnDisk()));
    //c.add(new StatsEntry("Entries", slStats.getEntries()));
    c.add(new StatsEntry("Hit count", slStats.getHitCount()));
    c.add(new StatsEntry("Miss count", slStats.getMissCount()));
    c.add(new StatsEntry("Put count", slStats.getPutCount()));
    c.add(new StatsEntry("Memory size", slStats.getSizeInMemory()));
}

From source file:org.horizontaldb.shard.hibernate.AbstractDaoEnricher.java

License:Apache License

private void logSlcStats(Session session, String tenantId) {
    if (LOG.isTraceEnabled() && session != null) {
        Statistics statistics = session.getSessionFactory().getStatistics();

        if (statistics != null && statistics.isStatisticsEnabled()) {
            String[] regions = statistics.getSecondLevelCacheRegionNames();

            for (String region : regions) {
                SecondLevelCacheStatistics stat = statistics.getSecondLevelCacheStatistics(region);

                LOG.trace(String.format(
                        "secondLevelCacheStatistics.%s.%s=hits[%s], misses[%s], puts[%s], memCount[%s], memSize[%s], diskCount[%s]",
                        tenantId, region, stat.getHitCount(), stat.getMissCount(), stat.getPutCount(),
                        stat.getElementCountInMemory(), stat.getSizeInMemory(), stat.getElementCountOnDisk()));
            }//from  w w  w .  j  a v  a  2  s  .  c om
        }
    }
}

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

License:LGPL

@Test
public void testSingleUser() throws Exception {
    // setup//from w  ww .  j  a v a  2 s.  co m
    sessionFactory().getStatistics().clear();
    // wait a while to make sure that timestamp comparison works after invalidateRegion
    TIME_SERVICE.advance(1);

    Customer customer = createCustomer(0);
    final Integer customerId = customer.getId();
    getCustomerIDs().add(customerId);

    // wait a while to make sure that timestamp comparison works after collection remove (during insert)
    TIME_SERVICE.advance(1);

    assertNull("contact exists despite not being added", getFirstContact(customerId));

    // check that cache was hit
    SecondLevelCacheStatistics customerSlcs = sessionFactory().getStatistics()
            .getSecondLevelCacheStatistics(Customer.class.getName());
    assertEquals(1, customerSlcs.getPutCount());
    assertEquals(1, customerSlcs.getElementCountInMemory());
    assertEquals(1, TEST_SESSION_ACCESS.getRegion(sessionFactory(), Customer.class.getName())
            .getElementCountInMemory());

    log.infof("Add contact to customer {0}", customerId);
    String contactsRegionName = Customer.class.getName() + ".contacts";
    SecondLevelCacheStatistics contactsCollectionSlcs = sessionFactory().getStatistics()
            .getSecondLevelCacheStatistics(contactsRegionName);
    assertEquals(1, contactsCollectionSlcs.getPutCount());
    assertEquals(1, contactsCollectionSlcs.getElementCountInMemory());
    assertEquals(1,
            TEST_SESSION_ACCESS.getRegion(sessionFactory(), contactsRegionName).getElementCountInMemory());

    final Contact contact = addContact(customerId);
    assertNotNull("contact returned by addContact is null", contact);
    assertEquals("Customer.contacts cache was not invalidated after addContact", 0,
            contactsCollectionSlcs.getElementCountInMemory());

    assertNotNull("Contact missing after successful add call", getFirstContact(customerId));

    // read everyone's contacts
    readEveryonesFirstContact();

    removeContact(customerId);
    assertNull("contact still exists after successful remove call", getFirstContact(customerId));

}

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

License:LGPL

@Test
public void testQueryCacheInvalidation() throws Exception {
    Statistics stats = sessionFactory().getStatistics();
    stats.clear();/*from   w  w  w .  ja v  a 2s .c o m*/

    SecondLevelCacheStatistics slcs = stats.getSecondLevelCacheStatistics(Item.class.getName());
    sessionFactory().getCache().evictEntityRegion(Item.class.getName());

    TIME_SERVICE.advance(1);

    assertEquals(0, slcs.getPutCount());
    assertEquals(0, slcs.getElementCountInMemory());
    assertEquals(0, getNumberOfItems());

    ByRef<Long> idRef = new ByRef<>(null);
    withTxSession(s -> {
        Item item = new Item();
        item.setName("widget");
        item.setDescription("A really top-quality, full-featured widget.");
        s.persist(item);
        idRef.set(item.getId());
    });

    assertEquals(1, slcs.getPutCount());
    assertEquals(1, slcs.getElementCountInMemory());
    assertEquals(1, getNumberOfItems());

    withTxSession(s -> {
        Item item = s.get(Item.class, idRef.get());
        assertEquals(slcs.getHitCount(), 1);
        assertEquals(slcs.getMissCount(), 0);
        item.setDescription("A bog standard item");
    });

    assertEquals(slcs.getPutCount(), 2);

    CacheEntry entry = getEntry(Item.class.getName(), idRef.get());
    Serializable[] ser = entry.getDisassembledState();
    assertTrue(ser[0].equals("widget"));
    assertTrue(ser[1].equals("A bog standard item"));

    withTxSession(s -> {
        Item item = s.load(Item.class, idRef.get());
        s.delete(item);
    });
}

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

License:LGPL

@Test
public void testEntityCacheContentsAfterEvictAll() throws Exception {
    final List<Citizen> citizens = saveSomeCitizens();

    withTxSession(s -> {/* ww w .j  ava2 s  . co m*/
        Cache cache = s.getSessionFactory().getCache();

        Statistics stats = sessionFactory().getStatistics();
        SecondLevelCacheStatistics slcStats = stats.getSecondLevelCacheStatistics(Citizen.class.getName());

        assertTrue("2lc entity cache is expected to contain Citizen id = " + citizens.get(0).getId(),
                cache.containsEntity(Citizen.class, citizens.get(0).getId()));
        assertTrue("2lc entity cache is expected to contain Citizen id = " + citizens.get(1).getId(),
                cache.containsEntity(Citizen.class, citizens.get(1).getId()));
        assertEquals(2, slcStats.getPutCount());

        cache.evictEntityRegions();
        TIME_SERVICE.advance(1);

        assertEquals(0, slcStats.getElementCountInMemory());
        assertFalse("2lc entity cache is expected to not contain Citizen id = " + citizens.get(0).getId(),
                cache.containsEntity(Citizen.class, citizens.get(0).getId()));
        assertFalse("2lc entity cache is expected to not contain Citizen id = " + citizens.get(1).getId(),
                cache.containsEntity(Citizen.class, citizens.get(1).getId()));

        Citizen citizen = s.load(Citizen.class, citizens.get(0).getId());
        assertNotNull(citizen);
        assertNotNull(citizen.getFirstname()); // proxy gets resolved
        assertEquals(1, slcStats.getMissCount());

        // cleanup
        markRollbackOnly(s);
    });
}

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

License:LGPL

@Test
public void testSingleUser() throws Exception {
    // setup/*from   w  ww.ja  v  a 2 s  .c  o  m*/
    sessionFactory().getStatistics().clear();
    // wait a while to make sure that timestamp comparison works after invalidateRegion
    TIME_SERVICE.advance(1);

    Customer customer = createCustomer(0);
    final Integer customerId = customer.getId();
    getCustomerIDs().add(customerId);

    // wait a while to make sure that timestamp comparison works after collection remove (during insert)
    TIME_SERVICE.advance(1);

    assertNull("contact exists despite not being added", getFirstContact(customerId));

    // check that cache was hit
    SecondLevelCacheStatistics customerSlcs = sessionFactory().getStatistics()
            .getSecondLevelCacheStatistics(Customer.class.getName());
    assertEquals(1, customerSlcs.getPutCount());
    assertEquals(1, customerSlcs.getElementCountInMemory());
    assertEquals(1, customerSlcs.getEntries().size());

    log.infof("Add contact to customer {0}", customerId);
    SecondLevelCacheStatistics contactsCollectionSlcs = sessionFactory().getStatistics()
            .getSecondLevelCacheStatistics(Customer.class.getName() + ".contacts");
    assertEquals(1, contactsCollectionSlcs.getPutCount());
    assertEquals(1, contactsCollectionSlcs.getElementCountInMemory());
    assertEquals(1, contactsCollectionSlcs.getEntries().size());

    final Contact contact = addContact(customerId);
    assertNotNull("contact returned by addContact is null", contact);
    assertEquals("Customer.contacts cache was not invalidated after addContact", 0,
            contactsCollectionSlcs.getElementCountInMemory());

    assertNotNull("Contact missing after successful add call", getFirstContact(customerId));

    // read everyone's contacts
    readEveryonesFirstContact();

    removeContact(customerId);
    assertNull("contact still exists after successful remove call", getFirstContact(customerId));

}