b4a74d3c753ad72f35795769ffa1ef5f41a5bb88
[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      //   userId = new UserHandle(System.getProperty("user.name", System.getProperty("USERNAME","Joe Doe")),
209        //   System.getProperty("host.name",System.getProperty("HOSTNAME", "Unknown") ));// clientName, clientVersion,  sessionPath);
210         userId = new UserHandle(null, null);
211         
212       }
213     
214     //FullName and organisation should not be null (otherwise UserHandle equals method raises an java.lang.NullPointerException )
215     //use    current OS user and hostname, if null
216     if ( userId.getFullName() == null)
217       {
218         userId.setFullName(System.getProperty("user.name", System.getProperty("USERNAME","Joe Doe")));
219       }
220         
221     if (userId.getOrganization() == null)
222       {
223         userId.setOrganization( System.getProperty("host.name",System.getProperty("HOSTNAME", "Unknown") ));
224       }
225       
226     if (clientHandle == null)
227       clientHandle = new ClientHandle("SimpleVamsasClientApp","0.1");
228      else
229        {
230          if (clientHandle.getClientName() == null)
231            {
232              clientHandle.setClientName("SimpleVamsasClientApp");
233            }
234          if (clientHandle.getVersion() == null)
235            {
236              clientHandle.setVersion("0.1");
237            }
238        }
239     
240   //create simple client
241      client = new SimpleClient(userId,  clientHandle,  vamsasSession);
242      vamsasSession.addClient(client);
243      vamsasSession.setSessionManager(this.getSessionManager());
244      return client;
245   }
246   /**
247    * @see uk.ac.vamsas.client.IClientFactory#getIClient(uk.ac.vamsas.client.ClientHandle, uk.ac.vamsas.client.UserHandle)
248    */
249   public IClient getIClient(ClientHandle applicationHandle, UserHandle userId)
250       throws NoDefaultSessionException {
251     // create new session
252     // register SimpleClient and UserHandles in session
253     // create client instance
254     IClient client = null;
255     if (this.sessionArena==null)
256       throw new Error("Improperly initialised SimpleClientFactory object - null sessionArena.");
257     
258     ClientHandle clientHandle =applicationHandle;
259     //create default clientHandle with "SimpleVamsasClientApp","0.1",
260     if (clientHandle == null)
261      clientHandle = new ClientHandle("SimpleVamsasClientApp","0.1");
262     else
263       {
264         if (clientHandle.getClientName() == null)
265         {
266           clientHandle.setClientName("SimpleVamsasClientApp");
267         }
268       
269     
270     if (clientHandle.getVersion() == null)
271       {
272         clientHandle.setVersion("0.1");
273       }
274       }
275     //check if any available session(s)
276     String[] availableSessions = this.getCurrentSessions();
277     if (availableSessions != null) 
278       {//there are available sessions
279         if (availableSessions.length>1)
280           {//more than one session if available... can not choose
281           
282           //represents list of session as String
283             StringBuffer sessionURNs = new StringBuffer("");
284             for (int i = 0; i< availableSessions.length ; i++)
285               {
286                 sessionURNs.append(availableSessions[i]+" ");
287               }
288             throw new  NoDefaultSessionException("Several sessions available, please pick one: "+sessionURNs);
289           }
290       
291         //check if only one session available. if yes, open it
292         if (availableSessions.length == 1)
293           {
294           //only one session available, open it.
295             return this.getIClient(clientHandle,  availableSessions[0]);
296           }
297       }
298     //no session available  - create a new one
299     
300     
301     try 
302       {
303         //create sessionDirectory
304         File sessdir = File.createTempFile("sess", ".simpleclient", this.sessionArena);
305         log.debug("Creating new session  directory");
306        if (!(sessdir.delete() && sessdir.mkdir()))
307           throw new IOException("Could not make session directory "+sessdir);
308       //create session
309      /*   VamsasSession vamsasSession = new VamsasSession(sessdir);
310       
311         this.getSessionFile().addSession(new SessionHandle(new SessionUrn(vamsasSession).getSessionUrn()), false);
312         if (userId == null)
313           {
314       //create a default userHandle
315       //with current OS user and hostname
316             userId = new UserHandle(System.getProperty("user.name", System.getProperty("USERNAME","Joe Doe")),
317               System.getProperty("host.name",System.getProperty("HOSTNAME", "Unknown") ));// clientName, clientVersion,  sessionPath);
318           }
319      
320       
321       //create simple client
322          client = new SimpleClient(userId,  clientHandle,  vamsasSession);*/
323        client = this.initClient(sessdir, userId, clientHandle);
324       } 
325     catch (IOException e) 
326       {
327         log.error("error while creating new IClient",e);
328       }
329     catch (InvalidSessionUrnException e) 
330       {
331         log.error("Unable to create new IClient. The session urn is incorrect ",e);
332       }
333    
334       return client;
335   }
336
337
338   /**
339    * @see uk.ac.vamsas.client.IClientFactory#getCurrentSessions()
340    */
341   public String[] getCurrentSessions() {
342     String [] sessions = null;
343     try {
344       sessions =this.getSessionManager().getCurrentSessions();
345     } catch (IOException e) {
346      log.error("Unable to get available sessions",e);
347      sessions = null;
348     }
349     return sessions;
350   }
351
352
353   /**
354    * @return the sessionFile
355    */
356   private SimpleSessionManager getSessionManager()  throws IOException
357     {
358       if (this.sessionManager == null)
359         {
360           this.sessionManager = new SimpleSessionManager( new File (this.sessionArena, SESSION_LIST));
361         }
362       return this.sessionManager;
363     }
364
365   
366
367 }