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 boolean lockFile(Lock extantlock) {
20 if (fileLock!=null && !fileLock.isLocked()) {
21 fileLock.release();// tidy up invalid lock
28 * Get a lock for the SessionFile
30 * @return true if lock was made
32 protected boolean lockFile() {
34 if (fileLock.isLocked())
37 // lock failed for some reason.
40 if (sessionFile != null) {
41 if (sessionFile.exists()) {
42 // TODO: see if we need to loop-wait for locks or they just block until
47 fileLock = new Lock(sessionFile); // TODO: wait around if we can't get the lock.
48 } while (!fileLock.isLocked());
49 // fileLock = new Lock(sessionFile);
50 return fileLock.isLocked();
54 "org.vamsas.client.simpleclient.ClientsFile.lockList called for non-initialised ClientsFile!");
61 * Explicitly release the SessionFile's lock.
63 * @return true if lock was released.
65 protected void unlockFile() {
66 if (fileLock != null) {
73 * Makes a backup of the sessionFile.
74 * @return Backed up SessionFile or null if failed to make backup.
76 protected File backupSessionFile() {
77 return backupSessionFile(null, sessionFile.getName(),".old", sessionFile.getParentFile());
80 protected File backupSessionFile(Lock extantLock, String backupPrefix, String backupSuffix, File backupDir) {
82 if (lockFile(extantLock)) {
84 tempfile = File.createTempFile(backupPrefix, backupSuffix, backupDir);
85 FileOutputStream tos = new FileOutputStream(tempfile);
86 tos.getChannel().transferFrom(fileLock.rafile.getChannel(), 0,
87 fileLock.rafile.length());
89 } catch (FileNotFoundException e1) {
90 System.err.println("Can't create temp file for "+sessionFile.getName());
91 e1.printStackTrace(System.err);
93 } catch (IOException e1) {
95 .println("Error when copying content to temp file for "+sessionFile.getName());
96 e1.printStackTrace(System.err);