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