implementing minimal set : SimpleClientFactory createSession method -> SimpleClient...
[vamsas.git] / src / org / vamsas / client / simpleclient / VamsasSession.java
1 package org.vamsas.client.simpleclient;
2
3 import java.io.BufferedWriter;
4 import java.io.File;
5 import java.io.IOException;
6 import java.io.PrintStream;
7 import java.io.PrintWriter;
8 import java.io.Writer;
9
10 import org.apache.commons.logging.Log;
11 import org.apache.commons.logging.LogFactory;
12 import org.apache.log4j.Appender;
13 import org.apache.log4j.Logger;
14 import org.apache.log4j.FileAppender;
15 import org.vamsas.client.ClientHandle;
16 import org.vamsas.client.UserHandle;
17 /**
18  * Holds the file handlers and watchers for a session.
19  * 
20  * TODO: delete the stuff below - prolly irrelevant now
21  * Vamsas client is intialised with a path to create live session directories. 
22  * This path may contain a vamsas.properties file 
23  * that sets additional parameters (otherwise client 
24  * just uses the one on the classpath).
25  * 
26  * A vamsas session consists of :
27  *  SessionDir - translates to urn of a live session.
28  *  Contains: Vamsas Document (as a jar), Session client list file, 
29  *  both of which may be locked, and additional 
30  *  temporary versions of these files when write 
31  *  operations are taking place.
32  * 
33  * Zip file entries
34  *  - vamsasdocument.xml : core info
35  *  one or more:
36  *  - <applicationname>.version.sessionnumber.raw (string given in vamsasdocument.xml applicationData entry)
37  *  
38  * Lockfile
39  *  - filename given in the vamsasdocument.xml. Should be checked for validity by any client and rewritten if necessary. 
40  *    The lockfile can point to the jar itself.
41  * Mode of operation.
42  * Initially - documentHandler either:
43  *  - creates a zip for a new session for the client
44  *  - connect to an existing session zip 
45  *   1. reads session urn file
46  *   2. waits for lock
47  *   3. examines session - decide whether to create new application data slice or connect to one stored in session.
48  *   4. writes info into session file
49  *   5. releases lock and generates local client events.
50  *   6. Creates Watcher thread to generate events.
51  * 
52  * During the session
53  *  - Update watcher checks for file change - 
54  * 
55  */
56
57 public class VamsasSession {
58   /**
59    * indicator file for informing other processes that 
60    * they should finalise their vamsas datasets for 
61    * storing into a vamsas archive.
62    */
63   public static final String CLOSEANDSAVE_FILE="stored.log";
64   /**
65    * log file location
66    */
67   public static final String SESSION_LOG="Log.txt";
68   private static Log log = LogFactory.getLog(VamsasSession.class);
69   protected Logger slog = Logger.getLogger("org.vamsas.client.SessionLog");
70   /**
71    * setup the sessionLog using Log4j.
72    * @throws IOException
73    */
74   private void initLog() throws IOException {
75     // TODO: LATER: make dedicated appender format for session log.
76     Appender app = slog.getAppender("SESSION_LOG");
77     slog.addAppender(new FileAppender(app.getLayout(), new File(sessionDir, SESSION_LOG).getAbsolutePath()));
78   }
79   
80   /**
81    * the sessionDir is given as the session location for new clients.
82    */
83   File sessionDir;
84   /**
85    * holds the list of attached clients
86    */
87   ClientsFile clist;
88   public static final String CLIENT_LIST="Clients.obj";
89   /**
90    * holds the data
91    */
92   VamsasFile vamArchive; 
93   public static final String VAMSAS_OBJ="VamDoc.jar";
94   
95   /**
96    * sets up the vamsas session files and watchers in sessionDir
97    * @param sessionDir
98    */
99   protected VamsasSession(File sessionDir) throws IOException {
100     if (sessionDir==null)
101       throw new Error("Null directory for VamsasSession.");
102     if (sessionDir.exists()) {
103       if (!sessionDir.isDirectory() || !sessionDir.canWrite() || sessionDir.canRead())
104         throw new IOException("Cannot access '"+sessionDir+"' as a read/writable Directory.");
105       if (checkSessionFiles(sessionDir)) {
106         // session files exist in the directory
107         this.sessionDir = sessionDir;
108         initSessionObjects();
109         slog.debug("Initialising additional VamsasSession instance");
110         log.debug("Attached to VamsasSession in "+sessionDir);
111       } 
112     } else {
113       // start from scratch
114       if (!sessionDir.mkdir())
115         throw new IOException("Failed to make VamsasSession directory in "+sessionDir);
116       this.sessionDir = sessionDir; 
117       createSessionFiles();
118       createDummyVamsasDocument();
119       initSessionObjects();
120       slog.debug("Session directory created.");
121       log.debug("Initialised VamsasSession in "+sessionDir);
122     }
123   }
124   /**
125    * tests presence of existing sessionfiles files in dir
126    * @param dir
127    * @return
128    */
129   private boolean checkSessionFiles(File dir) throws IOException {
130     File c_file = new File(dir,CLIENT_LIST);
131     File v_doc = new File(dir,VAMSAS_OBJ);
132     if (c_file.exists() && v_doc.exists())
133       return true;
134     return false;
135   }
136   /**
137    * create new empty files in dir
138    *
139    */
140   private void createSessionFiles() throws IOException {
141     if (sessionDir==null)
142       throw new IOException("Invalid call to createSessionFiles() with null sessionDir");
143     File c_file = new File(sessionDir,CLIENT_LIST);
144     File v_doc = new File(sessionDir,VAMSAS_OBJ);
145     if (c_file.createNewFile())
146       log.debug("Created new ClientFile "+c_file); // don't care if this works or not
147     if (v_doc.createNewFile())
148       log.debug("Created new Vamsas Session Document File "+v_doc); 
149   }
150   /**
151    * construct SessionFile objects and watchers for each
152    */
153   private void initSessionObjects() throws IOException {
154     if (clist!=null || vamArchive!=null)
155       throw new IOException("initSessionObjects called for initialised VamsasSession object.");
156     clist = new ClientsFile(new File(sessionDir,CLIENT_LIST));
157     vamArchive = new VamsasFile(new File(sessionDir,VAMSAS_OBJ));
158     initLog();
159   }
160   /**
161    * make a new watcher object for the clientFile
162    * @return new ClientFile watcher instance
163    */
164   public FileWatcher getClientWatcher() {
165     return new FileWatcher(clist.sessionFile);
166   }
167   /**
168    * make a new watcher object for the vamsas Document
169    * @return new ClientFile watcher instance
170    */
171   public FileWatcher getDocWatcher() {
172     return new FileWatcher(vamArchive.sessionFile);
173   }
174   FileWatcher store_doc_file=null;
175   /**
176    * make a new watcher object for the messages file
177    * @return new watcher instance
178    */
179   public FileWatcher getStoreWatcher() {
180     return store_doc_file = new FileWatcher(new File(CLOSEANDSAVE_FILE));
181   }
182   /**
183    * write to the StoreWatcher file to indicate that a storeDocumentRequest has been made.
184    * The local client's storeWatcher FileWatcher object is updated so the initial change is not registered.
185    * @param client
186    * @param user
187    * @return
188    */
189   public void addStoreDocumentRequest(ClientHandle client, UserHandle user) throws IOException {
190     SessionFile sfw = new SessionFile(new File(sessionDir, CLOSEANDSAVE_FILE));
191     while (!sfw.lockFile())
192       log.debug("Trying to get lock for "+CLOSEANDSAVE_FILE);
193     sfw.fileLock.rafile.setLength(0); // wipe out any old info.
194     // TODO: rationalise what gets written to this file (ie do we want other clients to read the id of the requestor?)
195     sfw.fileLock.rafile.writeUTF(client.getClientUrn()+":"+user.getFullName()+"@"+user.getOrganization());
196     sfw.unlockFile();
197     if (store_doc_file!=null)
198       store_doc_file.setState();
199     slog.info("FinalizeAppData request from "+user.getFullName()+" using "+client.getClientUrn()+"");
200   }
201   /**
202    * create a new session with an existing vamsas Document - by copying it into the session.
203    * @param archive
204    */
205   protected void setVamsasDocument(File archive) throws IOException {
206     log.debug("Transferring vamsas data from "+archive+" to session:"+vamArchive.sessionFile);
207     SessionFile xtantdoc = new SessionFile(archive);
208     vamArchive.updateFrom(null, xtantdoc);
209     // TODO: LATER: decide if session archive provenance should be updated to reflect access.
210     // TODO: soon! do a proper import objects from external file 
211     log.debug("Transfer complete.");
212   }
213   /**
214    * write session as a new vamsas Document (this will overwrite any existing file without warning)
215    * @param destarchive
216    */
217   protected void writeVamsasDocument(File destarchive, Lock extlock) throws IOException {
218     log.debug("Transferring vamsas data from "+vamArchive.sessionFile+" to session:"+destarchive);
219     SessionFile newdoc = new SessionFile(destarchive);
220     if (extlock==null && !vamArchive.lockFile())
221       while (!vamArchive.lockFile())
222         log.info("Trying to get lock for "+vamArchive.sessionFile);
223     // TODO: LATER: decide if session archive provenance should be written in vamsasDocument file for this export.
224     newdoc.updateFrom(extlock, vamArchive);
225     // TODO: SOON: fix use of updateFrom for file systems where locks cannot be made (because they don't have a lockManager, ie NFS/Unix, etc).
226     vamArchive.unLock();
227     newdoc.unlockFile();
228     log.debug("Transfer complete.");
229   }
230   
231   /**
232    * Creates a VamsasArchive object for accessing and updating document
233    * Note: this will lock the Vamsas Document for exclusive access to the client.
234    * @return session vamsas document
235    * @throws IOException if locks fail or vamsas document read fails.
236    */
237   protected VamsasArchive getVamsasDocument() throws IOException {
238     // TODO: check we haven't already done this once
239     if (!vamArchive.lockFile()) 
240       throw new IOException("Failed to get lock for vamsas archive.");
241     
242     VamsasArchive va = new VamsasArchive(vamArchive.sessionFile, false, true, vamArchive);
243     
244     return va;
245   }
246   
247 }
248
249