1 package org.vamsas.client.simpleclient;
3 import java.io.BufferedInputStream;
4 import java.io.BufferedOutputStream;
6 import java.io.FileInputStream;
7 import java.io.FileNotFoundException;
8 import java.io.FileOutputStream;
9 import java.io.IOException;
10 import java.io.RandomAccessFile;
11 import java.nio.channels.FileLock;
13 public class NativeLock extends Lock {
15 protected FileLock lock = null;
20 public NativeLock(File lockfile) {
22 // try and get a lock.
26 if (!lockfile.exists())
27 if (!lockfile.createNewFile()) {
28 log.warn("Failed to create locked file "+lockfile);
32 lock = (rafile=new RandomAccessFile(lockfile,"rw")).getChannel().tryLock();
33 if (lock==null || !lock.isValid()) {
34 // failed to get lock. Close the file channel
35 log.debug("failed to get lock for "+lockfile);
36 rafile.getChannel().close();
39 } catch (FileNotFoundException e) {
41 log.debug("Lock failed - normal behaviour for windows locking.");
42 //log.error("Error! Couldn't create a lockfile at "
43 // + lockfile.getAbsolutePath(), e);
44 } catch (IOException e) {
45 log.error("Error! Problems with IO when creating a lock on "
46 + lockfile.getAbsolutePath(),e);
50 public boolean isLocked() {
51 if (lock != null && lock.isValid()) {
57 public void release() {
61 public void release(boolean closeChannel) {
63 // channel.close should be called before release() for rigourous locking.
64 if (rafile!=null && rafile.getFD().valid() && rafile.getChannel()!=null && lock.isValid()) {
65 if (closeChannel && rafile.getChannel().isOpen()) {
69 if (lock!=null && lock.isValid())
73 } catch (IOException e) {
74 log.warn("Whilst releasing lock",e);
80 * gets Locked Stream for reading from
81 * @param atStart true to start reading at beginning of file.
82 * @return null if file not locked
85 public FileInputStream getFileInputStream(boolean atStart) throws IOException {
90 return new FileInputStream(rafile.getFD());
94 * gets Locked stream to write to
95 * FileInput always starts at the *end* of the file (after any truncation)
96 * @param clear true means file will be cleared to zero length
97 * @return null if file is not locked
100 public FileOutputStream getFileOutputStream(boolean clear) throws IOException {
105 rafile.seek(rafile.length());
106 return new LockedFileOutputStream(rafile.getFD());
110 * return buffered output stream to locked file.
111 * @param clear - true means file is truncated to 0 length before writing
114 public BufferedOutputStream getBufferedOutputStream(boolean clear) throws IOException {
115 FileOutputStream fos = getFileOutputStream(clear);
117 return new BufferedOutputStream(fos);
121 * @see org.vamsas.client.simpleclient.Lock#finalize()
123 protected void finalize() throws Throwable {
124 release(true); // we explicitly lose the lock here.
125 // log.debug("lock closing through garbage collection ?");