5c052f6cba1e4f721b762395b9f511644de78514
[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.FileInputStream;
6 import java.io.FileNotFoundException;
7 import java.io.FileOutputStream;
8 import java.io.IOException;
9 import java.io.RandomAccessFile;
10 import java.nio.channels.FileLock;
11
12 import org.apache.commons.logging.LogFactory;
13
14 /**
15  * transient object representing a file lock
16  * This lock should hold for all processes interacting in a session.
17  * TODO: currently implemented for local filesystem style locking - need a fallback mechanism for systems without file locks.
18  * @author jimp
19  * 
20  */
21
22 public class Lock {
23   org.apache.commons.logging.Log log = LogFactory.getLog(Lock.class);
24   FileLock lock = null;
25   RandomAccessFile rafile=null;
26   /**
27    * creates a valid Lock (test with <method>isLocked</method>)
28    * if a lock could be obtained for <param>lockfile</param>
29    * @param lockfile
30    */
31   public Lock(java.io.File lockfile) {
32     // try and get a lock.
33     lock = null;
34     
35     try {
36       if (!lockfile.exists())
37         if (!lockfile.createNewFile()) {
38           log.warn("Failed to create locked file "+lockfile);
39           return;
40         }
41       
42       lock = (rafile=new RandomAccessFile(lockfile,"rw")).getChannel().tryLock();
43       if (lock==null || !lock.isValid()) {
44         // failed to get lock. Close the file channel
45         log.debug("failed to get lock for "+lockfile);
46         rafile.getChannel().close();
47         lock=null;
48       }
49     } catch (FileNotFoundException e) {
50       //
51       log.debug("Lock failed - normal behaviour for windows locking.");
52       //log.error("Error! Couldn't create a lockfile at "
53       //  + lockfile.getAbsolutePath(), e);
54     } catch (IOException e) {
55       log.error("Error! Problems with IO when creating a lock on "
56           + lockfile.getAbsolutePath(),e);
57     }
58   }
59   
60   boolean isLocked() {
61     if (lock != null && lock.isValid()) {
62       return true;
63     }
64     return false;
65   }
66   public void release() {
67     try {
68       // TODO: verify that channel.close should be called after release() for rigourous locking.
69       if (rafile!=null && rafile.getChannel()!=null) {
70         if (rafile.getChannel().isOpen()) {
71           if (lock!=null && lock.isValid())
72             lock.release();
73           if (rafile.getChannel().isOpen())
74             rafile.getChannel().close();
75         }
76       }
77     } catch (IOException e) {
78       log.warn("Whilst releasing lock",e);
79     }
80     lock=null;
81     rafile=null;
82   }
83   
84   /**
85    * gets Locked Stream for reading from
86    * @param atStart true to start reading at beginning of file.
87    * @return null if file not locked
88    * @throws IOException
89    */
90   public FileInputStream getFileInputStream(boolean atStart) throws IOException {
91     if (!isLocked())
92       return null;
93     if (atStart)
94       rafile.seek(0);
95     return new FileInputStream(rafile.getFD());
96   }
97   /**
98    * gets Locked stream to write to
99    * FileInput always starts at the *end* of the file (after any truncation)
100    * @param clear true means file will be cleared to zero length
101    * @return null if file is not locked
102    * @throws IOException
103    */
104   public FileOutputStream getFileOutputStream(boolean clear) throws IOException {
105     if (!isLocked())
106       return null;
107     if (clear)
108       rafile.setLength(0);
109     rafile.seek(rafile.length());
110     return new LockedFileOutputStream(rafile.getFD());
111   }
112   /**
113    * return buffered output stream to locked file.
114    * @param clear - true means file is truncated to 0 length before writing 
115    * @return
116    */
117   public BufferedOutputStream getBufferedOutputStream(boolean clear) throws IOException {
118     FileOutputStream fos = getFileOutputStream(clear);
119     if (fos!=null)
120       return new BufferedOutputStream(fos);
121     return null;
122   }
123
124   /**
125    * return buffered input stream for locked file.
126    * @param atStart - true means read from begining of file
127    * @return null if file is not locked.
128    */
129   public BufferedInputStream getBufferedInputStream(boolean atStart) throws IOException {
130     FileInputStream fis = getFileInputStream(atStart);
131     if (fis!=null)
132       return new BufferedInputStream(fis);
133     return null;
134   }
135   /* Explicitly release lock (probably don't need to do this!)
136    * @see java.lang.Object#finalize()
137    */
138   protected void finalize() throws Throwable {
139     release();
140     super.finalize();
141   }
142   
143 }