Moves sessionFile management to SimpleSessionManager calling SessionsFile class...
[vamsas.git] / src / uk / ac / vamsas / client / simpleclient / SimpleClientFactory.java
1 /*
2 * VAMSAS Project
3 *
4
5
6 * Dec 13, 2006 
7 *
8 */
9  
10 package uk.ac.vamsas.client.simpleclient;
11
12 import java.io.File;
13
14 import java.io.IOException;
15 import java.net.MalformedURLException;
16
17
18 import org.apache.commons.logging.Log;
19 import org.apache.commons.logging.LogFactory;
20
21 import uk.ac.vamsas.client.ClientHandle;
22 import uk.ac.vamsas.client.IClient;
23 import uk.ac.vamsas.client.IClientFactory;
24 import uk.ac.vamsas.client.InvalidSessionUrnException;
25 import uk.ac.vamsas.client.NoDefaultSessionException;
26 import uk.ac.vamsas.client.SessionHandle;
27 import uk.ac.vamsas.client.UserHandle;
28
29 /**
30  * 
31  * creates a session arena in the user home directory under .vamsas.
32  * Each session has its own subdirectory.
33  */
34 public class SimpleClientFactory implements IClientFactory {
35
36   private static Log log = LogFactory.getLog(SimpleClientFactory.class);
37
38   private File sessionArena = null;
39   
40   private String vamsasSubdirectoryName = ".vamsas";
41   
42  private SimpleSessionManager sessionManager = null;
43   private static final String SESSION_LIST="sessions.obj";
44   
45   //private   String[] currentlyAvailableDessions = null; 
46   
47   /**
48    * default constructor - called by CreateClientFactory only.
49    *
50    *Inits the sessionarena to the directory .vamsas of the user home directory. 
51    *
52    */
53   public SimpleClientFactory() throws IOException
54   {
55    // sessionArena
56     
57     //retrieves user home directory
58     String userHomeDirectory = System.getProperty("user.home");
59     if (userHomeDirectory == null || userHomeDirectory.length()<1)
60       {
61         new IOException("Unable to detect user home directory");
62       }
63     String sessionArenaPath =  userHomeDirectory.concat(File.separator.concat(this.vamsasSubdirectoryName));
64     
65     this.initSessionArena(sessionArenaPath);
66    // this.initFactoryObjects();
67   }
68   
69   
70   /**
71    * Create a client factory that works with sessions at the given
72    * path.
73    * @param path path to directory called  session arena, where will be created session directories and session files.
74    */
75   public SimpleClientFactory(String path) throws IOException
76   {
77     this.initSessionArena(path);
78   }
79   /**
80    * Inits sessionArena to a given path.
81    * checks if path is valid.
82    * 
83    * @param path path to a directory to use 
84    * @throws IOException if the path is incorrect
85    */
86   private void  initSessionArena (String path) throws IOException
87   {
88     // Check path is valid and read/writeable.
89     File arenaFile = new File (path);
90     if (!arenaFile.exists())
91     {
92       if (! arenaFile.mkdirs())
93       {
94         this.sessionArena = null;
95         throw(new IOException("Unable to create a directory called "+path));
96       }
97     }
98     if (arenaFile.exists() && arenaFile.isDirectory() && arenaFile.canRead() && arenaFile.canWrite()) 
99       {
100         this.sessionArena = arenaFile;
101       } 
102     else
103       {
104       this.sessionArena = null;
105         throw(new IOException("Cannot read and write to a directory called "+path));
106       }
107   }
108   
109   
110
111   
112
113   /**
114    * @see uk.ac.vamsas.client.IClientFactory#getIClient(uk.ac.vamsas.client.ClientHandle)
115    * 
116    * Creates a IClient object, using default UserHandle with system variables:"user.name" or "USERNAME")),
117             "host.name" or "HOSTNAME" 
118    */
119   public IClient getIClient(ClientHandle applicationHandle)
120       throws NoDefaultSessionException {
121     // create a new session
122     // register new ClientHandle in session
123     // create SimpleClient instance
124     return this.getIClient(applicationHandle, (UserHandle) null);
125   }
126
127   /**
128    * the URN should be something like simpleclient:FILEPATH URL encoded
129    * @see uk.ac.vamsas.client.IClientFactory#getIClient(uk.ac.vamsas.client.ClientHandle, java.lang.String)
130    */
131   public IClient getIClient(ClientHandle applicationHandle, String sessionUrn) {
132 //  locate session from Urn
133     // check that clientHandle is unique (with default user) - if not update the clientHandle urn to make it unique.
134     // wait for lock and attach to session
135     // create SimpleClient instance
136     log.debug("Trying to create session with URN "+sessionUrn);
137     return this.getIClient(applicationHandle, null, sessionUrn);
138   
139   }
140
141   private File convertSessionUrnToFile(String sessionUrn) throws InvalidSessionUrnException
142   {
143     if (sessionUrn == null)
144       {
145         log.debug("Incorrect URN: can not open session.");
146         throw new InvalidSessionUrnException();
147       }
148     
149     SessionUrn urn = new SessionUrn(sessionUrn);
150    return urn.asFile();
151     
152   }
153   
154   /**
155    * @see uk.ac.vamsas.client.IClientFactory#getIClient(uk.ac.vamsas.client.ClientHandle, uk.ac.vamsas.client.UserHandle, java.lang.String)
156    */
157   public IClient getIClient(ClientHandle applicationHandle, UserHandle userId,
158       String sessionUrn) {
159 //  locate session from Urn
160     // check Uniqueness of user + ClientHandle in the session. Update clientHandle urn accordingly.
161     // wait for lock, attach to session
162     // create client instance
163     IClient client = null;
164     
165     try {
166       File sessionDirectory = this.convertSessionUrnToFile(sessionUrn);
167       //create session
168       log.debug("found session directory "+sessionDirectory.getAbsolutePath());
169       VamsasSession vamsasSession = new VamsasSession(sessionDirectory);
170  
171    /*   if (userId == null)
172         {
173         //create a default userHandle
174         //with current OS user and hostname
175           userId = new UserHandle(System.getProperty("user.name", System.getProperty("USERNAME","Joe Doe")),
176               System.getProperty("host.name",System.getProperty("HOSTNAME", "Unknown") ));// clientName, clientVersion,  sessionPath);
177         }
178  
179  
180  //create simple client
181        client = new SimpleClient(userId,  applicationHandle,  vamsasSession);*/
182       client = this.initClient(sessionDirectory, userId, applicationHandle);
183     } catch (MalformedURLException e) {
184       log.error("error while creating new IClient: incorrect session urn",e);
185       client = null;
186      
187     } catch (InvalidSessionUrnException e) {
188       log.error("error while creating new IClient: incorrect session urn",e);
189       client = null;
190     } catch (IOException e) {
191       log.error("error while creating new IClient: file access error",e);
192       client = null;
193     }
194     return client;
195   }
196
197   
198   private IClient initClient( File sessdir, UserHandle userId, ClientHandle clientHandle) throws IOException, InvalidSessionUrnException
199   {
200     IClient client = null;
201 //  create session
202     VamsasSession vamsasSession = new VamsasSession(sessdir);
203   
204     this.getSessionManager().addSession(new SessionHandle(new SessionUrn(vamsasSession).getSessionUrn()));
205     if (userId == null)
206       {
207   //create a default userHandle
208   //with current OS user and hostname
209         userId = new UserHandle(System.getProperty("user.name", System.getProperty("USERNAME","Joe Doe")),
210           System.getProperty("host.name",System.getProperty("HOSTNAME", "Unknown") ));// clientName, clientVersion,  sessionPath);
211       }
212  
213   
214   //create simple client
215      client = new SimpleClient(userId,  clientHandle,  vamsasSession);
216      vamsasSession.addClient(client);
217      vamsasSession.setSessionManager(this.getSessionManager());
218      return client;
219   }
220   /**
221    * @see uk.ac.vamsas.client.IClientFactory#getIClient(uk.ac.vamsas.client.ClientHandle, uk.ac.vamsas.client.UserHandle)
222    */
223   public IClient getIClient(ClientHandle applicationHandle, UserHandle userId)
224       throws NoDefaultSessionException {
225     // create new session
226     // register SimpleClient and UserHandles in session
227     // create client instance
228     IClient client = null;
229     if (this.sessionArena==null)
230       throw new Error("Improperly initialised SimpleClientFactory object - null sessionArena.");
231     
232     ClientHandle clientHandle =applicationHandle;
233     //create default clientHandle with "SimpleVamsasClientApp","0.1",
234     if (clientHandle == null)
235      clientHandle = new ClientHandle("SimpleVamsasClientApp","0.1");
236     
237     //check if any available session(s)
238     String[] availableSessions = this.getCurrentSessions();
239     if (availableSessions != null) 
240       {//there are available sessions
241         if (availableSessions.length>1)
242           {//more than one session if available... can not choose
243           
244           //represents list of session as String
245             StringBuffer sessionURNs = new StringBuffer("");
246             for (int i = 0; i< availableSessions.length ; i++)
247               {
248                 sessionURNs.append(availableSessions[i]+" ");
249               }
250             throw new  NoDefaultSessionException("Several sessions available, please pick one: "+sessionURNs);
251           }
252       
253         //check if only one session available. if yes, open it
254         if (availableSessions.length == 1)
255           {
256           //only one session available, open it.
257             return this.getIClient(clientHandle,  availableSessions[0]);
258           }
259       }
260     //no session available  - create a new one
261     
262     
263     try 
264       {
265         //create sessionDirectory
266         File sessdir = File.createTempFile("sess", ".simpleclient", this.sessionArena);
267         log.debug("Creating new session  directory");
268        if (!(sessdir.delete() && sessdir.mkdir()))
269           throw new IOException("Could not make session directory "+sessdir);
270       //create session
271      /*   VamsasSession vamsasSession = new VamsasSession(sessdir);
272       
273         this.getSessionFile().addSession(new SessionHandle(new SessionUrn(vamsasSession).getSessionUrn()), false);
274         if (userId == null)
275           {
276       //create a default userHandle
277       //with current OS user and hostname
278             userId = new UserHandle(System.getProperty("user.name", System.getProperty("USERNAME","Joe Doe")),
279               System.getProperty("host.name",System.getProperty("HOSTNAME", "Unknown") ));// clientName, clientVersion,  sessionPath);
280           }
281      
282       
283       //create simple client
284          client = new SimpleClient(userId,  clientHandle,  vamsasSession);*/
285        client = this.initClient(sessdir, userId, clientHandle);
286       } 
287     catch (IOException e) 
288       {
289         log.error("error while creating new IClient",e);
290       }
291     catch (InvalidSessionUrnException e) 
292       {
293         log.error("Unable to create new IClient. The session urn is incorrect ",e);
294       }
295    
296       return client;
297   }
298
299
300   /**
301    * @see uk.ac.vamsas.client.IClientFactory#getCurrentSessions()
302    */
303   public String[] getCurrentSessions() {
304     String [] sessions = null;
305     try {
306       sessions =this.getSessionManager().getCurrentSessions();
307     } catch (IOException e) {
308      log.error("Unable to get available sessions",e);
309      sessions = null;
310     }
311     return sessions;
312   }
313
314
315   /**
316    * @return the sessionFile
317    */
318   private SimpleSessionManager getSessionManager()  throws IOException
319     {
320       if (this.sessionManager == null)
321         {
322           this.sessionManager = new SimpleSessionManager( new File (this.sessionArena, SESSION_LIST));
323         }
324       return this.sessionManager;
325     }
326
327   
328
329 }