null pointer exception on attempt to release lock explicitly.
[vamsas.git] / src / uk / ac / vamsas / client / simpleclient / FileLock.java
1 package uk.ac.vamsas.client.simpleclient;
2
3 import java.io.BufferedOutputStream;
4 import java.io.File;
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.FileChannel;
11 import java.nio.channels.ReadableByteChannel;
12 /**
13  * File based Locking mechanism to get around some bizarre limitations of JarEntry seeking.
14  * Abstract locks have a target file, to which access is controlled when a lock is held. Native locks on WindowsXP seem to conflict with Jar seek operations, so a file lock creates an advisory lock.
15  * Method:
16  * A lock file is created, if it doesn't already exist - the naming convention is TargetFile+suffixSeparator+_LockSuffix.
17  * A lock is obtained by locking the lock file with a native lock. The NativeLock is used for this.
18  * @author JimP
19  *
20  */
21 public class FileLock extends Lock {
22   private File _lock = null;
23   protected static String _LockSuffix="lck";
24   private NativeLock advisory=null;
25   /**
26    * ensure that the _lock file exists
27    * and create a lock
28    */
29   private boolean ensureLockFile(boolean block) {
30     if (_lock==null)
31       return false;
32     if (advisory!=null && advisory.isLocked())
33       return true;
34     try { 
35       advisory=new NativeLock(_lock, block);
36     } catch (Exception e) {
37       if (!_lock.exists()) {
38         // advisory cannot be created. this is serious.
39         log.fatal("Failed to create advisory lock file "+_lock,e);
40         throw new Error("Failed to create advisory lock file "+_lock);
41       }
42     }
43     return (advisory!=null) && advisory.isLocked();
44   }
45   /**
46    * call to clear up a filelock file after its been made
47    *
48    */
49   private void tidy() {
50     if (_lock!=null) { 
51       if ( advisory!=null) {
52         advisory.target.deleteOnExit(); // release will null the target
53         advisory.release(true);
54       }
55       advisory=null;
56       _lock=null;
57     }
58   }
59   /**
60    * @param lockfile
61    * @param block true means thread blocks until FileLock is obtained.
62    */
63   public FileLock(File lockfile, boolean block) {
64     super(lockfile);
65     // try and get a lock.
66     try {
67       _lock = new File(lockfile.getParentFile(), lockfile.getName()+"."+_LockSuffix);
68       if (!ensureLockFile(block)) {
69         log.debug("Couldn't get lock on "+_lock);
70         tidy();
71         return;
72       }
73       // create target file ready to be written to if necessary.
74       if (!lockfile.exists())
75         if (!lockfile.createNewFile()) {
76           log.warn("Failed to create locked file "+lockfile);
77           return;
78         }
79       //openRaFile();
80     } catch (FileNotFoundException e) {
81       //
82       log.debug("FileLock failed with target="+lockfile+" and lockfile suffix of "+_LockSuffix);
83       //log.error("Error! Couldn't create a lockfile at "
84       //  + lockfile.getAbsolutePath(), e);
85     } catch (IOException e) {
86       log.error("Error! Problems with IO when creating a lock on "
87           + lockfile.getAbsolutePath(),e);
88     }
89   }
90   
91   private boolean openRaFile() throws IOException {
92     if (target==null)
93       return false;
94     if (advisory==null || !advisory.isLocked())
95       return false;
96     if (rafile==null || rafile.getFD()==null || !rafile.getFD().valid()) {
97       rafile=new RandomAccessFile(target,"rw");
98     } else {
99       if (log.isDebugEnabled())
100         log.debug("Reusing existing RandomAccessFile on "+target);
101     }
102     return (rafile.getChannel()!=null) && rafile.getChannel().isOpen();
103   }
104   
105   public boolean isLocked() {
106     if (advisory != null) {
107       if (advisory.isLocked())
108         return true;
109       advisory=null;
110       if (log.isDebugEnabled())
111         log.debug("Lockfile "+_lock+" unexpectedly deleted ?");
112     }
113     return false;
114   }
115   
116   public void release() {
117     release(true);
118   }
119   
120   public void release(boolean closeChannel) {
121     if (!isLocked())
122       return;
123     if (rafile!=null) {
124       if (closeChannel) {
125         try {
126           rafile.close();
127         } catch (Exception e) {
128           log.debug("Unexpected exception whilst closing RandomAccessFile on "+target, e);
129         }
130         rafile=null; // do not hold reference to rafile anymore either
131       }
132       if (log.isDebugEnabled())
133         log.debug("Releasing advisory lock on "+target);
134       // TODO: LATER: verify this change in closeChannel semantics really is correct - ArchiveClient works correctly
135     }
136     tidy();
137   }
138   
139   public FileInputStream getFileInputStream(boolean atStart) throws IOException {
140     if (!isLocked()) {
141       log.debug("Don't hold lock on "+target+" to get locked FileInputStream.");
142       return null;
143     }
144     openRaFile();
145     if (atStart)
146       rafile.seek(0);
147     return new FileInputStream(rafile.getFD());
148   }
149   
150   
151   public FileOutputStream getFileOutputStream(boolean clear) throws IOException {
152     if (!isLocked()) {
153       log.debug("Don't hold lock on "+target+" to get locked FileOutputStream.");
154       return null;
155     }
156     openRaFile();
157     if (clear) {
158       rafile.seek(0);
159       rafile.setLength(0);
160     } else
161       rafile.seek(rafile.length());
162     return new LockedFileOutputStream(rafile.getFD());
163   }
164   
165   
166   public BufferedOutputStream getBufferedOutputStream(boolean clear) throws IOException {
167     log.debug("Getting BufferedOutputStream (clear="+clear+")");
168     FileOutputStream fos = getFileOutputStream(clear);
169     if (fos!=null)
170       return new BufferedOutputStream(fos);
171     return null;
172   }
173   
174   /* (non-Javadoc)
175    * @see uk.ac.vamsas.client.simpleclient.Lock#getLength()
176    */
177   public long length() {
178     if (isLocked()) {
179       if (!target.exists()) {
180         try {
181           target.createNewFile();
182         } catch (Exception e) {
183           log.error("Invalid lock:Failed to create target file "+target);
184           tidy();
185           return -1;
186         }
187         return 0;
188       }
189       return target.length();
190     }
191     return -1;
192   }
193   protected void finalize() throws Throwable {
194     release(true); // we explicitly lose the lock here.
195     super.finalize();
196   }
197   public RandomAccessFile getRaFile() throws IOException {
198     if (isLocked() && openRaFile()) {
199       return rafile;
200     }
201     log.debug("Failed to getRaFile on target "+target);
202     return null;
203   }
204   public FileChannel getRaChannel() throws IOException {
205     if (isLocked() && openRaFile()) {
206       return rafile.getChannel();
207     }
208     log.debug("Failed to getRaChannel on target "+target);
209     return null;
210   }
211 }