refactored org to uk
[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
16
17 import org.apache.commons.logging.Log;
18 import org.apache.commons.logging.LogFactory;
19 import org.vamsas.client.ClientHandle;
20 import org.vamsas.client.IClient;
21 import org.vamsas.client.IClientFactory;
22 import org.vamsas.client.InvalidSessionUrnException;
23 import org.vamsas.client.NoDefaultSessionException;
24 import org.vamsas.client.SessionHandle;
25 import org.vamsas.client.UserHandle;
26
27 /**
28  * 
29  * 
30  */
31 public class SimpleClientFactory implements IClientFactory {
32
33   private static Log log = LogFactory.getLog(SimpleClientFactory.class);
34
35   private File sessionArena = null;
36   
37   private String vamsasSubdirectoryName = ".vamsas";
38   
39   private SessionsFile sessionFile = null;
40   private static final String SESSION_LIST="sessions.obj";
41   
42   //private   String[] currentlyAvailableDessions = null; 
43   
44   /**
45    * default constructor - called by CreateClientFactory only.
46    *
47    *Inits the sessionarena to the directory .vamsas of the user home directory. 
48    *
49    */
50   public SimpleClientFactory() throws IOException
51   {
52    // sessionArena
53     
54     //retrieves user home directory
55     String userHomeDirectory = System.getProperty("user.home");
56     if (userHomeDirectory == null || userHomeDirectory.length()<1)
57       {
58         new IOException("Unable to detect user home directory");
59       }
60     String sessionArenaPath =  userHomeDirectory.concat(File.separator.concat(this.vamsasSubdirectoryName));
61     
62     this.initSessionArena(sessionArenaPath);
63     this.initFactoryObjects();
64   }
65   
66   
67   /**
68    * Create a client factory that works with sessions at the given
69    * path.
70    * @param path path to directory called  session arena, where will be created session directories and session files.
71    */
72   public SimpleClientFactory(String path) throws IOException
73   {
74     this.initSessionArena(path);
75   }
76   /**
77    * Inits sessionArena to a given path.
78    * checks if path is valid.
79    * 
80    * @param path path to a directory to use 
81    * @throws IOException if the path is incorrect
82    */
83   private void  initSessionArena (String path) throws IOException
84   {
85     // Check path is valid and read/writeable.
86     File arenaFile = new File (path);
87     if (!arenaFile.exists())
88     {
89       if (! arenaFile.mkdirs())
90       {
91         this.sessionArena = null;
92         throw(new IOException("Unable to create a directory called "+path));
93       }
94     }
95     if (arenaFile.exists() && arenaFile.isDirectory() && arenaFile.canRead() && arenaFile.canWrite()) 
96       {
97         this.sessionArena = arenaFile;
98       } 
99     else
100       {
101       this.sessionArena = null;
102         throw(new IOException("Cannot read and write to a directory called "+path));
103       }
104   }
105   
106   /**
107    * construct SessionFile objects and watchers for each
108    */
109   private void initFactoryObjects() throws IOException {
110     if (this.sessionFile!=null )
111       throw new IOException("initFactoryObjects called for initialised ClientFactory object.");
112     this.sessionFile = new SessionsFile(new File(this.sessionArena,SESSION_LIST));
113
114   }
115   /**
116    * @see org.vamsas.client.IClientFactory#getCurrentSessions()
117    */
118   public String[] getCurrentSessions() 
119   { 
120     String[] sessions = null;
121     if (this.sessionFile!=null )
122       {
123         SessionHandle[] sessionHandles =  this.sessionFile.retrieveSessionsList();
124         if (sessionHandles != null)
125           {
126             sessions = new String[sessionHandles.length];
127             for (int i = sessionHandles.length -1; i > 0; i--)
128               {
129                 SessionHandle sessionHandle = sessionHandles[i];
130                 sessions [i] = sessionHandle.getSessionUrn();
131               }
132           }
133       }
134     return sessions;
135   }
136   
137   
138   private void discoverSession()
139   {
140    
141   }
142
143   /**
144    * @see org.vamsas.client.IClientFactory#getIClient(org.vamsas.client.ClientHandle)
145    * 
146    * Creates a IClient object, using default UserHandle with system variables:"user.name" or "USERNAME")),
147             "host.name" or "HOSTNAME" 
148    */
149   public IClient getIClient(ClientHandle applicationHandle)
150       throws NoDefaultSessionException {
151     
152     return this.getIClient(applicationHandle, (UserHandle) null);
153   }
154
155   /**
156    * @see org.vamsas.client.IClientFactory#getIClient(org.vamsas.client.ClientHandle, java.lang.String)
157    */
158   public IClient getIClient(ClientHandle applicationHandle, String sessionUrn) {
159     // TODO Auto-generated method stub
160     return null;
161   }
162
163   /**
164    * @see org.vamsas.client.IClientFactory#getIClient(org.vamsas.client.ClientHandle, org.vamsas.client.UserHandle, java.lang.String)
165    */
166   public IClient getIClient(ClientHandle applicationHandle, UserHandle userId,
167       String sessionUrn) {
168     // TODO Auto-generated method stub
169     return null;
170   }
171
172   /**
173    * @see org.vamsas.client.IClientFactory#getIClient(org.vamsas.client.ClientHandle, org.vamsas.client.UserHandle)
174    */
175   public IClient getIClient(ClientHandle applicationHandle, UserHandle userId)
176       throws NoDefaultSessionException {
177     SimpleClient client = null;
178     if (this.sessionArena==null)
179       throw new Error("Improperly initialised SimpleClientFactory object - null sessionArena.");
180     
181     ClientHandle clientHandle =applicationHandle;
182     //create default clientHandle with "SimpleVamsasClientApp","0.1",
183     if (clientHandle == null)
184      clientHandle = new ClientHandle("SimpleVamsasClientApp","0.1");
185     
186     //check if any available session(s)
187     String[] availableSessions = this.getCurrentSessions();
188     if (availableSessions != null) 
189       {//there are available sessions
190         if (availableSessions.length>1)
191           {//more than one session if available... can not choose
192           
193           //represents list of session as String
194             StringBuffer sessionURNs = new StringBuffer("");
195             for (int i = 0; i< availableSessions.length ; i++)
196               {
197                 sessionURNs.append(availableSessions[i]+" ");
198               }
199             throw new  NoDefaultSessionException("Several sessions available, please pick one: "+sessionURNs);
200           }
201       
202         //check if only one session available. if yes, open it
203         if (availableSessions.length == 1)
204           {
205           //only one session available, open it.
206             return this.getIClient(clientHandle,  availableSessions[0]);
207           }
208       }
209     //no session available  - create a new one
210     
211     
212     try 
213       {
214         //create sessionDirectory
215         File sessdir = File.createTempFile("sess", ".simpleclient", this.sessionArena);
216         log.debug("Creating new session  directory");
217        if (!(sessdir.delete() && sessdir.mkdir()))
218           throw new IOException("Could not make session directory "+sessdir);
219       //create session
220         VamsasSession vamsasSession = new VamsasSession(sessdir);
221       
222         this.getSessionFile().addSession(new SessionHandle(new SessionUrn(vamsasSession).getSessionUrn()), false);
223         if (userId == null)
224           {
225       //create a default userHandle
226       //with current OS user and hostname
227             userId = new UserHandle(System.getProperty("user.name", System.getProperty("USERNAME","Joe Doe")),
228               System.getProperty("host.name",System.getProperty("HOSTNAME", "Unknown") ));// clientName, clientVersion,  sessionPath);
229           }
230      
231       
232       //create simple client
233          client = new SimpleClient(userId,  clientHandle,  vamsasSession);
234       } 
235     catch (IOException e) 
236       {
237         log.error("error while creating new IClient",e);
238       }
239     catch (InvalidSessionUrnException e) 
240       {
241         log.error("Unable to create new IClient. The session urn is incorrect ",e);
242       }
243    
244       return client;
245   }
246
247
248   /**
249    * @return the sessionFile
250    */
251   private SessionsFile getSessionFile()  throws IOException
252     {
253       if (this.sessionFile == null)
254         {
255           this.sessionFile = new SessionsFile( new File (this.sessionArena, SESSION_LIST));
256         }
257       return this.sessionFile;
258     }
259
260   
261
262 }