27f83c7ee2bcd0247ee5fd5ec4daed5977fbddb2
[vamsas.git] / src / uk / ac / vamsas / client / simpleclient / SessionFlagFile.java
1 package uk.ac.vamsas.client.simpleclient;
2
3 import java.io.File;
4
5 import org.apache.commons.logging.Log;
6 import org.apache.commons.logging.LogFactory;
7
8 /**
9  * methods for setting and checking 
10  * binary flags in a vamsas session directory.
11  * all methods apart from the constructor will 
12  * throw a fatal error if the flagFile is not
13  * a valid java.io.File object.
14  * LATER: extract SessionFlag interface for generalizing the vamsas session code 
15  * @author jimp
16  *
17  */
18 public class SessionFlagFile {
19   private static Log log = LogFactory.getLog(SessionFlagFile.class);
20   protected File flagFile=null;
21   private void checkFlagFile() {
22     if (flagFile==null) {
23       log.fatal("Implementation error - uninitialized SessionFlagFile", 
24           new Error("Implementation error - uninitialized SessionFlagFile"));
25     }
26   }
27   /**
28    * will log a warning if exceptions occur during flag creation.
29    * @return true if flag was set successfully
30    */
31   public boolean setFlag() {
32     checkFlagFile();
33     try {
34       if (flagFile.createNewFile()) {
35         log.debug("Set session flag "+flagFile);
36       } else {
37         log.debug("Session flag already set "+flagFile);
38       }
39       return true;
40     }
41     catch (Exception e) {
42       log.warn("Couldn't set session flag "+flagFile, e);
43     }
44     return false;
45   }
46   /**
47    * 
48    * @return true if flag was cleared successfully
49    */
50   public boolean clearFlag() {
51     checkFlagFile();
52     if (flagFile.exists()) {
53       log.debug("clearing session flag "+flagFile);
54       if (!flagFile.delete()) {
55         log.warn("failed to clear session flag "+flagFile);
56         return false;
57       }
58     } else {
59       log.debug("clearFlag called for already cleared flag "+flagFile);
60     }
61     return true;
62   }
63     /**
64      * 
65      * @return state of session flag
66      */
67   public boolean checkFlag() {
68     checkFlagFile();
69     if (flagFile.exists()) {
70       if (log.isDebugEnabled())
71         log.debug("Flag '"+flagFile+"' is set.");
72       return true;
73     }
74     if (log.isDebugEnabled())
75       log.debug("Flag '"+flagFile+"' is not set.");    
76     return false;
77   }
78     /**
79      * @param flagFile
80      */
81     public SessionFlagFile(File flagFile) {
82       super();
83       this.flagFile = flagFile;
84     };
85 }