FileDocCategorySizeDatePackage
FSDirectory.javaAPI DocApache Lucene 1.915340Mon Feb 20 09:20:16 GMT 2006org.apache.lucene.store

FSDirectory

public class FSDirectory extends Directory
Straightforward implementation of {@link Directory} as a directory of files.
see
Directory
author
Doug Cutting

Fields Summary
private static final Hashtable
DIRECTORIES
This cache of directories ensures that there is a unique Directory instance per path, so that synchronization on the Directory can be used to synchronize access between readers and writers. This should be a WeakHashMap, so that entries can be GC'd, but that would require Java 1.2. Instead we use refcounts...
private static boolean
disableLocks
public static final String
LOCK_DIR
Directory specified by org.apache.lucene.lockDir or java.io.tmpdir system property
private static Class
IMPL
The default class which implements filesystem-based directories.
private static MessageDigest
DIGESTER
private byte[]
buffer
A buffer optionally used in renameTo method
private File
directory
private int
refCount
private File
lockDir
private static final char[]
HEX_DIGITS
So we can do some byte-to-hexchar conversion below
Constructors Summary
protected FSDirectory()


    
Methods Summary
public synchronized voidclose()
Closes the store to future operations.

    if (--refCount <= 0) {
      synchronized (DIRECTORIES) {
        DIRECTORIES.remove(directory);
      }
    }
  
private synchronized voidcreate()

    if (!directory.exists())
      if (!directory.mkdirs())
        throw new IOException("Cannot create directory: " + directory);

    if (!directory.isDirectory())
      throw new IOException(directory + " not a directory");

    String[] files = directory.list(new IndexFileNameFilter());            // clear old files
    for (int i = 0; i < files.length; i++) {
      File file = new File(directory, files[i]);
      if (!file.delete())
        throw new IOException("Cannot delete " + files[i]);
    }

    String lockPrefix = getLockPrefix().toString(); // clear old locks
    files = lockDir.list();
    if (files == null)
      throw new IOException("Cannot read lock directory " + lockDir.getAbsolutePath());
    for (int i = 0; i < files.length; i++) {
      if (!files[i].startsWith(lockPrefix))
        continue;
      File lockFile = new File(lockDir, files[i]);
      if (!lockFile.delete())
        throw new IOException("Cannot delete " + files[i]);
    }
  
public org.apache.lucene.store.IndexOutputcreateOutput(java.lang.String name)
Creates a new, empty file in the directory with the given name. Returns a stream writing this file.

    File file = new File(directory, name);
    if (file.exists() && !file.delete())          // delete existing, if any
      throw new IOException("Cannot overwrite: " + file);

    return new FSIndexOutput(file);
  
public voiddeleteFile(java.lang.String name)
Removes an existing file in the directory.

    File file = new File(directory, name);
    if (!file.delete())
      throw new IOException("Cannot delete " + file);
  
public booleanfileExists(java.lang.String name)
Returns true iff a file with the given name exists.

    File file = new File(directory, name);
    return file.exists();
  
public longfileLength(java.lang.String name)
Returns the length in bytes of a file in the directory.

    File file = new File(directory, name);
    return file.length();
  
public longfileModified(java.lang.String name)
Returns the time the named file was last modified.

    File file = new File(directory, name);
    return file.lastModified();
  
public static longfileModified(java.io.File directory, java.lang.String name)
Returns the time the named file was last modified.

    File file = new File(directory, name);
    return file.lastModified();
  
public static org.apache.lucene.store.FSDirectorygetDirectory(java.lang.String path, boolean create)
Returns the directory instance for the named location.

Directories are cached, so that, for a given canonical path, the same FSDirectory instance will always be returned. This permits synchronization on directories.

param
path the path to the directory.
param
create if true, create, or erase any existing contents.
return
the FSDirectory for the named file.


                                                            
        
        
    return getDirectory(new File(path), create);
  
public static org.apache.lucene.store.FSDirectorygetDirectory(java.io.File file, boolean create)
Returns the directory instance for the named location.

Directories are cached, so that, for a given canonical path, the same FSDirectory instance will always be returned. This permits synchronization on directories.

param
file the path to the directory.
param
create if true, create, or erase any existing contents.
return
the FSDirectory for the named file.

    file = new File(file.getCanonicalPath());
    FSDirectory dir;
    synchronized (DIRECTORIES) {
      dir = (FSDirectory)DIRECTORIES.get(file);
      if (dir == null) {
        try {
          dir = (FSDirectory)IMPL.newInstance();
        } catch (Exception e) {
          throw new RuntimeException("cannot load FSDirectory class: " + e.toString());
        }
        dir.init(file, create);
        DIRECTORIES.put(file, dir);
      } else if (create) {
        dir.create();
      }
    }
    synchronized (dir) {
      dir.refCount++;
    }
    return dir;
  
public static booleangetDisableLocks()
Returns whether Lucene's use of lock files is disabled.

return
true if locks are disabled, false if locks are enabled.

    return FSDirectory.disableLocks;
  
public java.io.FilegetFile()

    return directory;
  
private java.lang.StringBuffergetLockPrefix()

    String dirName;                               // name to be hashed
    try {
      dirName = directory.getCanonicalPath();
    } catch (IOException e) {
      throw new RuntimeException(e.toString());
    }

    byte digest[];
    synchronized (DIGESTER) {
      digest = DIGESTER.digest(dirName.getBytes());
    }
    StringBuffer buf = new StringBuffer();
    buf.append("lucene-");
    for (int i = 0; i < digest.length; i++) {
      int b = digest[i];
      buf.append(HEX_DIGITS[(b >> 4) & 0xf]);
      buf.append(HEX_DIGITS[b & 0xf]);
    }

    return buf;
  
private voidinit(java.io.File path, boolean create)

    directory = path;

    if (LOCK_DIR == null) {
      lockDir = directory;
    }
    else {
      lockDir = new File(LOCK_DIR);
    }
    // Ensure that lockDir exists and is a directory.
    if (!lockDir.exists()) {
      if (!lockDir.mkdirs())
        throw new IOException("Cannot create directory: " + lockDir);
    } else if (!lockDir.isDirectory()) {
      throw new IOException("Found regular file where directory expected: " + lockDir);
    }
    if (create) {
      create();
    }

    if (!directory.isDirectory())
      throw new IOException(path + " not a directory");
  
public java.lang.String[]list()
Returns an array of strings, one for each file in the directory.

    return directory.list();
  
public org.apache.lucene.store.LockmakeLock(java.lang.String name)
Constructs a {@link Lock} with the specified name. Locks are implemented with {@link File#createNewFile()}.

param
name the name of the lock file
return
an instance of Lock holding the lock


                                    
      
    StringBuffer buf = getLockPrefix();
    buf.append("-");
    buf.append(name);

    // create a lock file
    final File lockFile = new File(lockDir, buf.toString());

    return new Lock() {
      public boolean obtain() throws IOException {
        if (disableLocks)
          return true;

        if (!lockDir.exists()) {
          if (!lockDir.mkdirs()) {
            throw new IOException("Cannot create lock directory: " + lockDir);
          }
        }

        return lockFile.createNewFile();
      }
      public void release() {
        if (disableLocks)
          return;
        lockFile.delete();
      }
      public boolean isLocked() {
        if (disableLocks)
          return false;
        return lockFile.exists();
      }

      public String toString() {
        return "Lock@" + lockFile;
      }
    };
  
public org.apache.lucene.store.IndexInputopenInput(java.lang.String name)
Returns a stream reading an existing file.

    return new FSIndexInput(new File(directory, name));
  
public synchronized voidrenameFile(java.lang.String from, java.lang.String to)
Renames an existing file in the directory.

    File old = new File(directory, from);
    File nu = new File(directory, to);

    /* This is not atomic.  If the program crashes between the call to
       delete() and the call to renameTo() then we're screwed, but I've
       been unable to figure out how else to do this... */

    if (nu.exists())
      if (!nu.delete())
        throw new IOException("Cannot delete " + nu);

    // Rename the old file to the new one. Unfortunately, the renameTo()
    // method does not work reliably under some JVMs.  Therefore, if the
    // rename fails, we manually rename by copying the old file to the new one
    if (!old.renameTo(nu)) {
      java.io.InputStream in = null;
      java.io.OutputStream out = null;
      try {
        in = new FileInputStream(old);
        out = new FileOutputStream(nu);
        // see if the buffer needs to be initialized. Initialization is
        // only done on-demand since many VM's will never run into the renameTo
        // bug and hence shouldn't waste 1K of mem for no reason.
        if (buffer == null) {
          buffer = new byte[1024];
        }
        int len;
        while ((len = in.read(buffer)) >= 0) {
          out.write(buffer, 0, len);
        }

        // delete the old file.
        old.delete();
      }
      catch (IOException ioe) {
        throw new IOException("Cannot rename " + old + " to " + nu);
      }
      finally {
        if (in != null) {
          try {
            in.close();
          } catch (IOException e) {
            throw new RuntimeException("Cannot close input stream: " + e.toString());
          }
        }
        if (out != null) {
          try {
            out.close();
          } catch (IOException e) {
            throw new RuntimeException("Cannot close output stream: " + e.toString());
          }
        }
      }
    }
  
public static voidsetDisableLocks(boolean doDisableLocks)
Set whether Lucene's use of lock files is disabled. By default, lock files are enabled. They should only be disabled if the index is on a read-only medium like a CD-ROM.


                                     
       
    FSDirectory.disableLocks = doDisableLocks;
  
public java.lang.StringtoString()
For debug output.

    return this.getClass().getName() + "@" + directory;
  
public voidtouchFile(java.lang.String name)
Set the modified time of an existing file to now.

    File file = new File(directory, name);
    file.setLastModified(System.currentTimeMillis());