SimpleClient creates dummy documents.
[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       initSessionObjects();
119       slog.debug("Session directory created.");
120       log.debug("Initialised VamsasSession in "+sessionDir);
121     }
122   }
123   /**
124    * tests presence of existing sessionfiles files in dir
125    * @param dir
126    * @return
127    */
128   private boolean checkSessionFiles(File dir) throws IOException {
129     File c_file = new File(dir,CLIENT_LIST);
130     File v_doc = new File(dir,VAMSAS_OBJ);
131     if (c_file.exists() && v_doc.exists())
132       return true;
133     return false;
134   }
135   /**
136    * create new empty files in dir
137    *
138    */
139   private void createSessionFiles() throws IOException {
140     if (sessionDir==null)
141       throw new IOException("Invalid call to createSessionFiles() with null sessionDir");
142     File c_file = new File(sessionDir,CLIENT_LIST);
143     File v_doc = new File(sessionDir,VAMSAS_OBJ);
144     if (c_file.createNewFile())
145       log.debug("Created new ClientFile "+c_file); // don't care if this works or not
146     if (v_doc.createNewFile())
147       log.debug("Created new Vamsas Session Document File "+v_doc); 
148   }
149   /**
150    * construct SessionFile objects and watchers for each
151    */
152   private void initSessionObjects() throws IOException {
153     if (clist!=null || vamArchive!=null)
154       throw new IOException("initSessionObjects called for initialised VamsasSession object.");
155     clist = new ClientsFile(new File(sessionDir,CLIENT_LIST));
156     vamArchive = new VamsasFile(new File(sessionDir,VAMSAS_OBJ));
157     initLog();
158   }
159   /**
160    * make a new watcher object for the clientFile
161    * @return new ClientFile watcher instance
162    */
163   public FileWatcher getClientWatcher() {
164     return new FileWatcher(clist.sessionFile);
165   }
166   /**
167    * make a new watcher object for the vamsas Document
168    * @return new ClientFile watcher instance
169    */
170   public FileWatcher getDocWatcher() {
171     return new FileWatcher(vamArchive.sessionFile);
172   }
173   FileWatcher store_doc_file=null;
174   /**
175    * make a new watcher object for the messages file
176    * @return new watcher instance
177    */
178   public FileWatcher getStoreWatcher() {
179     return store_doc_file = new FileWatcher(new File(CLOSEANDSAVE_FILE));
180   }
181   /**
182    * write to the StoreWatcher file to indicate that a storeDocumentRequest has been made.
183    * The local client's storeWatcher FileWatcher object is updated so the initial change is not registered.
184    * @param client
185    * @param user
186    * @return
187    */
188   public void addStoreDocumentRequest(ClientHandle client, UserHandle user) throws IOException {
189     SessionFile sfw = new SessionFile(new File(sessionDir, CLOSEANDSAVE_FILE));
190     while (!sfw.lockFile())
191       log.debug("Trying to get lock for "+CLOSEANDSAVE_FILE);
192     sfw.fileLock.rafile.setLength(0); // wipe out any old info.
193     // TODO: rationalise what gets written to this file (ie do we want other clients to read the id of the requestor?)
194     sfw.fileLock.rafile.writeUTF(client.getClientUrn()+":"+user.getFullName()+"@"+user.getOrganization());
195     sfw.unlockFile();
196     if (store_doc_file!=null)
197       store_doc_file.setState();
198     slog.info("FinalizeAppData request from "+user.getFullName()+" using "+client.getClientUrn()+"");
199   }
200   /**
201    * create a new session with an existing vamsas Document - by copying it into the session.
202    * @param archive
203    */
204   protected void setVamsasDocument(File archive) throws IOException {
205     log.debug("Transferring vamsas data from "+archive+" to session:"+vamArchive.sessionFile);
206     SessionFile xtantdoc = new SessionFile(archive);
207     vamArchive.updateFrom(null, xtantdoc);
208     // TODO: LATER: decide if session archive provenance should be updated to reflect access.
209     // TODO: soon! do a proper import objects from external file 
210     log.debug("Transfer complete.");
211   }
212   /**
213    * write session as a new vamsas Document (this will overwrite any existing file without warning)
214    * @param destarchive
215    */
216   protected void writeVamsasDocument(File destarchive, Lock extlock) throws IOException {
217     log.debug("Transferring vamsas data from "+vamArchive.sessionFile+" to session:"+destarchive);
218     SessionFile newdoc = new SessionFile(destarchive);
219     if (extlock==null && !vamArchive.lockFile())
220       while (!vamArchive.lockFile())
221         log.info("Trying to get lock for "+vamArchive.sessionFile);
222     // TODO: LATER: decide if session archive provenance should be written in vamsasDocument file for this export.
223     newdoc.updateFrom(extlock, vamArchive);
224     // 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).
225     vamArchive.unLock();
226     newdoc.unlockFile();
227     log.debug("Transfer complete.");
228   }
229   
230   /**
231    * Creates a VamsasArchive object for accessing and updating document
232    * Note: this will lock the Vamsas Document for exclusive access to the client.
233    * @return session vamsas document
234    * @throws IOException if locks fail or vamsas document read fails.
235    */
236   protected VamsasArchive getVamsasDocument() throws IOException {
237     // TODO: check we haven't already done this once
238     if (!vamArchive.lockFile()) 
239       throw new IOException("Failed to get lock for vamsas archive.");
240     
241     VamsasArchive va = new VamsasArchive(vamArchive.sessionFile, false, true, vamArchive);
242     
243     return va;
244   }
245   
246 }
247
248