1 package org.vamsas.client.simpleclient;
3 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;
11 public class FileLock extends Lock {
13 protected static String _LockSuffix="lck";
15 * call to clear up a filelock file after its been made
27 public FileLock(File lockfile) {
29 // try and get a lock.
31 _lock = new File(lockfile.getParentFile(), lockfile.getName()+"."+_LockSuffix);
32 if (_lock.exists() || !_lock.createNewFile()) {
33 log.debug("Failed to get lock for "+lockfile+" using lockfile "+_lock);
37 _lock.deleteOnExit(); // safe - all locks should be removed on finalization.
38 // create target file ready to be written to if necessary.
39 if (!lockfile.exists())
40 if (!lockfile.createNewFile()) {
41 log.warn("Failed to create locked file "+lockfile);
45 } catch (FileNotFoundException e) {
47 log.debug("FileLock failed with target="+lockfile+" and lockfile suffix of "+_LockSuffix);
48 //log.error("Error! Couldn't create a lockfile at "
49 // + lockfile.getAbsolutePath(), e);
50 } catch (IOException e) {
51 log.error("Error! Problems with IO when creating a lock on "
52 + lockfile.getAbsolutePath(),e);
56 private boolean openRaFile() throws IOException {
59 if (_lock==null || !_lock.exists())
62 rafile=new RandomAccessFile(target,"rw");
63 return (rafile.getChannel()!=null) && rafile.getChannel().isOpen();
66 public boolean isLocked() {
71 if (log.isDebugEnabled())
72 log.debug("Lockfile "+_lock+" unexpectedly deleted ?");
77 public void release() {
81 public void release(boolean closeChannel) {
88 } catch (Exception e) {
89 log.debug("Unexpected exception whilst closing RandomAccessFile on "+target, e);
96 public FileInputStream getFileInputStream(boolean atStart) throws IOException {
102 return new FileInputStream(rafile.getFD());
106 public FileOutputStream getFileOutputStream(boolean clear) throws IOException {
113 rafile.seek(rafile.length());
114 return new LockedFileOutputStream(rafile.getFD());
118 public BufferedOutputStream getBufferedOutputStream(boolean clear) throws IOException {
119 FileOutputStream fos = getFileOutputStream(clear);
121 return new BufferedOutputStream(fos);
125 protected void finalize() throws Throwable {
126 release(true); // we explicitly lose the lock here.