List of usage examples for org.hibernate SessionFactory getStatistics
Statistics getStatistics();
From source file:net.firejack.platform.processor.statistics.StatisticsProcessor.java
License:Apache License
@Scheduled(cron = "0 0/5 * * * *") public void schedulerStatisticsHandler() { if (templates != null) { for (HibernateTemplate template : templates) { SessionFactory sessionFactory = template.getSessionFactory(); Statistics statistics = sessionFactory.getStatistics(); if (statistics.isStatisticsEnabled()) { LogTransaction logTransaction = new LogTransaction(); logTransaction.setPackageLookup(OpenFlameSecurityConstants.getPackageLookup()); logTransaction.setTransactions(statistics.getSuccessfulTransactionCount()); logTransaction.setEntitiesLoaded(statistics.getEntityLoadCount()); logTransaction.setEntitiesInserted(statistics.getEntityInsertCount()); logTransaction.setEntitiesUpdated(statistics.getEntityUpdateCount()); logTransaction.setEntitiesDeleted(statistics.getEntityDeleteCount()); logTransaction.setEntitiesFetched(statistics.getEntityFetchCount()); logTransaction.setCollectionsLoaded(statistics.getCollectionLoadCount()); logTransaction.setCollectionsRecreated(statistics.getCollectionRecreateCount()); logTransaction.setCollectionsUpdated(statistics.getCollectionUpdateCount()); logTransaction.setCollectionsRemoved(statistics.getCollectionRemoveCount()); logTransaction.setCollectionsFetched(statistics.getCollectionFetchCount()); logTransaction.setMaxQueryTime(statistics.getQueryExecutionMaxTime()); Date hourlyDate = new Date(); logTransaction.setHourPeriod(DateUtils.truncate(hourlyDate, Calendar.HOUR).getTime()); logTransaction.setDayPeriod(DateUtils.truncate(hourlyDate, Calendar.DAY_OF_MONTH).getTime()); logTransaction.setWeekPeriod(DateUtils.truncateDateToWeek(hourlyDate).getTime()); logTransaction.setMonthPeriod(DateUtils.truncate(hourlyDate, Calendar.MONTH).getTime()); OPFEngine.StatisticsService.saveLogTransaction(logTransaction); statistics.clear();//ww w.jav a 2 s .c o m } else { logger.warn("Hibernate Statistics is disabled."); } } } }
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;/* w ww.j a va 2s. c om*/ 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:net.welen.buzz.typehandler.impl.hibernate.HibernateSecondLevelStatisticsUnitHandler.java
License:Open Source License
/** * Loops through the whole JNDI tree to find all Hibernate Session Factories and EJB3 EntityMangers * and get all their SecondLevelCacheRegions * /* ww w. j a va 2 s .co m*/ * @param jndiName * @return * @throws TypeHandlerException */ private List<String> searchJNDI(String jndiName) throws TypeHandlerException { ArrayList<String> answer = new ArrayList<String>(); boolean debug = LOG.isDebugEnabled(); try { NamingEnumeration<NameClassPair> jndiContent = new InitialContext().list(jndiName); while (jndiContent.hasMore()) { NameClassPair node = jndiContent.nextElement(); if (debug) { LOG.debug("Checking class: " + node.getClassName()); } if (node.getClassName().equals("org.jnp.interfaces.NamingContext")) { answer.addAll(searchJNDI(jndiName + "/" + node.getName())); } String className = node.getClassName(); if (className.equals("org.hibernate.impl.SessionFactoryImpl") // Hibernate || className.equals("org.jboss.ejb3.entity.InjectedEntityManagerFactory") // JBoss 4.2.3 || className.equals("org.jboss.jpa.injection.InjectedEntityManagerFactory") // JBoss 5,1 6,1 || className.equals("org.hibernate.ejb.EntityManagerFactoryImpl") // JBoss 7 ) { if (debug) { LOG.debug("Hibernate sessionfactory found: " + node.getName()); } // Add all second level regions? SessionFactory sessionFactory; Object o; try { o = new InitialContext().lookup(node.getName()); } catch (NamingException e) { throw new TypeHandlerException(e); } if (o.getClass().getName().equals("org.hibernate.ejb.EntityManagerFactoryImpl")) { // Hibernate 4 sessionFactory = ((EntityManagerFactoryImpl) o).getSessionFactory(); } else { // Hibernate 3 sessionFactory = (SessionFactory) o; } String regions[] = sessionFactory.getStatistics().getSecondLevelCacheRegionNames(); for (int i = 0; i < regions.length; i++) { if (debug) { LOG.debug("Found second level cache region: " + regions[i]); } answer.add(jndiName + "/" + node.getName() + SEPARATOR + regions[i]); } } } return answer; } catch (NamingException e) { throw new TypeHandlerException(e); } }
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 v a 2 s . com*/ 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.apache.ignite.cache.hibernate.GridHibernateL2CacheSelfTest.java
License:Apache License
/** * @param sesFactory Session factory./*from w w w. ja v a2 s .co m*/ * @param nameToId Name-ID mapping. * @param absentNames Absent entities' names. */ private void assertNaturalIdCache(SessionFactory sesFactory, Map<String, Integer> nameToId, String... absentNames) { sesFactory.getStatistics().clear(); NaturalIdCacheStatistics stats = sesFactory.getStatistics().getNaturalIdCacheStatistics(NATURAL_ID_REGION); long hitBefore = stats.getHitCount(); long missBefore = stats.getMissCount(); final Session ses = sesFactory.openSession(); try { for (Map.Entry<String, Integer> e : nameToId.entrySet()) assertEquals((int) e.getValue(), ((Entity) ses.bySimpleNaturalId(Entity.class).load(e.getKey())).getId()); for (String name : absentNames) assertNull((ses.bySimpleNaturalId(Entity.class).load(name))); assertEquals(nameToId.size() + hitBefore, stats.getHitCount()); assertEquals(absentNames.length + missBefore, stats.getMissCount()); } finally { ses.close(); } }
From source file:org.apache.ignite.cache.hibernate.GridHibernateL2CacheSelfTest.java
License:Apache License
/** * @param sesFactory Session factory./*www . j av a 2s . co m*/ * @param idToChildCnt Number of children per entity. * @param expHit Expected cache hits. * @param expMiss Expected cache misses. */ @SuppressWarnings("unchecked") private void assertCollectionCache(SessionFactory sesFactory, Map<Integer, Integer> idToChildCnt, int expHit, int expMiss) { sesFactory.getStatistics().clear(); Session ses = sesFactory.openSession(); try { for (Map.Entry<Integer, Integer> e : idToChildCnt.entrySet()) { Entity entity = (Entity) ses.load(Entity.class, e.getKey()); assertEquals((int) e.getValue(), entity.getChildren().size()); } } finally { ses.close(); } SecondLevelCacheStatistics stats = sesFactory.getStatistics() .getSecondLevelCacheStatistics(CHILD_COLLECTION_REGION); assertEquals(expHit, stats.getHitCount()); assertEquals(expMiss, stats.getMissCount()); }
From source file:org.apache.ignite.cache.hibernate.GridHibernateL2CacheSelfTest.java
License:Apache License
/** * @param entityName Entity name./* ww w. j a v a 2s . com*/ * @param sesFactory Session factory. * @param idToName ID to name mapping. * @param absentIds Absent entities' IDs. */ private void assertEntityCache(String entityName, SessionFactory sesFactory, Map<Integer, String> idToName, Integer... absentIds) { assert entityName.equals(ENTITY_NAME) || entityName.equals(ENTITY2_NAME) : entityName; sesFactory.getStatistics().clear(); final Session ses = sesFactory.openSession(); final boolean entity1 = entityName.equals(ENTITY_NAME); try { if (entity1) { for (Map.Entry<Integer, String> e : idToName.entrySet()) assertEquals(e.getValue(), ((Entity) ses.load(Entity.class, e.getKey())).getName()); } else { for (Map.Entry<Integer, String> e : idToName.entrySet()) assertEquals(e.getValue(), ((Entity2) ses.load(Entity2.class, e.getKey())).getName()); } for (final int id : absentIds) { GridTestUtils.assertThrows(log, new Callable<Void>() { @Override public Void call() throws Exception { if (entity1) ((Entity) ses.load(Entity.class, id)).getName(); else ((Entity2) ses.load(Entity2.class, id)).getName(); return null; } }, ObjectNotFoundException.class, null); } SecondLevelCacheStatistics stats = sesFactory.getStatistics().getSecondLevelCacheStatistics(entityName); assertEquals(idToName.size(), stats.getHitCount()); assertEquals(absentIds.length, stats.getMissCount()); } finally { ses.close(); } }
From source file:org.apache.ignite.examples.datagrid.hibernate.HibernateL2CacheExample.java
License:Apache License
/** * Prints Hibernate L2 cache statistics to standard output. * * @param sesFactory Hibernate {@link SessionFactory}, for which to print * statistics./* w ww.j a v a 2s.c o m*/ */ private static void printStats(SessionFactory sesFactory) { System.out.println("=== Hibernate L2 cache statistics ==="); for (String entityName : ENTITY_NAMES) { System.out.println("\tEntity: " + entityName); SecondLevelCacheStatistics stats = sesFactory.getStatistics().getSecondLevelCacheStatistics(entityName); System.out.println("\t\tL2 cache entries: " + stats.getEntries()); System.out.println("\t\tHits: " + stats.getHitCount()); System.out.println("\t\tMisses: " + stats.getMissCount()); } System.out.println("====================================="); }
From source file:org.apache.karaf.jpa.hibernate.impl.StatisticsPublisher.java
License:Apache License
private void publishStatistics(ServiceReference<EntityManagerFactory> reference, EntityManagerFactory emf) { String persitenceProvider = (String) reference.getProperty("osgi.unit.provider"); if (!"org.hibernate.ejb.HibernatePersistence".equals(persitenceProvider)) { return;//from ww w .ja va 2s . co m } if (reference.getProperty("org.apache.aries.jpa.proxy.factory") != null) { return; } try { EntityManager em = emf.createEntityManager(); SessionFactory sessionFactory = em.unwrap(Session.class).getSessionFactory(); final Statistics statistics = sessionFactory.getStatistics(); statistics.setStatisticsEnabled(true); mbeanServer.registerMBean(getStatisticsMBean(statistics), getOName(reference)); } catch (Exception e) { LOG.warn("Error publishing StatisticsMXBean" + e.getMessage(), e); } }
From source file:org.bonitasoft.engine.persistence.AbstractHibernatePersistenceService.java
License:Open Source License
/** * @param sessionFactory/*from w w w . j a v a2s . c om*/ * @param classMapping * @param classAliasMappings * @param enableWordSearch * @param wordSearchExclusionMappings * @param logger * @throws ClassNotFoundException */ protected AbstractHibernatePersistenceService(final SessionFactory sessionFactory, final List<Class<? extends PersistentObject>> classMapping, final Map<String, String> classAliasMappings, final boolean enableWordSearch, final Set<String> wordSearchExclusionMappings, final TechnicalLoggerService logger) throws ClassNotFoundException { super("TEST", "#", enableWordSearch, wordSearchExclusionMappings, logger); this.sessionFactory = sessionFactory; this.classAliasMappings = classAliasMappings; this.classMapping = classMapping; orderByCheckingMode = getOrderByCheckingMode(); statistics = sessionFactory.getStatistics(); cacheQueries = Collections.emptyMap(); interfaceToClassMapping = Collections.emptyMap(); mappingExclusions = Collections.emptyList(); }