View Javadoc

1   package org.astrogrid.jes.util;
2   
3   import java.io.File;
4   import java.io.IOException;
5   
6   /***
7    * An implementation of {@link org.astrogrid.jes.util.BaseDirectory}
8    * for testing. The directory is created with a unique name in the
9    * temporary-files directory during construction
10   * 
11   * @author Guy Rixon
12   */
13  public class TemporaryBaseDirectory implements BaseDirectory {
14    
15    private File directory;
16    
17    /***
18     * Creates a new instance of TemporaryBaseDirectory.
19     * Creates also the directory to which the object refers,
20     * as a subdirectory of the default temporary-files directory.
21     * A gloss on the temporary-file mechanism of java.io.File
22     * is used to make sure that the temporary directory does not classh
23     * with any existing directories or any directories created in
24     * parallel.
25     */
26    public TemporaryBaseDirectory() throws IOException {
27      
28      // Create a temporary file whose name is the name of the desired
29      // directory with ".tmp" appended. This file and its name have
30      // the usual guarantees of uniqueness specified in the API
31      // contract for java.io.File. If we now create a directory
32      // whose name is the same as the file but without the ".tmp"
33      // suffix, then we can be sure that we do not clash with any
34      // existing drectories and that there is no race condition. 
35      File tmpFile = File.createTempFile("jes-test-base-directory",".tmp");
36      
37      // Derive the name for the directory.
38      int dirNameEnd = tmpFile.getName().indexOf(".tmp");
39      String dirName = tmpFile.getName().substring(0, dirNameEnd);
40      this.directory = new File(tmpFile.getParent(), dirName);
41      
42      // Create the directory in the file system.
43      this.directory.mkdir();
44    }
45    
46    /***
47     * Gets the directory that was created during construction.
48     *
49     * @return The directory
50     */
51    public File getDir() {
52      return this.directory;
53    }
54    
55  }