From 5d6714658343d31860e54195cd8b872c418f4bb4 Mon Sep 17 00:00:00 2001 From: Martin Schreier Date: Mon, 3 Jan 2022 20:25:30 +0100 Subject: [PATCH] Switching to new ehcache version --- .../cache/factory/CacheCreator.java | 5 +- .../cache/factory/CacheFactory.java | 8 +- .../spring-cache-ehcache/pom.xml | 4 +- .../cache/ehcache/EhcacheCache.java | 368 ++++++++++-------- .../cache/ehcache/EhcacheCreator.java | 11 +- .../cache/ehcache/StatisticsRetrieval.java | 57 +++ .../src/test/resources/log4j2-test.xml | 2 +- .../test/resources/spring-context-disk.xml | 3 + .../src/test/resources/spring-context.xml | 10 + .../cache/hashmap/HashMapCacheCreator.java | 8 +- .../cache/test/AbstractCacheTestCase.java | 26 +- .../cache/test/examples/wine/Wine.java | 20 + 12 files changed, 334 insertions(+), 188 deletions(-) create mode 100644 spring-cache/spring-cache-providers/spring-cache-ehcache/src/main/java/org/apache/archiva/components/cache/ehcache/StatisticsRetrieval.java diff --git a/spring-cache/spring-cache-api/src/main/java/org/apache/archiva/components/cache/factory/CacheCreator.java b/spring-cache/spring-cache-api/src/main/java/org/apache/archiva/components/cache/factory/CacheCreator.java index bb55a5e..46aed46 100644 --- a/spring-cache/spring-cache-api/src/main/java/org/apache/archiva/components/cache/factory/CacheCreator.java +++ b/spring-cache/spring-cache-api/src/main/java/org/apache/archiva/components/cache/factory/CacheCreator.java @@ -27,8 +27,9 @@ * CacheCreator - an interface for CacheCreators * * @author Joakim Erdfelt + * @author Martin Schreier */ -public interface CacheCreator +public interface CacheCreator { /** * Create a Cache, initialize it, and return it. @@ -37,5 +38,5 @@ * @return the created cache. * @throws CacheException if there was a cache creation error. */ - public Cache createCache( CacheHints hints ) throws CacheException; + public Cache createCache( CacheHints hints, Class keyType, Class valueType ) throws CacheException; } diff --git a/spring-cache/spring-cache-api/src/main/java/org/apache/archiva/components/cache/factory/CacheFactory.java b/spring-cache/spring-cache-api/src/main/java/org/apache/archiva/components/cache/factory/CacheFactory.java index dbca1a0..119550f 100644 --- a/spring-cache/spring-cache-api/src/main/java/org/apache/archiva/components/cache/factory/CacheFactory.java +++ b/spring-cache/spring-cache-api/src/main/java/org/apache/archiva/components/cache/factory/CacheFactory.java @@ -114,7 +114,7 @@ public void setCacheCreatorFactory( CacheCreator creator ) CacheFactory.creator = creator; } - public Cache getCache( String id, CacheHints hints ) + public Cache getCache( String id, Class keyType, Class valueType, CacheHints hints ) throws CacheException { if ( creator == null ) @@ -124,7 +124,7 @@ public Cache getCache( String id, CacheHints hints ) if ( caches.containsKey( id ) ) { - return (Cache) caches.get( id ); + return (Cache) caches.get( id ); } if ( hints == null ) @@ -134,9 +134,9 @@ public Cache getCache( String id, CacheHints hints ) hints.setName( id ); } - Cache cache = CacheFactory.creator.createCache( hints ); + Cache cache = CacheFactory.creator.createCache( hints, keyType, valueType ); caches.put( id, cache ); - return (Cache) cache; + return cache; } } diff --git a/spring-cache/spring-cache-providers/spring-cache-ehcache/pom.xml b/spring-cache/spring-cache-providers/spring-cache-ehcache/pom.xml index d52c2e2..7b6a75a 100644 --- a/spring-cache/spring-cache-providers/spring-cache-ehcache/pom.xml +++ b/spring-cache/spring-cache-providers/spring-cache-ehcache/pom.xml @@ -40,9 +40,9 @@ - net.sf.ehcache + org.ehcache ehcache - 2.10.9.2 + 3.9.9 commons-logging diff --git a/spring-cache/spring-cache-providers/spring-cache-ehcache/src/main/java/org/apache/archiva/components/cache/ehcache/EhcacheCache.java b/spring-cache/spring-cache-providers/spring-cache-ehcache/src/main/java/org/apache/archiva/components/cache/ehcache/EhcacheCache.java index 4d6e014..4559cf9 100644 --- a/spring-cache/spring-cache-providers/spring-cache-ehcache/src/main/java/org/apache/archiva/components/cache/ehcache/EhcacheCache.java +++ b/spring-cache/spring-cache-providers/spring-cache-ehcache/src/main/java/org/apache/archiva/components/cache/ehcache/EhcacheCache.java @@ -19,19 +19,18 @@ * under the License. */ -import net.sf.ehcache.Cache; -import net.sf.ehcache.CacheManager; -import net.sf.ehcache.Element; -import net.sf.ehcache.Status; -import net.sf.ehcache.config.CacheConfiguration; -import net.sf.ehcache.config.Configuration; -import net.sf.ehcache.config.ConfigurationFactory; -import net.sf.ehcache.config.DiskStoreConfiguration; -import net.sf.ehcache.config.MemoryUnit; -import net.sf.ehcache.config.PersistenceConfiguration; -import net.sf.ehcache.statistics.StatisticsGateway; -import net.sf.ehcache.store.MemoryStoreEvictionPolicy; import org.apache.archiva.components.cache.CacheStatistics; +import org.ehcache.Cache; +import org.ehcache.PersistentCacheManager; +import org.ehcache.StateTransitionException; +import org.ehcache.Status; +import org.ehcache.config.builders.CacheConfigurationBuilder; +import org.ehcache.config.builders.CacheManagerBuilder; +import org.ehcache.config.builders.ExpiryPolicyBuilder; +import org.ehcache.config.builders.ResourcePoolsBuilder; +import org.ehcache.config.units.MemoryUnit; +import org.ehcache.core.spi.service.StatisticsService; +import org.ehcache.expiry.ExpiryPolicy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -41,6 +40,11 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.time.Duration; +import java.time.temporal.ChronoUnit; +import java.util.HashSet; +import java.util.Random; +import java.util.concurrent.ConcurrentHashMap; /** * EhcacheCache @@ -56,9 +60,18 @@ private static final String EHCACHE_DISK_STORE_PROPERTY = "org.apache.archiva.ehcache.diskStore"; - private Logger log = LoggerFactory.getLogger( EhcacheCache.class ); + private static final Logger log = LoggerFactory.getLogger( EhcacheCache.class ); - class Stats + private final Class keyType; + private final Class valueType; + + public EhcacheCache( Class keyType, Class valueType ) + { + this.keyType = keyType; + this.valueType = valueType; + } + + static class Stats implements CacheStatistics { private boolean useBaseLine = false; @@ -66,17 +79,25 @@ private long missCountBL = 0; private long sizeBL = 0; private long localHeapSizeInBytesBL = 0; + private final String cacheName; + private final StatisticsRetrieval svc; + + public Stats( StatisticsRetrieval svc, String cacheName ) + { + this.cacheName = cacheName; + this.svc = svc; + } // No API for cache clear since 2.10. We use a baseline, if the cache is cleared. @Override public void clear( ) { useBaseLine = true; - final StatisticsGateway cStats = ehcache.getStatistics( ); - hitCountBL = cStats.cacheHitCount( ); - missCountBL = cStats.cacheMissCount( ); - sizeBL = cStats.getSize( ); - localHeapSizeInBytesBL = cStats.getLocalHeapSizeInBytes( ); + org.ehcache.core.statistics.CacheStatistics cStats = getStats( ); + hitCountBL = cStats.getCacheHits( ); + missCountBL = cStats.getCacheMisses( ); + sizeBL = cStats.getTierStatistics( ).size( ); + localHeapSizeInBytesBL = cStats.getTierStatistics( ).get( "OnHeap" ).getAllocatedByteSize( ); } @Override @@ -93,31 +114,59 @@ public double getCacheHitRate( ) return hits / ( hits + miss ); } + private org.ehcache.core.statistics.CacheStatistics getStats( ) + { + return svc.getStatisticsService( ).getCacheStatistics( this.cacheName ); + } + @Override public long getCacheHits( ) { - return useBaseLine ? ehcache.getStatistics( ).cacheHitCount( ) - hitCountBL : ehcache.getStatistics( ).cacheHitCount( ); + long hits = getStats( ).getCacheHits( ); + return useBaseLine ? hits - hitCountBL : hits; } @Override public long getCacheMiss( ) { - return useBaseLine ? ehcache.getStatistics( ).cacheMissCount( ) - missCountBL : ehcache.getStatistics( ).cacheMissCount( ); + long misses = getStats( ).getCacheMisses( ); + return useBaseLine ? misses - missCountBL : misses; } @Override public long getSize( ) { - return useBaseLine ? ehcache.getStatistics( ).getSize( ) - sizeBL : ehcache.getStatistics( ).getSize( ); + long size = getStats( ).getTierStatistics( ).size( ); + return useBaseLine ? size - sizeBL : size; } @Override public long getInMemorySize( ) { - return useBaseLine ? ehcache.getStatistics( ).getLocalHeapSizeInBytes( ) - localHeapSizeInBytesBL : ehcache.getStatistics( ).getLocalHeapSizeInBytes( ); + long memSize = getStats( ).getTierStatistics( ).get( "OnHeap" ).getAllocatedByteSize( ); + return useBaseLine ? memSize - localHeapSizeInBytesBL : memSize; + } + + public StatisticsService getService( ) + { + return svc.getStatisticsService( ); } } + private static class ManagerData + { + final PersistentCacheManager cacheManager; + final StatisticsRetrieval statisticsRetrieval; + final HashSet cacheNames = new HashSet<>( ); + + ManagerData( PersistentCacheManager cacheManager, StatisticsRetrieval statisticsRetrieval ) + { + this.cacheManager = cacheManager; + this.statisticsRetrieval = statisticsRetrieval; + } + + } + /** * how often to run the disk store expiry thread. A large number of 120 seconds plus is recommended */ @@ -131,9 +180,9 @@ public long getInMemorySize( ) /** * Location on disk for the ehcache store. */ - private String diskStorePath = System.getProperties( ).containsKey( EHCACHE_DISK_STORE_PROPERTY ) ? + private Path diskStorePath = Paths.get( System.getProperties( ).containsKey( EHCACHE_DISK_STORE_PROPERTY ) ? System.getProperty( EHCACHE_DISK_STORE_PROPERTY ) : - System.getProperty( "java.io.tmpdir" ) + "/ehcache-archiva"; + System.getProperty( "java.io.tmpdir" ) + "/ehcache-archiva" ).toAbsolutePath( ); private boolean eternal = false; @@ -143,6 +192,9 @@ public long getInMemorySize( ) private String name = "cache"; + private String registeredName; + private Path registeredPath; + /** * Flag indicating when to use the disk store. */ @@ -178,20 +230,21 @@ public long getInMemorySize( ) private Path configurationFile = null; - private CacheManager cacheManager = null;//CacheManager.getInstance(); - - private net.sf.ehcache.Cache ehcache; + private Cache ehcache; private Stats stats; + private static final ConcurrentHashMap cacheManagerRefs = new ConcurrentHashMap<>( ); + + @Override public void clear( ) { - if (ehcache!=null) + if ( ehcache != null ) { - ehcache.removeAll( ); + ehcache.clear( ); } - if (stats!=null) + if ( stats != null ) { stats.clear( ); } @@ -205,119 +258,161 @@ public void initialize( ) { System.setProperty( "net.sf.ehcache.skipUpdateCheck", "true" ); } + this.registeredName = getName( ); + Path storePath = getDiskStorePath( ); + this.registeredPath = storePath; + ManagerData md = cacheManagerRefs.computeIfAbsent( this.registeredPath, ( key ) -> { + StatisticsRetrieval retrieval = new StatisticsRetrieval( ); + return new ManagerData( initCacheManager( retrieval, this.registeredPath ), retrieval ); + } ); + + this.stats = new Stats( md.statisticsRetrieval, this.registeredName ); - stats = new Stats( ); + final PersistentCacheManager cacheManager = md.cacheManager; - boolean cacheManagerExists = CacheManager.getCacheManager( getName( ) ) != null; + Cache cCache = cacheManager.getCache( registeredName, keyType, valueType ); - if ( cacheManagerExists ) + if ( cCache != null ) { if ( failOnDuplicateCache ) { - throw new RuntimeException( "A previous cacheManager with name [" + getName( ) + "] exists." ); + throw new RuntimeException( "A previous cache with name [" + registeredName + "] exists." ); } else { - log.warn( "skip duplicate cache {}", getName( ) ); - cacheManager = CacheManager.getCacheManager( getName( ) ); + log.warn( "skip duplicate cache {}", registeredName ); + this.ehcache = cCache; } } else { - Configuration configuration; - if ( configurationFile != null && Files.exists( configurationFile ) && Files.isReadable( configurationFile ) ) + int diskSize = getMaxElementsOnDisk( ) > 0 ? getMaxElementsOnDisk( ) : 100; + int memElements = getMaxElementsInMemory( ) > 0 ? getMaxElementsInMemory( ) : 1; + ResourcePoolsBuilder rpBuilder = ResourcePoolsBuilder + .heap( memElements ).disk( diskSize, MemoryUnit.MB, isDiskPersistent( ) ); + if ( isOverflowToOffHeap( ) ) { - configuration = ConfigurationFactory.parseConfiguration( configurationFile.toFile( ) ); + rpBuilder.offheap( getMaxBytesLocalOffHeap( ), MemoryUnit.B ); } - else - { - configuration = new Configuration( ); - } - Path diskStore = Paths.get( getDiskStorePath( ) ); - if (!Files.exists( diskStore )) - { - try - { - Files.createDirectories( diskStore ); - } - catch ( IOException e ) - { - log.error( "Could not create cache path " + e.getMessage( ) ); - } - } - this.cacheManager = new CacheManager( configuration.name( getName( ) ).diskStore( - new DiskStoreConfiguration( ).path( getDiskStorePath( ) ) ) ); + log.info( "Creating cache {}", registeredName ); + this.ehcache = cacheManager.createCache( this.registeredName, CacheConfigurationBuilder.newCacheConfigurationBuilder( keyType, valueType, rpBuilder ) + .withExpiry( getExpiry( ) ) + .build( ) ); + + md.cacheNames.add( this.registeredName ); } + } - boolean cacheExists = cacheManager.cacheExists( getName( ) ); + ExpiryPolicy getExpiry( ) + { + int ttl = getTimeToLiveSeconds( ); + int tti = getTimeToIdleSeconds( ); + if ( ttl <= 0 && tti <= 0 ) + { + return ExpiryPolicy.NO_EXPIRY; + } + if ( ttl <= 0 && tti > 0 ) + { + return ExpiryPolicyBuilder.timeToIdleExpiration( Duration.ofSeconds( tti ) ); + } + if ( ttl > 0 && tti <= 0 ) + { + return ExpiryPolicyBuilder.timeToLiveExpiration( Duration.ofSeconds( ttl ) ); + } + return ExpiryPolicyBuilder.expiry( ).create( Duration.ofSeconds( ttl ) ).access( Duration.ofSeconds( tti ) ).update( Duration.ofSeconds( tti ) ).build( ); + } + + private Duration getDurationFromSeconds( int seconds ) + { + return seconds <= 0 ? ChronoUnit.FOREVER.getDuration( ) : Duration.ofSeconds( seconds ); + } - if ( cacheExists ) + private synchronized PersistentCacheManager initCacheManager( StatisticsRetrieval svc, Path diskStorePath ) + { + log.info( "Initializing Cache Manager {}, {}", isStatisticsEnabled( ), diskStorePath ); + if ( !Files.exists( diskStorePath ) ) { - if ( failOnDuplicateCache ) + try { - throw new RuntimeException( "A previous cache with name [" + getName( ) + "] exists." ); + Files.createDirectories( diskStorePath ); } - else + catch ( IOException e ) { - log.warn( "skip duplicate cache {}", getName( ) ); - ehcache = cacheManager.getCache( getName( ) ); + log.error( "Could not create cache path: {}", e.getMessage( ) ); } } - else + + try { - CacheConfiguration cacheConfiguration = - new CacheConfiguration( ).name( getName( ) ).memoryStoreEvictionPolicy( - getMemoryStoreEvictionPolicy( ) ).eternal( isEternal( ) ).timeToLiveSeconds( - getTimeToLiveSeconds( ) ).timeToIdleSeconds( - getTimeToIdleSeconds( ) ).diskExpiryThreadIntervalSeconds( - getDiskExpiryThreadIntervalSeconds( ) ).overflowToOffHeap( - isOverflowToOffHeap( ) ).maxEntriesLocalDisk( getMaxElementsOnDisk( ) ); - - cacheConfiguration.addPersistence( new PersistenceConfiguration( ) ); - if ( isDiskPersistent( ) ) + CacheManagerBuilder builder = CacheManagerBuilder.newCacheManagerBuilder( ) + .with( CacheManagerBuilder.persistence( diskStorePath.toFile( ) ) ); + if ( isStatisticsEnabled( ) ) { - cacheConfiguration.getPersistenceConfiguration( ).setStrategy( PersistenceConfiguration.Strategy.LOCALTEMPSWAP.name( ) ); + builder = builder.using( svc ); } - else + return builder.build( true ); + } catch ( StateTransitionException ex ) { + // One try to use fallback path, if the cache exists already + Path fallBackPath = diskStorePath.getParent( ).resolve( diskStorePath.getFileName( ).toString( ) + "-" + ( new Random( ).nextLong( ) % 1000 ) ); + try { - cacheConfiguration.getPersistenceConfiguration( ).setStrategy( PersistenceConfiguration.Strategy.NONE.name( ) ); + Files.createDirectories( fallBackPath ); } - - if ( getMaxElementsInMemory( ) > 0 ) + catch ( IOException e ) { - cacheConfiguration = cacheConfiguration.maxEntriesLocalHeap( getMaxElementsInMemory( ) ); + log.error( "Could not create fallback cache path: {} ", e.getMessage( ) ); } - - if ( getMaxBytesLocalHeap( ) > 0 ) + CacheManagerBuilder builder = CacheManagerBuilder.newCacheManagerBuilder( ) + .with( CacheManagerBuilder.persistence( fallBackPath.toFile( ) ) ); + if ( isStatisticsEnabled( ) ) { - cacheConfiguration = cacheConfiguration.maxBytesLocalHeap( getMaxBytesLocalHeap( ), MemoryUnit.BYTES ); + builder = builder.using( svc ); } - if ( getMaxBytesLocalOffHeap( ) > 0 ) - { - cacheConfiguration = - cacheConfiguration.maxBytesLocalOffHeap( getMaxBytesLocalOffHeap( ), MemoryUnit.BYTES ); - } - - ehcache = new Cache( cacheConfiguration ); - cacheManager.addCache( ehcache ); + return builder.build( true ); } } @PreDestroy public void dispose( ) { - if ( this.cacheManager.getStatus( ).equals( Status.STATUS_ALIVE ) ) + ManagerData data = cacheManagerRefs.get( registeredPath ); + PersistentCacheManager cacheManager = data.cacheManager; + HashSet names = data.cacheNames; + if ( cacheManager != null && cacheManager.getStatus( ).equals( Status.AVAILABLE ) ) { - log.info( "Disposing cache: {}", ehcache ); + log.info( "Disposing cache: {}, {}", ehcache, registeredName ); if ( this.ehcache != null ) { try { - this.cacheManager.removeCache( this.ehcache.getName( ) ); - this.ehcache = null; - } catch (Throwable e) { + cacheManager.destroyCache( this.registeredName ); + + } + catch ( Throwable e ) + { log.error( "Cache removal failed: {}", e.getMessage( ), e ); } + finally + { + names.remove( this.registeredName ); + this.ehcache = null; + } + } + if ( names.size( ) == 0 ) + { + try + { + cacheManager.close( ); + cacheManager.destroy( ); + } + catch ( Throwable e ) + { + log.error( "Cache manager removal failed: {}", e.getMessage( ), e ); + } + finally + { + cacheManagerRefs.remove( registeredPath ); + } } } else @@ -326,7 +421,6 @@ public void dispose( ) } } - @SuppressWarnings( "unchecked" ) @Override public T get( V key ) { @@ -335,12 +429,7 @@ public T get( V key ) return null; } - Element elem = ehcache.get( key ); - if ( elem == null ) - { - return null; - } - return (T) elem.getObjectValue( ); + return ehcache.get( key ); } public long getDiskExpiryThreadIntervalSeconds( ) @@ -348,11 +437,16 @@ public long getDiskExpiryThreadIntervalSeconds( ) return diskExpiryThreadIntervalSeconds; } - public String getDiskStorePath( ) + public Path getDiskStorePath( ) { return diskStorePath; } + public void setDiskStorePath( Path path ) + { + this.diskStorePath = path.toAbsolutePath( ); + } + @Override public int getMaxElementsInMemory( ) { @@ -364,10 +458,6 @@ public String getMemoryEvictionPolicy( ) return memoryEvictionPolicy; } - public MemoryStoreEvictionPolicy getMemoryStoreEvictionPolicy( ) - { - return MemoryStoreEvictionPolicy.fromString( memoryEvictionPolicy ); - } public String getName( ) { @@ -395,7 +485,7 @@ public int getTimeToLiveSeconds( ) @Override public boolean hasKey( V key ) { - return ehcache.isKeyInCache( key ); + return ehcache.containsKey( key ); } public boolean isDiskPersistent( ) @@ -420,40 +510,25 @@ public boolean isOverflowToDisk( ) @Override public void register( V key, T value ) { - ehcache.put( new Element( key, value ) ); + ehcache.put( key, value ); } @Override - @SuppressWarnings( "unchecked" ) public T put( V key, T value ) { // Multiple steps done to satisfy Cache API requirement for Previous object return. - Element elem; - Object previous = null; - elem = ehcache.get( key ); - if ( elem != null ) - { - previous = elem.getObjectValue( ); - } - elem = new Element( key, value ); - ehcache.put( elem ); - return (T) previous; + T previous; + previous = ehcache.get( key ); + ehcache.put( key, value ); + return previous; } @Override - @SuppressWarnings( "unchecked" ) public T remove( V key ) { - Element elem; - Object previous = null; - elem = ehcache.get( key ); - if ( elem != null ) - { - previous = elem.getObjectValue( ); - ehcache.remove( key ); - } - - return (T) previous; + T previous = ehcache.get( key ); + ehcache.remove( key ); + return previous; } public void setDiskExpiryThreadIntervalSeconds( long diskExpiryThreadIntervalSeconds ) @@ -466,11 +541,6 @@ public void setDiskPersistent( boolean diskPersistent ) this.diskPersistent = diskPersistent; } - public void setDiskStorePath( String diskStorePath ) - { - this.diskStorePath = diskStorePath; - } - public void setEternal( boolean eternal ) { this.eternal = eternal; @@ -481,11 +551,6 @@ public void setEternal( boolean eternal ) public void setMaxElementsInMemory( int maxElementsInMemory ) { this.maxElementsInMemory = maxElementsInMemory; - if ( this.ehcache != null ) - { - this.ehcache.getCacheConfiguration( ).setMaxEntriesLocalHeap( this.maxElementsInMemory ); - - } } public void setMemoryEvictionPolicy( String memoryEvictionPolicy ) @@ -510,20 +575,12 @@ public void setOverflowToDisk( boolean overflowToDisk ) @Override public void setTimeToIdleSeconds( int timeToIdleSeconds ) { - if ( this.ehcache != null ) - { - this.ehcache.getCacheConfiguration( ).setTimeToIdleSeconds( timeToIdleSeconds ); - } this.timeToIdleSeconds = timeToIdleSeconds; } @Override public void setTimeToLiveSeconds( int timeToLiveSeconds ) { - if ( this.ehcache != null ) - { - this.ehcache.getCacheConfiguration( ).setTimeToLiveSeconds( timeToIdleSeconds ); - } this.timeToLiveSeconds = timeToLiveSeconds; } @@ -534,7 +591,7 @@ public boolean isStatisticsEnabled( ) public void setStatisticsEnabled( boolean statisticsEnabled ) { - this.statisticsEnabled = statisticsEnabled; + // ignored for ehache } public boolean isFailOnDuplicateCache( ) @@ -587,11 +644,6 @@ public int getMaxElementsOnDisk( ) public void setMaxElementsOnDisk( int maxElementsOnDisk ) { this.maxElementsOnDisk = maxElementsOnDisk; - if ( this.ehcache != null ) - { - this.ehcache.getCacheConfiguration( ).setMaxEntriesInCache( this.maxElementsOnDisk ); - this.ehcache.getCacheConfiguration( ).maxEntriesLocalDisk( this.maxElementsOnDisk ); - } } /** diff --git a/spring-cache/spring-cache-providers/spring-cache-ehcache/src/main/java/org/apache/archiva/components/cache/ehcache/EhcacheCreator.java b/spring-cache/spring-cache-providers/spring-cache-ehcache/src/main/java/org/apache/archiva/components/cache/ehcache/EhcacheCreator.java index af521a9..e80788e 100644 --- a/spring-cache/spring-cache-providers/spring-cache-ehcache/src/main/java/org/apache/archiva/components/cache/ehcache/EhcacheCreator.java +++ b/spring-cache/spring-cache-providers/spring-cache-ehcache/src/main/java/org/apache/archiva/components/cache/ehcache/EhcacheCreator.java @@ -32,16 +32,17 @@ * EhcacheCreator - runtime creation of an ehcache. * * @author Joakim Erdfelt + * @author Martin Schreier */ -public class EhcacheCreator - implements CacheCreator +public class EhcacheCreator + implements CacheCreator { @Override - public Cache createCache( CacheHints hints ) + public Cache createCache( CacheHints hints, Class keyType, Class valueType ) throws CacheException { - EhcacheCache cache = new EhcacheCache( ); + EhcacheCache cache = new EhcacheCache( keyType, valueType ); cache.setName( hints.getName( ) ); @@ -66,7 +67,7 @@ public Cache createCache( CacheHints hints ) } } - cache.setDiskStorePath( overflowPath.toAbsolutePath( ).toString( ) ); + cache.setDiskStorePath( overflowPath ); } cache.setMaxElementsInMemory( hints.getMaxElements( ) ); diff --git a/spring-cache/spring-cache-providers/spring-cache-ehcache/src/main/java/org/apache/archiva/components/cache/ehcache/StatisticsRetrieval.java b/spring-cache/spring-cache-providers/spring-cache-ehcache/src/main/java/org/apache/archiva/components/cache/ehcache/StatisticsRetrieval.java new file mode 100644 index 0000000..cef9059 --- /dev/null +++ b/spring-cache/spring-cache-providers/spring-cache-ehcache/src/main/java/org/apache/archiva/components/cache/ehcache/StatisticsRetrieval.java @@ -0,0 +1,57 @@ +package org.apache.archiva.components.cache.ehcache; +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + + +import org.ehcache.core.spi.service.StatisticsService; +import org.ehcache.spi.service.Service; +import org.ehcache.spi.service.ServiceDependencies; +import org.ehcache.spi.service.ServiceProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import static java.util.Objects.requireNonNull; + +/** + * + * EhCache Service class that retrieves the Statistics instance. + * + * @author Martin Schreier + */ +@ServiceDependencies( StatisticsService.class ) +public class StatisticsRetrieval implements Service +{ + private static final Logger log = LoggerFactory.getLogger( StatisticsRetrieval.class ); + + private StatisticsService statisticsService; + + @Override + public void start( ServiceProvider serviceProvider) { + log.info( "Starting Statistics Retrieval" ); + this.statisticsService = serviceProvider.getService(StatisticsService.class); + } + + @Override + public void stop() { + this.statisticsService = null; + } + + public StatisticsService getStatisticsService() { + return requireNonNull(statisticsService); + } +} diff --git a/spring-cache/spring-cache-providers/spring-cache-ehcache/src/test/resources/log4j2-test.xml b/spring-cache/spring-cache-providers/spring-cache-ehcache/src/test/resources/log4j2-test.xml index ab778b6..3c0b979 100644 --- a/spring-cache/spring-cache-providers/spring-cache-ehcache/src/test/resources/log4j2-test.xml +++ b/spring-cache/spring-cache-providers/spring-cache-ehcache/src/test/resources/log4j2-test.xml @@ -25,7 +25,7 @@ - + diff --git a/spring-cache/spring-cache-providers/spring-cache-ehcache/src/test/resources/spring-context-disk.xml b/spring-cache/spring-cache-providers/spring-cache-ehcache/src/test/resources/spring-context-disk.xml index ecd9d17..012ae5f 100644 --- a/spring-cache/spring-cache-providers/spring-cache-ehcache/src/test/resources/spring-context-disk.xml +++ b/spring-cache/spring-cache-providers/spring-cache-ehcache/src/test/resources/spring-context-disk.xml @@ -25,6 +25,9 @@ + + + diff --git a/spring-cache/spring-cache-providers/spring-cache-ehcache/src/test/resources/spring-context.xml b/spring-cache/spring-cache-providers/spring-cache-ehcache/src/test/resources/spring-context.xml index 688d09d..7e732f5 100644 --- a/spring-cache/spring-cache-providers/spring-cache-ehcache/src/test/resources/spring-context.xml +++ b/spring-cache/spring-cache-providers/spring-cache-ehcache/src/test/resources/spring-context.xml @@ -25,6 +25,8 @@ + + @@ -38,6 +40,8 @@ + + @@ -51,6 +55,8 @@ + + @@ -64,6 +70,8 @@ + + @@ -77,6 +85,8 @@ + + diff --git a/spring-cache/spring-cache-providers/spring-cache-hashmap/src/main/java/org/apache/archiva/components/cache/hashmap/HashMapCacheCreator.java b/spring-cache/spring-cache-providers/spring-cache-hashmap/src/main/java/org/apache/archiva/components/cache/hashmap/HashMapCacheCreator.java index 031e85b..4a2df3e 100644 --- a/spring-cache/spring-cache-providers/spring-cache-hashmap/src/main/java/org/apache/archiva/components/cache/hashmap/HashMapCacheCreator.java +++ b/spring-cache/spring-cache-providers/spring-cache-hashmap/src/main/java/org/apache/archiva/components/cache/hashmap/HashMapCacheCreator.java @@ -29,15 +29,15 @@ * * @author Joakim Erdfelt */ -public class HashMapCacheCreator - implements CacheCreator +public class HashMapCacheCreator + implements CacheCreator { - public Cache createCache( CacheHints cacheHint ) + public Cache createCache( CacheHints cacheHint, Class keyType, Class valueType ) throws CacheException { // Supports NO CacheHints. - HashMapCache cache = new HashMapCache( ); + HashMapCache cache = new HashMapCache<>( ); cache.initialize( ); diff --git a/spring-cache/spring-cache-test/src/main/java/org/apache/archiva/components/cache/test/AbstractCacheTestCase.java b/spring-cache/spring-cache-test/src/main/java/org/apache/archiva/components/cache/test/AbstractCacheTestCase.java index 379e5d6..f096897 100644 --- a/spring-cache/spring-cache-test/src/main/java/org/apache/archiva/components/cache/test/AbstractCacheTestCase.java +++ b/spring-cache/spring-cache-test/src/main/java/org/apache/archiva/components/cache/test/AbstractCacheTestCase.java @@ -28,15 +28,14 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.ArrayList; import java.util.Iterator; import java.util.List; -import java.util.logging.ConsoleHandler; -import java.util.logging.Level; -import java.util.logging.Logger; /** * AbstractCacheTestCase @@ -48,14 +47,16 @@ public abstract class AbstractCacheTestCase extends TestCase { - static - { - Logger logger = Logger.getLogger( "org.codehaus.plexus.cache" ); - logger.setLevel( Level.ALL ); - ConsoleHandler handler = new ConsoleHandler( ); - handler.setLevel( Level.ALL ); - logger.addHandler( handler ); - } +// static +// { +// Logger logger = Logger.getLogger( "org.codehaus.plexus.cache" ); +// logger.setLevel( Level.ALL ); +// ConsoleHandler handler = new ConsoleHandler( ); +// handler.setLevel( Level.ALL ); +// logger.addHandler( handler ); +// } + + private static final Logger log = LoggerFactory.getLogger( AbstractCacheTestCase.class ); protected Cache cache; @@ -85,6 +86,7 @@ public void testSimplePutGet( ) @Test public void testLargePutGet( ) { + log.info( "Starting test testLargePutGet" ); EnglishNumberFormat fmt = new EnglishNumberFormat( ); for ( int i = 4500; i <= 5000; i++ ) @@ -229,7 +231,7 @@ public void testTwoSecondRefresh( ) @Test public void testCacheFactory( ) throws CacheException { - Cache cache = CacheFactory.getInstance( ).getCache( "foo-factory-test", null ); + Cache cache = CacheFactory.getInstance( ).getCache( "foo-factory-test", String.class, Integer.class,null ); // This test is only here to ensure that the provider implements a Creator class. assertNotNull( "Cache should not be null", cache ); diff --git a/spring-cache/spring-cache-test/src/main/java/org/apache/archiva/components/cache/test/examples/wine/Wine.java b/spring-cache/spring-cache-test/src/main/java/org/apache/archiva/components/cache/test/examples/wine/Wine.java index 130ae6f..1f854f4 100644 --- a/spring-cache/spring-cache-test/src/main/java/org/apache/archiva/components/cache/test/examples/wine/Wine.java +++ b/spring-cache/spring-cache-test/src/main/java/org/apache/archiva/components/cache/test/examples/wine/Wine.java @@ -67,4 +67,24 @@ public String toString( ) sb.append( '}' ); return sb.toString( ); } + + @Override + public boolean equals( Object o ) + { + if ( this == o ) return true; + if ( o == null || getClass( ) != o.getClass( ) ) return false; + + Wine wine = (Wine) o; + + if ( name != null ? !name.equals( wine.name ) : wine.name != null ) return false; + return localisation != null ? localisation.equals( wine.localisation ) : wine.localisation == null; + } + + @Override + public int hashCode( ) + { + int result = name != null ? name.hashCode( ) : 0; + result = 31 * result + ( localisation != null ? localisation.hashCode( ) : 0 ); + return result; + } }