1 package org.vamsas.client.simpleclient;
4 import java.io.FileNotFoundException;
5 import java.io.FileOutputStream;
6 import java.io.IOException;
8 import org.apache.commons.logging.Log;
9 import org.apache.commons.logging.LogFactory;
10 import org.apache.commons.logging.impl.Log4jFactory;
13 * Basic methods for classes handling locked IO on files
14 * monitored by all (simpleclient) clients in a vamsas session.
18 public class SessionFile {
19 private static Log log = LogFactory.getLog(SessionFile.class);
20 protected File sessionFile;
21 protected Lock fileLock = null;
23 protected SessionFile(File file) {
28 protected boolean lockFile(Lock extantlock) {
29 if (fileLock!=null && !fileLock.isLocked()) {
30 fileLock.release();// tidy up invalid lock
37 * Get a lock for the SessionFile
39 * @return true if lock was made
41 protected boolean lockFile() {
43 if (fileLock.isLocked())
46 // lock failed for some reason.
49 if (sessionFile != null) {
50 if (sessionFile.exists()) {
51 // TODO: see if we need to loop-wait for locks or they just block until
56 fileLock = new Lock(sessionFile); // TODO: wait around if we can't get the lock.
57 } while (!fileLock.isLocked());
58 // fileLock = new Lock(sessionFile);
59 return fileLock.isLocked();
62 log.error("lockFile called for non-initialised SessionFile!");
69 * Explicitly release the SessionFile's lock.
71 * @return true if lock was released.
73 protected void unlockFile() {
74 if (fileLock != null) {
81 * Makes a backup of the sessionFile.
82 * @return Backed up SessionFile or null if failed to make backup.
84 protected File backupSessionFile() {
85 return backupSessionFile(null, sessionFile.getName(),".old", sessionFile.getParentFile());
88 protected File backupSessionFile(Lock extantLock, String backupPrefix, String backupSuffix, File backupDir) {
90 if (lockFile(extantLock)) {
92 tempfile = File.createTempFile(backupPrefix, backupSuffix, backupDir);
93 FileOutputStream tos = new FileOutputStream(tempfile);
94 tos.getChannel().transferFrom(fileLock.rafile.getChannel(), 0,
95 fileLock.rafile.length());
97 } catch (FileNotFoundException e1) {
98 log.warn("Can't create temp file for "+sessionFile.getName(),e1);
100 } catch (IOException e1) {
101 log.warn("Error when copying content to temp file for "+sessionFile.getName(),e1);
108 * Replaces data in sessionFile with data from file handled by another sessionFile
109 * passes up any exceptions.
110 * @param newData source for new data
112 protected void updateFrom(Lock extantLock, SessionFile newData) throws IOException {
113 log.debug("Updating "+sessionFile.getAbsolutePath()+" from "+newData.sessionFile.getAbsolutePath());
115 throw new IOException("Null newData object.");
116 if (newData.sessionFile!=null)
117 throw new IOException("Null SessionFile in newData.");
119 lockFile(extantLock);
121 fileLock.rafile.getChannel().transferFrom(newData.fileLock.rafile.getChannel(), 0,
122 newData.fileLock.rafile.length());