package org.eclipse.osgi.internal.location;
import java.io.*;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import org.eclipse.osgi.internal.messages.Msg;
import org.eclipse.osgi.util.NLS;
public class Locker_JavaNio implements Locker {
private final File lockFile;
private final boolean debug;
private FileLock fileLock;
private RandomAccessFile raFile;
public Locker_JavaNio(File lockFile, boolean debug) {
this.lockFile = lockFile;
this.debug = debug;
}
@Override
public synchronized boolean lock() throws IOException {
raFile = new RandomAccessFile(lockFile, "rw");
try {
fileLock = raFile.getChannel().tryLock(0, 1, false);
} catch (IOException ioe) {
if (debug)
System.out.println(NLS.bind(Msg.location_cannotLock, lockFile));
String specificMessage = NLS.bind(Msg.location_cannotLockNIO, new Object[] {lockFile, ioe.getMessage(), "\"-D" + LocationHelper.PROP_OSGI_LOCKING + "=none\""});
throw new IOException(specificMessage);
} catch (OverlappingFileLockException e) {
fileLock = null;
} finally {
if (fileLock != null)
return true;
raFile.close();
raFile = null;
}
return false;
}
@Override
public synchronized void release() {
if (fileLock != null) {
try {
fileLock.release();
} catch (IOException e) {
}
fileLock = null;
}
if (raFile != null) {
try {
raFile.close();
} catch (IOException e) {
}
raFile = null;
}
}
@Override
public synchronized boolean isLocked() throws IOException {
if (fileLock != null)
return true;
try {
RandomAccessFile temp = new RandomAccessFile(lockFile, "rw");
FileLock tempLock = null;
try {
try {
tempLock = temp.getChannel().tryLock(0, 1, false);
} catch (IOException ioe) {
if (debug)
System.out.println(NLS.bind(Msg.location_cannotLock, lockFile));
String specificMessage = NLS.bind(Msg.location_cannotLockNIO, new Object[] {lockFile, ioe.getMessage(), "\"-D" + LocationHelper.PROP_OSGI_LOCKING + "=none\""});
throw new IOException(specificMessage);
}
if (tempLock != null) {
tempLock.release();
return false;
}
return true;
} catch (OverlappingFileLockException e) {
return true;
} finally {
temp.close();
}
} catch (FileNotFoundException e) {
return false;
}
}
}