1 package org.vamsas.client.simpleclient;
4 import java.io.FileNotFoundException;
5 import java.io.FileOutputStream;
6 import java.io.IOException;
9 * Basic methods for classes handling locked IO on files
10 * monitored by all (simpleclient) clients in a vamsas session.
14 public class SessionFile {
16 protected File sessionFile;
17 protected Lock fileLock = null;
19 protected SessionFile(File file) {
24 protected boolean lockFile(Lock extantlock) {
25 if (fileLock!=null && !fileLock.isLocked()) {
26 fileLock.release();// tidy up invalid lock
33 * Get a lock for the SessionFile
35 * @return true if lock was made
37 protected boolean lockFile() {
39 if (fileLock.isLocked())
42 // lock failed for some reason.
45 if (sessionFile != null) {
46 if (sessionFile.exists()) {
47 // TODO: see if we need to loop-wait for locks or they just block until
52 fileLock = new Lock(sessionFile); // TODO: wait around if we can't get the lock.
53 } while (!fileLock.isLocked());
54 // fileLock = new Lock(sessionFile);
55 return fileLock.isLocked();
59 "org.vamsas.client.simpleclient.SessionFile.lockFile called for non-initialised SessionFile!");
66 * Explicitly release the SessionFile's lock.
68 * @return true if lock was released.
70 protected void unlockFile() {
71 if (fileLock != null) {
78 * Makes a backup of the sessionFile.
79 * @return Backed up SessionFile or null if failed to make backup.
81 protected File backupSessionFile() {
82 return backupSessionFile(null, sessionFile.getName(),".old", sessionFile.getParentFile());
85 protected File backupSessionFile(Lock extantLock, String backupPrefix, String backupSuffix, File backupDir) {
87 if (lockFile(extantLock)) {
89 tempfile = File.createTempFile(backupPrefix, backupSuffix, backupDir);
90 FileOutputStream tos = new FileOutputStream(tempfile);
91 tos.getChannel().transferFrom(fileLock.rafile.getChannel(), 0,
92 fileLock.rafile.length());
94 } catch (FileNotFoundException e1) {
95 System.err.println("Can't create temp file for "+sessionFile.getName());
96 e1.printStackTrace(System.err);
98 } catch (IOException e1) {
100 .println("Error when copying content to temp file for "+sessionFile.getName());
101 e1.printStackTrace(System.err);