diff src/cachingfilter/CachedDir.java @ 0:7ecd1a4ef557

add content
author Franklin Schmidt <fschmidt@gmail.com>
date Thu, 21 Mar 2019 19:15:52 -0600
parents
children
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/cachingfilter/CachedDir.java	Thu Mar 21 19:15:52 2019 -0600
@@ -0,0 +1,99 @@
+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();
+	}
+
+}