updated test cases for spring 2006 schema, and major debug of locking system
[vamsas.git] / src / org / vamsas / client / simpleclient / NativeLock.java
index 96d9b6b..6a624f1 100644 (file)
@@ -7,17 +7,25 @@ import java.io.FileInputStream;
 import java.io.FileNotFoundException;
 import java.io.FileOutputStream;
 import java.io.IOException;
+import java.io.OutputStream;
 import java.io.RandomAccessFile;
+import java.nio.channels.FileChannel;
 import java.nio.channels.FileLock;
+import java.nio.channels.ReadableByteChannel;
 
+/**
+ * @author JimP
+ *
+ */
 public class NativeLock extends Lock {
 
   protected FileLock lock = null;
 
   /**
    * @param lockfile
+   * @param block true means thread will block until a lock is obtained.
    */
-  public NativeLock(File lockfile) {
+  public NativeLock(File lockfile, boolean block) {
     super(lockfile);
     // try and get a lock.
     lock = null;
@@ -29,7 +37,11 @@ public class NativeLock extends Lock {
           return;
         }
       
-      lock = (rafile=new RandomAccessFile(lockfile,"rw")).getChannel().tryLock();
+      rafile=new RandomAccessFile(lockfile,"rw");
+      if (block)
+        lock = rafile.getChannel().lock();
+      else
+        lock = rafile.getChannel().tryLock();
       if (lock==null || !lock.isValid()) {
         // failed to get lock. Close the file channel
         log.debug("failed to get lock for "+lockfile);
@@ -100,9 +112,11 @@ public class NativeLock extends Lock {
   public FileOutputStream getFileOutputStream(boolean clear) throws IOException {
     if (!isLocked())
       return null;
-    if (clear)
+    if (clear) {
+      rafile.seek(0);
       rafile.setLength(0);
-    rafile.seek(rafile.length());
+    } else
+      rafile.seek(rafile.length());
     return new LockedFileOutputStream(rafile.getFD());
   }
 
@@ -112,7 +126,7 @@ public class NativeLock extends Lock {
    * @return
    */
   public BufferedOutputStream getBufferedOutputStream(boolean clear) throws IOException {
-    FileOutputStream fos = getFileOutputStream(clear);
+    OutputStream fos = getFileOutputStream(clear);
     if (fos!=null)
       return new BufferedOutputStream(fos);
     return null;
@@ -126,4 +140,34 @@ public class NativeLock extends Lock {
     super.finalize();
   }
 
+  /* (non-Javadoc)
+   * @see org.vamsas.client.simpleclient.Lock#getLength()
+   */
+  public long length() {
+    if (isLocked()){
+      try {
+        return rafile.length();
+      } catch (Exception e) {
+        log.debug("getLength exception:",e);
+      }
+    }
+    return -1;
+  }
+
+  public RandomAccessFile getRaFile() throws IOException {
+    if (isLocked())
+      return rafile;
+    else
+      log.debug("Failed to getRaFile on "+target);
+    return null;
+  }  
+  
+  public FileChannel getRaChannel() throws IOException {
+    if (isLocked())
+      return rafile.getChannel();
+    else
+      log.debug("Failed to getRaChannel on "+target);
+    return null;
+  }
+
 }