9dd472fab8f5b6d4bcb0b51b6078110be952cd87
[vamsas.git] / src / org / vamsas / client / simpleclient / Lock.java
1 package org.vamsas.client.simpleclient;
2
3 import java.io.BufferedInputStream;
4 import java.io.BufferedOutputStream;
5 import java.io.File;
6 import java.io.FileInputStream;
7 import java.io.FileOutputStream;
8 import java.io.IOException;
9 import java.io.RandomAccessFile;
10
11 import org.apache.commons.logging.LogFactory;
12
13 /**
14  * transient object representing a file lock
15  * This lock should hold for all processes interacting in a session.
16  * @author jimp
17  */
18
19 public abstract class Lock {
20   protected org.apache.commons.logging.Log log = LogFactory.getLog(Lock.class);
21   File target = null; // The file that is being locked
22   protected RandomAccessFile rafile=null;
23   
24   /**
25    * creates a valid Lock (test with <method>isLocked</method>)
26    * if a lock could be obtained for <param>lockfile</param>
27    * @param lockfile
28    */
29   protected Lock(java.io.File lockfile) {
30     target = lockfile;
31   }
32   /**
33    * 
34    * @return true if lock is held on the target
35    */
36   public abstract boolean isLocked();
37   /**
38    * release lock and close all managed channels to file
39    *
40    */
41   public abstract void release();
42   /**
43    * optionally close the open random access channel on the file when releasing lock
44    * @param closeChannel
45    */
46   public abstract void release(boolean closeChannel);
47
48   /**
49    * gets Locked Stream for reading from
50    * @param atStart true to start reading at beginning of file.
51    * @return null if file not locked
52    * @throws IOException
53    */
54   public abstract FileInputStream getFileInputStream(boolean atStart) throws IOException;
55
56   /**
57    * gets Locked stream to write to
58    * FileInput always starts at the *end* of the file (after any truncation)
59    * @param clear true means file will be cleared to zero length
60    * @return null if file is not locked
61    * @throws IOException
62    */
63   public abstract FileOutputStream getFileOutputStream(boolean clear) throws IOException;
64   /**
65    * return buffered output stream to locked file.
66    * @param clear - true means file is truncated to 0 length before writing 
67    * @return
68    */
69   public abstract BufferedOutputStream getBufferedOutputStream(boolean clear) throws IOException;
70   
71   protected void finalize() throws Throwable {
72     target=null;
73   }
74   /**
75    * return buffered input stream for locked file.
76    * @param atStart - true means read from begining of file
77    * @return null if file is not locked.
78    */
79   public BufferedInputStream getBufferedInputStream(boolean atStart) throws IOException {
80     FileInputStream fis = getFileInputStream(atStart);
81     if (fis!=null)
82       return new BufferedInputStream(fis);
83     return null;
84   }
85 }