This is an automated email from the ASF dual-hosted git repository. asf-gitbox-commits pushed a commit to branch master in repository https://gitbox.apache.org/repos/asf/commons-jcs.git
commit dd59fcff7ebd91e634b3ee27dc0d6ff6a39da91c Author: Thomas Vandahl <[email protected]> AuthorDate: Tue Oct 6 21:20:57 2026 +0200 Adapt sandbox filecache to jcs4 --- .../jcs/auxiliary/disk/file/FileDiskCache.java | 200 +++++++-------------- .../auxiliary/disk/file/FileDiskCacheFactory.java | 83 +++++---- .../auxiliary/disk/file/FileDiskCacheManager.java | 147 --------------- .../disk/file/FileDiskCacheFactoryUnitTest.java | 20 ++- .../auxiliary/disk/file/FileDiskCacheUnitTest.java | 66 +++---- 5 files changed, 163 insertions(+), 353 deletions(-) diff --git a/commons-jcs4-sandbox/commons-jcs4-filecache/src/main/java/org/apache/commons/jcs/auxiliary/disk/file/FileDiskCache.java b/commons-jcs4-sandbox/commons-jcs4-filecache/src/main/java/org/apache/commons/jcs/auxiliary/disk/file/FileDiskCache.java index 3ccbb530..58a1f507 100644 --- a/commons-jcs4-sandbox/commons-jcs4-filecache/src/main/java/org/apache/commons/jcs/auxiliary/disk/file/FileDiskCache.java +++ b/commons-jcs4-sandbox/commons-jcs4-filecache/src/main/java/org/apache/commons/jcs/auxiliary/disk/file/FileDiskCache.java @@ -1,21 +1,7 @@ -/* - * 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 - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ package org.apache.commons.jcs.auxiliary.disk.file; + /* + * 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 @@ -38,19 +24,16 @@ import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; import java.util.Map; import java.util.Set; -import org.apache.commons.jcs4.auxiliary.AuxiliaryCacheAttributes; import org.apache.commons.jcs4.auxiliary.disk.AbstractDiskCache; import org.apache.commons.jcs4.engine.behavior.ICacheElement; import org.apache.commons.jcs4.engine.behavior.IElementSerializer; import org.apache.commons.jcs4.engine.logging.behavior.ICacheEvent; -import org.apache.commons.jcs4.engine.logging.behavior.ICacheEventLogger; +import org.apache.commons.jcs4.engine.logging.behavior.ICacheEventLogger.CacheEventType; import org.apache.commons.jcs4.log.Log; -import org.apache.commons.jcs4.log.LogFactory; +import org.apache.commons.jcs4.utils.serialization.StandardSerializer; /** * This disk cache writes each item to a separate file. This is for regions with very few items, @@ -63,14 +46,11 @@ public class FileDiskCache<K, V> extends AbstractDiskCache<K, V> { /** The logger. */ - private static final Log log = LogFactory.getLog( FileDiskCache.class ); + private static final Log log = Log.getLog( FileDiskCache.class ); /** The name to prefix all log messages with. */ private final String logCacheName; - /** The config values. */ - private final FileDiskCacheAttributes diskFileCacheAttributes; - /** The directory where the files are stored */ private File directory; @@ -81,7 +61,7 @@ public class FileDiskCache<K, V> */ public FileDiskCache( final FileDiskCacheAttributes cacheAttributes ) { - this( cacheAttributes, null ); + this( cacheAttributes, new StandardSerializer() ); } /** @@ -95,7 +75,6 @@ public class FileDiskCache<K, V> { super( cattr ); setElementSerializer( elementSerializer ); - this.diskFileCacheAttributes = cattr; this.logCacheName = "Region [" + getCacheName() + "] "; setAlive(initializeFileSystem( cattr )); } @@ -113,15 +92,16 @@ public class FileDiskCache<K, V> final boolean createdDirectories = getDirectory().mkdirs(); if ( log.isInfoEnabled() ) { - log.info( logCacheName + "Cache file root directory: " + getDirectory() ); - log.info( logCacheName + "Created root directory: " + createdDirectories ); + log.info("{0}: Cache file root directory: {1}", logCacheName, getDirectory() ); + log.info("{0}: Created root directory: {1}", logCacheName, createdDirectories ); } // TODO consider throwing. final boolean exists = getDirectory().exists(); if ( !exists ) { - log.error( "Could not initialize File Disk Cache. The root directory does not exist." ); + log.error("{0}: Could not initialize File Disk Cache. The root directory {1} does not exist.", + logCacheName, getDirectory()); } return exists; } @@ -155,7 +135,7 @@ public class FileDiskCache<K, V> if ( log.isDebugEnabled() ) { - log.debug( logCacheName + "Creating file for name: [" + fileName + "] based on key: [" + key + "]" ); + log.debug("{0}: Creating file for name: [{1}] based on key: [{2}]", logCacheName, fileName, key); } return new File( getDirectory().getAbsolutePath(), fileName ); @@ -189,18 +169,9 @@ public class FileDiskCache<K, V> * @return AuxiliaryCacheAttributes */ @Override - public AuxiliaryCacheAttributes getAuxiliaryCacheAttributes() - { - return diskFileCacheAttributes; - } - - /** - * @return String the path to the directory - */ - @Override - protected String getDiskLocation() + public FileDiskCacheAttributes getAuxiliaryCacheAttributes() { - return getDirectory().getAbsolutePath(); + return (FileDiskCacheAttributes) super.getAuxiliaryCacheAttributes(); } /** @@ -212,12 +183,13 @@ public class FileDiskCache<K, V> protected synchronized void processDispose() throws IOException { - final ICacheEvent<String> cacheEvent = createICacheEvent( getCacheName(), "none", ICacheEventLogger.DISPOSE_EVENT ); + final ICacheEvent<String> cacheEvent = createICacheEvent(getCacheName(), "none", + CacheEventType.DISPOSE_EVENT, this::getEventLoggingExtraInfo); try { if ( !isAlive() ) { - log.error( logCacheName + "Not alive and dispose was called, directgory: " + getDirectory() ); + log.error("{0}: Not alive and dispose was called, directory: {1}", logCacheName, getDirectory()); return; } @@ -227,7 +199,7 @@ public class FileDiskCache<K, V> // TODO consider giving up the handle on the directory. if ( log.isInfoEnabled() ) { - log.info( logCacheName + "Shutdown complete." ); + log.info("{0}: Shutdown complete.", logCacheName); } } finally @@ -253,18 +225,15 @@ public class FileDiskCache<K, V> { if ( log.isDebugEnabled() ) { - log.debug( "File does not exist. Returning null from Get." + file ); + log.debug("{0}: File does not exist. Returning null from Get {1}", logCacheName, file); } return null; } ICacheElement<K, V> element = null; - FileInputStream fis = null; - try + try (FileInputStream fis = new FileInputStream( file )) { - fis = new FileInputStream( file ); - final long length = file.length(); // Create the byte array to hold the data final byte[] bytes = new byte[(int) length]; @@ -285,27 +254,23 @@ public class FileDiskCache<K, V> element = getElementSerializer().deSerialize( bytes, null ); // test that the retrieved object has equal key - if ( element != null && !key.equals( element.getKey() ) ) + if ( element != null && !key.equals( element.key() ) ) { if ( log.isInfoEnabled() ) { - log.info( logCacheName + "key: [" + key + "] point to cached object with key: [" + element.getKey() - + "]" ); + log.info("{0}: key: [{1}] point to cached object with key: [{2}]", logCacheName, key, + element.key()); } element = null; } } catch ( IOException | ClassNotFoundException e ) { - log.error( logCacheName + "Failure getting element, key: [" + key + "]", e ); - } - finally - { - silentClose( fis ); + log.error("{0}: Failure getting element, key: [{1}]", logCacheName, key, e); } // If this is true and we have a max file size, the Least Recently Used file will be removed. - if ( element != null && diskFileCacheAttributes.isTouchOnGet() ) + if ( element != null && getAuxiliaryCacheAttributes().isTouchOnGet() ) { touchWithRetry( file ); } @@ -353,7 +318,7 @@ public class FileDiskCache<K, V> final File file = file( key ); if ( log.isDebugEnabled() ) { - log.debug( logCacheName + "Removing file " + file ); + log.debug("{0}: Removing file {1}", logCacheName, file); } return deleteWithRetry( file ); } @@ -389,46 +354,34 @@ public class FileDiskCache<K, V> { removeIfLimitIsSetAndReached(); - final File file = file( element.getKey() ); + final File file = file( element.key() ); - File tmp = null; - OutputStream os = null; - try + File tmp = File.createTempFile( "JCS_DiskFileCache", null, getDirectory() ); + + try(final FileOutputStream fos = new FileOutputStream( tmp ); + final BufferedOutputStream os = new BufferedOutputStream( fos )) { final byte[] bytes = getElementSerializer().serialize( element ); - tmp = File.createTempFile( "JCS_DiskFileCache", null, getDirectory() ); - - final FileOutputStream fos = new FileOutputStream( tmp ); - os = new BufferedOutputStream( fos ); - if ( bytes != null ) { if ( log.isDebugEnabled() ) { - log.debug( logCacheName + "Wrote " + bytes.length + " bytes to file " + tmp ); + log.debug("{0}: Wrote {1} bytes to file {2}", logCacheName, bytes.length, tmp); } os.write( bytes ); - os.close(); - } - deleteWithRetry( file ); - final boolean result = tmp.renameTo( file ); - if ( log.isDebugEnabled() ) - { - log.debug( logCacheName + "Renamed to: " + file + " Result: " + result); } } catch ( final IOException e ) { - log.error( logCacheName + "Failure updating element, key: [" + element.getKey() + "]", e ); + log.error("{0}: Failure updating element, key: [{1}]", logCacheName, element.key(), e); } - finally + + deleteWithRetry( file ); + final boolean result = tmp.renameTo( file ); + if ( log.isDebugEnabled() ) { - silentClose( os ); - if ( tmp != null && tmp.exists() ) - { - deleteWithRetry( tmp ); - } + log.debug("{0}: Renamed to: {1} Result: {2}", logCacheName, file, result); } } @@ -441,11 +394,12 @@ public class FileDiskCache<K, V> private void removeIfLimitIsSetAndReached() { // TODO we might want to synchronize this block. - if ( diskFileCacheAttributes.getMaxNumberOfFiles() > 0 && getSize() >= diskFileCacheAttributes.getMaxNumberOfFiles() ) + final int maxNumberOfFiles = getAuxiliaryCacheAttributes().getMaxNumberOfFiles(); + if (maxNumberOfFiles > 0 && getSize() >= maxNumberOfFiles) { if ( log.isDebugEnabled() ) { - log.debug( logCacheName + "Max reached, removing least recently modified" ); + log.debug("{0}: Max reached, removing least recently modified", logCacheName); } long oldestLastModified = System.currentTimeMillis(); @@ -464,7 +418,7 @@ public class FileDiskCache<K, V> { if ( log.isDebugEnabled() ) { - log.debug( logCacheName + "Least recently modified: " + theLeastRecentlyModified ); + log.debug("{0}: Least recently modified: {1}", logCacheName, theLeastRecentlyModified ); } deleteWithRetry( theLeastRecentlyModified ); } @@ -485,10 +439,17 @@ public class FileDiskCache<K, V> // TODO: The following should be identical to success == false, but it isn't if ( file.exists() ) { - final int maxRetries = diskFileCacheAttributes.getMaxRetriesOnDelete(); + final int maxRetries = getAuxiliaryCacheAttributes().getMaxRetriesOnDelete(); for ( int i = 0; i < maxRetries && !success; i++ ) { - SleepUtil.sleepAtLeast( 5 ); + try + { + Thread.sleep(5); + } + catch (InterruptedException e) + { + // swallow + } success = file.delete(); } } @@ -498,7 +459,7 @@ public class FileDiskCache<K, V> } if ( log.isDebugEnabled() ) { - log.debug( logCacheName + "deleteWithRetry. success= " + success + " file: " + file ); + log.debug("{0}: deleteWithRetry. success= {1} file: {2}", logCacheName, success, file); } return success; } @@ -514,63 +475,30 @@ public class FileDiskCache<K, V> boolean success = file.setLastModified( System.currentTimeMillis() ); if ( !success ) { - final int maxRetries = diskFileCacheAttributes.getMaxRetriesOnTouch(); + final int maxRetries = getAuxiliaryCacheAttributes().getMaxRetriesOnTouch(); if ( file.exists() ) { for ( int i = 0; i < maxRetries && !success; i++ ) { - SleepUtil.sleepAtLeast( 5 ); + try + { + Thread.sleep(5); + } + catch (InterruptedException e) + { + // swallow + } success = file.delete(); } } } if ( log.isDebugEnabled() ) { - log.debug( logCacheName + "Last modified, success: " + success ); + log.debug("{0}: Last modified, success: {1}", logCacheName, success); } return success; } - /** - * Closes a stream and swallows errors. - * - * @param s The stream - */ - private void silentClose( final InputStream s ) - { - if ( s != null ) - { - try - { - s.close(); - } - catch ( final IOException e ) - { - log.error( logCacheName + "Failure closing stream", e ); - } - } - } - - /** - * Closes a stream and swallows errors. - * - * @param s The stream - */ - private void silentClose( final OutputStream s ) - { - if ( s != null ) - { - try - { - s.close(); - } - catch ( final IOException e ) - { - log.error( logCacheName + "Failure closing stream", e ); - } - } - } - /** * @param directory The directory to set */ @@ -586,4 +514,10 @@ public class FileDiskCache<K, V> { return directory; } + + @Override + protected String getEventLoggingExtraInfo() + { + return logCacheName; + } } diff --git a/commons-jcs4-sandbox/commons-jcs4-filecache/src/main/java/org/apache/commons/jcs/auxiliary/disk/file/FileDiskCacheFactory.java b/commons-jcs4-sandbox/commons-jcs4-filecache/src/main/java/org/apache/commons/jcs/auxiliary/disk/file/FileDiskCacheFactory.java index 19c5145a..7759ef93 100644 --- a/commons-jcs4-sandbox/commons-jcs4-filecache/src/main/java/org/apache/commons/jcs/auxiliary/disk/file/FileDiskCacheFactory.java +++ b/commons-jcs4-sandbox/commons-jcs4-filecache/src/main/java/org/apache/commons/jcs/auxiliary/disk/file/FileDiskCacheFactory.java @@ -16,60 +16,82 @@ */ package org.apache.commons.jcs.auxiliary.disk.file; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + import org.apache.commons.jcs4.auxiliary.AuxiliaryCacheAttributes; import org.apache.commons.jcs4.auxiliary.AuxiliaryCacheFactory; import org.apache.commons.jcs4.engine.behavior.ICompositeCacheManager; import org.apache.commons.jcs4.engine.behavior.IElementSerializer; import org.apache.commons.jcs4.engine.logging.behavior.ICacheEventLogger; +import org.apache.commons.jcs4.engine.match.behavior.IKeyMatcher; import org.apache.commons.jcs4.log.Log; -import org.apache.commons.jcs4.log.LogFactory; /** Create Disk File Caches */ public class FileDiskCacheFactory implements AuxiliaryCacheFactory { /** The logger. */ - private static final Log log = LogFactory.getLog( FileDiskCacheFactory.class ); + private static final Log log = Log.getLog( FileDiskCacheFactory.class ); /** The auxiliary name. */ private String name; - /** The manager used by this factory instance */ - private FileDiskCacheManager diskFileCacheManager; + /** Each region has an entry here. */ + private final ConcurrentMap<String, FileDiskCache<?, ?>> caches = + new ConcurrentHashMap<>(); /** - * Creates a manager if we don't have one, and then uses the manager to create the cache. The - * same factory will be called multiple times by the composite cache to create a cache for each - * region. + * Create the cache. The same factory will be called multiple times by the + * composite cache to create a cache for each region. * * @param attr config * @param cacheMgr The manager to use if needed * @param cacheEventLogger The event logger * @param elementSerializer The serializer + * @param keyMatcher The key matcher * @return AuxiliaryCache */ @Override public <K, V> FileDiskCache<K, V> createCache( - final AuxiliaryCacheAttributes attr, final ICompositeCacheManager cacheMgr, - final ICacheEventLogger cacheEventLogger, final IElementSerializer elementSerializer ) + final AuxiliaryCacheAttributes attr, final ICompositeCacheManager cacheMgr, + final ICacheEventLogger cacheEventLogger, final IElementSerializer elementSerializer, + IKeyMatcher<K> keyMatcher) { final FileDiskCacheAttributes idfca = (FileDiskCacheAttributes) attr; if ( log.isDebugEnabled() ) { log.debug( "Creating DiskFileCache for attributes = " + idfca ); } - synchronized( this ) - { - if ( diskFileCacheManager == null ) - { - if ( log.isDebugEnabled() ) - { - log.debug( "Creating DiskFileCacheManager" ); - } - diskFileCacheManager = new FileDiskCacheManager( idfca, cacheEventLogger, elementSerializer ); - } - return diskFileCacheManager.getCache( idfca ); - } + return getCache(idfca, cacheEventLogger, elementSerializer, + keyMatcher); + } + + /** + * Gets an DiskFileCache for the supplied attributes. Will provide an existing cache for the name + * attribute if one has been created, or will create a new cache. + * + * @param cacheAttributes Attributes the cache should have. + * @return A cache, either from the existing set or newly created. + */ + @SuppressWarnings("unchecked") // Need to cast because of common map for all caches + private <K, V> FileDiskCache<K, V> getCache( final FileDiskCacheAttributes cacheAttributes, + final ICacheEventLogger cacheEventLogger, final IElementSerializer elementSerializer, + final IKeyMatcher<?> keyMatcher) + { + final FileDiskCacheAttributes myCacheAttributes = (FileDiskCacheAttributes) cacheAttributes.clone(); + final String cacheName = cacheAttributes.getCacheName(); + + log.debug( "Getting cache named: " + cacheName ); + + // Try to load the cache from the set that have already been + // created. This only looks at the name attribute. + return (FileDiskCache<K, V>) caches.computeIfAbsent(cacheName, k -> { + FileDiskCache<K, V> newCache = new FileDiskCache<>(myCacheAttributes, elementSerializer); + newCache.setCacheEventLogger(cacheEventLogger); + newCache.setKeyMatcher((IKeyMatcher<K>) keyMatcher); + return newCache; + }); } /** @@ -95,22 +117,13 @@ public class FileDiskCacheFactory } /** - * @see org.apache.commons.jcs.auxiliary.AuxiliaryCacheFactory#initialize() - */ - @Override - public void initialize() - { - // TODO Auto-generated method stub - - } - - /** - * @see org.apache.commons.jcs.auxiliary.AuxiliaryCacheFactory#dispose() + * Gets the class implementing the extended AuxiliaryCacheAttributes for this factory + * + * @return The class value */ @Override - public void dispose() + public Class<? extends AuxiliaryCacheAttributes> getAttributeClass() { - // TODO Auto-generated method stub - + return FileDiskCacheAttributes.class; } } diff --git a/commons-jcs4-sandbox/commons-jcs4-filecache/src/main/java/org/apache/commons/jcs/auxiliary/disk/file/FileDiskCacheManager.java b/commons-jcs4-sandbox/commons-jcs4-filecache/src/main/java/org/apache/commons/jcs/auxiliary/disk/file/FileDiskCacheManager.java deleted file mode 100644 index 07f86a2c..00000000 --- a/commons-jcs4-sandbox/commons-jcs4-filecache/src/main/java/org/apache/commons/jcs/auxiliary/disk/file/FileDiskCacheManager.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * 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 - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.jcs.auxiliary.disk.file; - -/* - * 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 - * - * https://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 java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -import org.apache.commons.jcs4.engine.behavior.IElementSerializer; -import org.apache.commons.jcs4.engine.logging.behavior.ICacheEventLogger; -import org.apache.commons.jcs4.log.Log; -import org.apache.commons.jcs4.log.LogFactory; - -/** - * This is a non singleton. It creates caches on a per region basis. - */ -public class FileDiskCacheManager -{ - /** The logger */ - private static final Log log = LogFactory.getLog( FileDiskCacheManager.class ); - - /** Each region has an entry here. */ - private final ConcurrentMap<String, FileDiskCache<?, ?>> caches = - new ConcurrentHashMap<>(); - - /** Lock cache initialization */ - private final Lock lock = new ReentrantLock(); - - /** User configurable attributes */ - private final FileDiskCacheAttributes defaultCacheAttributes; - - /** Event logger */ - private final ICacheEventLogger eventLogger; - - /** Custom serializer */ - private final IElementSerializer elementSerializer; - - /** - * Constructor for the DiskFileCacheManager object - * - * @param defaultCacheAttributes Default attributes for caches managed by the instance. - * @param cacheEventLogger - * @param elementSerializer - */ - protected FileDiskCacheManager( final FileDiskCacheAttributes defaultCacheAttributes, final ICacheEventLogger cacheEventLogger, - final IElementSerializer elementSerializer ) - { - this.defaultCacheAttributes = defaultCacheAttributes; - this.elementSerializer = elementSerializer; - this.eventLogger = cacheEventLogger; - } - - /** - * Gets an DiskFileCache for the supplied name using the default attributes. - * - * @param cacheName Name that will be used when creating attributes. - * @return A cache. - */ - public <K, V> FileDiskCache<K, V> getCache( final String cacheName ) - { - final FileDiskCacheAttributes cacheAttributes = (FileDiskCacheAttributes) defaultCacheAttributes.clone(); - - cacheAttributes.setCacheName( cacheName ); - - return getCache( cacheAttributes ); - } - - /** - * Gets an DiskFileCache for the supplied attributes. Will provide an existing cache for the name - * attribute if one has been created, or will create a new cache. - * - * @param cacheAttributes Attributes the cache should have. - * @return A cache, either from the existing set or newly created. - */ - @SuppressWarnings("unchecked") // Need to cast because of common map for all caches - public <K, V> FileDiskCache<K, V> getCache( final FileDiskCacheAttributes cacheAttributes ) - { - FileDiskCache<K, V> cache = null; - - final String cacheName = cacheAttributes.getCacheName(); - - log.debug( "Getting cache named: " + cacheName ); - - // Try to load the cache from the set that have already been - // created. This only looks at the name attribute. - cache = (FileDiskCache<K, V>) caches.get( cacheName ); - - if (cache == null) - { - lock.lock(); - - try - { - cache = (FileDiskCache<K, V>) caches.get( cacheName ); - - // If it was not found, create a new one using the supplied - // attributes - if ( cache == null ) - { - cache = new FileDiskCache<>( cacheAttributes, elementSerializer ); - cache.setCacheEventLogger( eventLogger ); - caches.put( cacheName, cache ); - } - } - finally - { - lock.unlock(); - } - } - - return cache; - } -} diff --git a/commons-jcs4-sandbox/commons-jcs4-filecache/src/test/java/org/apache/commons/jcs/auxiliary/disk/file/FileDiskCacheFactoryUnitTest.java b/commons-jcs4-sandbox/commons-jcs4-filecache/src/test/java/org/apache/commons/jcs/auxiliary/disk/file/FileDiskCacheFactoryUnitTest.java index 4f9fb701..8f5ffefd 100644 --- a/commons-jcs4-sandbox/commons-jcs4-filecache/src/test/java/org/apache/commons/jcs/auxiliary/disk/file/FileDiskCacheFactoryUnitTest.java +++ b/commons-jcs4-sandbox/commons-jcs4-filecache/src/test/java/org/apache/commons/jcs/auxiliary/disk/file/FileDiskCacheFactoryUnitTest.java @@ -19,39 +19,45 @@ package org.apache.commons.jcs.auxiliary.disk.file; * under the License. */ -import junit.framework.TestCase; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import org.apache.commons.jcs4.auxiliary.MockCacheEventLogger; import org.apache.commons.jcs4.engine.behavior.ICompositeCacheManager; import org.apache.commons.jcs4.engine.behavior.IElementSerializer; import org.apache.commons.jcs4.engine.control.MockCompositeCacheManager; import org.apache.commons.jcs4.engine.control.MockElementSerializer; +import org.apache.commons.jcs4.engine.control.MockKeyMatcher; import org.apache.commons.jcs4.engine.logging.behavior.ICacheEventLogger; +import org.apache.commons.jcs4.engine.match.behavior.IKeyMatcher; +import org.junit.jupiter.api.Test; /** Verify that the factory works */ public class FileDiskCacheFactoryUnitTest - extends TestCase { /** Verify that we can get a cache from the manager via the factory */ + @Test public void testCreateCache_Normal() { // SETUP final String cacheName = "testCreateCache_Normal"; final FileDiskCacheAttributes cattr = new FileDiskCacheAttributes(); - cattr.setCacheName( cacheName ); - cattr.setDiskPath( "target/test-sandbox/FileDiskCacheFactoryUnitTest" ); + cattr.setCacheName(cacheName); + cattr.setDiskPath("target/test-sandbox/FileDiskCacheFactoryUnitTest"); final ICompositeCacheManager cacheMgr = new MockCompositeCacheManager(); final ICacheEventLogger cacheEventLogger = new MockCacheEventLogger(); final IElementSerializer elementSerializer = new MockElementSerializer(); + final IKeyMatcher<String> keyMatcher = new MockKeyMatcher<>(); final FileDiskCacheFactory factory = new FileDiskCacheFactory(); // DO WORK final FileDiskCache<String, String> result = factory.createCache( cattr, cacheMgr, cacheEventLogger, - elementSerializer ); + elementSerializer, keyMatcher); // VERIFY - assertNotNull( "Should have a disk cache", result ); - assertEquals( "Should have a disk cache with a serializer", elementSerializer, result.getElementSerializer() ); + assertNotNull(result, "Should have a disk cache"); + assertEquals(elementSerializer, result.getElementSerializer(), "Should have a disk cache with a serializer"); } } diff --git a/commons-jcs4-sandbox/commons-jcs4-filecache/src/test/java/org/apache/commons/jcs/auxiliary/disk/file/FileDiskCacheUnitTest.java b/commons-jcs4-sandbox/commons-jcs4-filecache/src/test/java/org/apache/commons/jcs/auxiliary/disk/file/FileDiskCacheUnitTest.java index 6e7ed276..442a9998 100644 --- a/commons-jcs4-sandbox/commons-jcs4-filecache/src/test/java/org/apache/commons/jcs/auxiliary/disk/file/FileDiskCacheUnitTest.java +++ b/commons-jcs4-sandbox/commons-jcs4-filecache/src/test/java/org/apache/commons/jcs/auxiliary/disk/file/FileDiskCacheUnitTest.java @@ -1,7 +1,5 @@ package org.apache.commons.jcs.auxiliary.disk.file; -import java.io.File; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -21,22 +19,28 @@ import java.io.File; * under the License. */ -import junit.framework.TestCase; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.File; import org.apache.commons.jcs4.engine.CacheElement; import org.apache.commons.jcs4.engine.CacheStatus; import org.apache.commons.jcs4.engine.behavior.ICacheElement; import org.apache.commons.jcs4.utils.timing.SleepUtil; +import org.junit.jupiter.api.Test; /** Tests for the disk file cache. */ public class FileDiskCacheUnitTest - extends TestCase { /** * Verify initialization. * * @throws Exception */ + @Test public void testInitialization_Normal() throws Exception { @@ -51,13 +55,13 @@ public class FileDiskCacheUnitTest final File directory = diskCache.getDirectory(); // VERIFY - assertNotNull( "Should have a directory", directory ); - assertTrue( "Should have an existing directory", directory.exists() ); - assertTrue( "Directory should include the cache name. " + directory.getAbsolutePath(), directory - .getAbsolutePath().indexOf( cacheName ) != -1 ); - assertTrue( "Directory should include the disk path. " + directory.getAbsolutePath(), directory - .getAbsolutePath().indexOf( "DiskFileCacheUnitTest" ) != -1 ); - assertTrue( "Should be alive", diskCache.getStatus() == CacheStatus.ALIVE ); + assertNotNull(directory, "Should have a directory"); + assertTrue(directory.exists(), "Should have an existing directory"); + assertTrue(directory.getAbsolutePath().indexOf( cacheName ) != -1, + "Directory should include the cache name. " + directory.getAbsolutePath()); + assertTrue(directory.getAbsolutePath().indexOf( "DiskFileCacheUnitTest" ) != -1, + "Directory should include the disk path. " + directory.getAbsolutePath()); + assertEquals(CacheStatus.ALIVE, diskCache.getStatus(), "Should be alive"); } /** @@ -79,7 +83,7 @@ public class FileDiskCacheUnitTest diskCache.dispose(); // VERIFY - assertTrue( "Should not be alive", diskCache.getStatus() == CacheStatus.DISPOSED ); + assertEquals(CacheStatus.DISPOSED, diskCache.getStatus(), "Should not be alive"); } /** @@ -103,9 +107,9 @@ public class FileDiskCacheUnitTest final File directory = diskCache.getDirectory(); // VERIFY - assertNotNull( "Should have a directory", directory ); - assertFalse( "Should not have an existing directory", directory.exists() ); - assertTrue( "Should not be alive", diskCache.getStatus() == CacheStatus.DISPOSED ); + assertNotNull(directory, "Should have a directory"); + assertTrue(directory.exists(), "Should have an existing directory"); + assertEquals(CacheStatus.DISPOSED, diskCache.getStatus(), "Should not be alive"); } /** @@ -129,7 +133,7 @@ public class FileDiskCacheUnitTest final int result = diskCache.getSize(); // VERIFY - assertEquals( "Should be empty.", 0, result ); + assertEquals(0, result, "Should be empty."); } /** @@ -155,7 +159,7 @@ public class FileDiskCacheUnitTest final int result = diskCache.getSize(); // VERIFY - assertEquals( "Should not be empty.", 1, result ); + assertEquals(1, result, "Should not be empty."); } /** @@ -182,7 +186,7 @@ public class FileDiskCacheUnitTest final int result = diskCache.getSize(); // VERIFY - assertEquals( "Should be empty.", 0, result ); + assertEquals(0, result, "Should be empty."); } /** @@ -204,7 +208,7 @@ public class FileDiskCacheUnitTest final ICacheElement<String, String> result = diskCache.get( "key" ); // VERIFY - assertNull( "Should be null.", result ); + assertNull(result, "Should be null."); } /** @@ -229,7 +233,7 @@ public class FileDiskCacheUnitTest final ICacheElement<String, String> result = diskCache.get( "key1" ); // VERIFY - assertNotNull( "Should NOT be null.", result ); + assertNotNull(result, "Should NOT be null."); } /** @@ -268,7 +272,7 @@ public class FileDiskCacheUnitTest } // VERIFY - assertEquals("All files should still be cached", maxNumberOfFiles, stillCached); + assertEquals(maxNumberOfFiles, stillCached, "All files should still be cached"); } /** @@ -307,7 +311,7 @@ public class FileDiskCacheUnitTest } // VERIFY - assertEquals(maxNumberOfFiles, stillCached); + assertEquals(maxNumberOfFiles, stillCached, "All files should still be cached"); } /** @@ -342,7 +346,7 @@ public class FileDiskCacheUnitTest // to make this test work. SleepUtil.sleepAtLeast( 501 ); final ICacheElement<String, String> ice = diskCache.get( "key" + i ); - assertNotNull("Value of key" + i + " should not be null", ice); + assertNotNull(ice, "Value of key" + i + " should not be null"); } SleepUtil.sleepAtLeast( 100 ); @@ -355,7 +359,7 @@ public class FileDiskCacheUnitTest final ICacheElement<String, String> result = diskCache.get( "key9" ); // VERIFY - assertNull( "Should be null.", result ); + assertNull(result, "Should be null."); } /** @@ -402,7 +406,7 @@ public class FileDiskCacheUnitTest final ICacheElement<String, String> result = diskCache.get( "key0" ); // VERIFY - assertNull( "Should be null.", result ); + assertNull(result, "Should be null."); } /** @@ -426,7 +430,7 @@ public class FileDiskCacheUnitTest final File result = diskCache.file( key ); // VERIFY - assertEquals( "Wrong string.", key, result.getName() ); + assertEquals(key, result.getName(), "Wrong string."); } /** @@ -450,7 +454,7 @@ public class FileDiskCacheUnitTest final File result = diskCache.file( key ); // VERIFY - assertEquals( "Wrong string.", "simple_string", result.getName() ); + assertEquals("simple_string", result.getName(), "Wrong string."); } /** @@ -474,7 +478,7 @@ public class FileDiskCacheUnitTest final File result = diskCache.file( key ); // VERIFY - assertEquals( "Wrong string.", "simple_string", result.getName() ); + assertEquals("simple_string", result.getName(), "Wrong string."); } /** @@ -499,7 +503,7 @@ public class FileDiskCacheUnitTest final File result = diskCache.file( firstResult.getName() ); // VERIFY - assertEquals( "Wrong string.", "simple_string", result.getName() ); + assertEquals("simple_string", result.getName(), "Wrong string."); } /** @@ -526,7 +530,7 @@ public class FileDiskCacheUnitTest final int result = diskCache.getSize(); // VERIFY - assertEquals( "Should be empty.", 0, result ); + assertEquals(0, result, "Should be empty."); } /** @@ -560,7 +564,7 @@ public class FileDiskCacheUnitTest // VERIFY final ICacheElement<String, String> afterElement = diskCache.get( "x" ); assertNotNull( afterElement ); - final String after = afterElement.getVal(); + final String after = afterElement.value(); assertNotNull( "afterElement = " + afterElement, after ); assertEquals( "wrong string after retrieval", string, after );
