Mercurial Hosting > nabble
view src/cachingfilter/CachedDir.java @ 19:18cf4872fd7f
remove anonymous posting
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Fri, 29 May 2020 22:58:25 -0600 |
parents | 7ecd1a4ef557 |
children |
line wrap: on
line source
package cachingfilter; import java.io.File; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; final class CachedDir implements CachedPage { private static final Logger logger = LoggerFactory.getLogger(CachedDir.class); private static final long tooLong = 1000L*60*10; // 10 minutes private final File dir; private File newFile; CachedDir( File parent, String child ) { this.dir = new File(parent,child); } public String name() { return dir.getName(); } public boolean exists() { if( !dir.exists() ) return false; File[] files = dir.listFiles(); if( files == null ) throw new RuntimeException("error doing listFiles of "+dir); return files.length >= 1; } public File lastFile() { File[] files = dir.listFiles(); if( files.length == 1 ) { return files[0]; } int n = 0; File lastFile = null; for( File file : files ) { String name = file.getName(); int i = Integer.parseInt(name); if( n < i ) { if( lastFile != null ) lastFile.delete(); n = i; lastFile = file; } else { file.delete(); } } if( lastFile==null ) throw new RuntimeException(dir.toString()); return lastFile; } public File newFile() throws IOException { if( !dir.exists() && !dir.mkdir() ) throw new RuntimeException("couldn't create "+dir); int n = 0; for( File file : dir.listFiles() ) { String name = file.getName(); int i = Integer.parseInt(name); if( n < i ) n = i; file.delete(); } newFile = new File( dir, Integer.toString( n + 1 ) ); if( !newFile.createNewFile() ) throw new RuntimeException("couldn't create "+newFile); return newFile; } public void deleteNewFile() { if( !newFile.delete() ) throw new RuntimeException("couldn't delete new file "+newFile); } public boolean delete() { File die = new File(dir.getParentFile(),"~die"); if( die.exists() ) { for( File f : die.listFiles() ) { if( !f.delete() ) { logger.error("couldn't delete "+f); return false; } } if( !die.delete() ) { logger.error("couldn't delete "+die); return false; } } return dir.renameTo(die); } public String toString() { return dir.toString(); } }