package net.jimblackler.Utils.test; import junit.framework.TestCase; import net.jimblackler.Utils.CollectionAbortedException; import net.jimblackler.Utils.Collector; import net.jimblackler.Utils.ResultHandler; import net.jimblackler.Utils.ThreadedYieldAdapter; import net.jimblackler.Utils.YieldAdapterIterable; import java.io.File; import java.io.IOException; /** * This demo shows a typical use for the yield adapter - a process that is implemented with * recursion, but may return a lot of results (so list gathering is not ideal). Here we implement a * process that lists all the files and directories under a given directory path. It is first * implemented with the Collector pattern, then the yield adapter is used to adapt this into a * version that returns a standard Iterable object. This is particularly convenient for the calling * code, without sacrificing the simplicity of the implementation. */ public class DirectoryScanDemo extends TestCase { /** * Implments Collector interface to return all the files and directories on the disk under a * specified file location. Results are returned to an injected results processor object. */ class DirectoryScanner implements Collector { final File baseDir; DirectoryScanner(String baseDirectoryName) throws IOException { baseDir = new File(baseDirectoryName); if (!baseDir.isDirectory()) { throw new IOException(baseDirectoryName + " is not a directory"); } } public void collect(ResultHandler stringResultHandler) throws CollectionAbortedException { collect(stringResultHandler, baseDir); } private void collect(ResultHandler stringResultHandler, File fileOrDir) throws CollectionAbortedException { stringResultHandler.handleResult(fileOrDir.getAbsolutePath()); // Send result to processor if (fileOrDir.isDirectory()) { // Recurse directory final File[] children = fileOrDir.listFiles(); // Get children if (children != null) { // Some dirs don't have children for (File child : children) { collect(stringResultHandler, child); // Recurse } } } } } /** * This tests reads files using the Collector pattern method, and displays the results using a * locally defined, injected ResultProcess object. */ public void testDiectoryScanCollector() throws Exception { final ResultHandler handler = new ResultHandler() { public void handleResult(String value) { System.out.println(value); } }; new DirectoryScanner(".").collect(handler); } /** * This shows how the yield adapter can be used to convert a Collector pattern method into one * that returns a standard iterator. */ YieldAdapterIterable scan(String directoryName) throws IOException { return new ThreadedYieldAdapter().adapt(new DirectoryScanner(directoryName)); } /** * This test reads files from the recursive scan, using a standard iterator */ public void testDirectoryScanIterator() throws Exception { for (String str : scan(".")) { System.out.println(str); } } }