2 * Created on 15-Sep-2005
4 * TODO To change the template for this generated file go to
5 * Window - Preferences - Java - Code Style - Code Templates
7 package uk.ac.vamsas.client.simpleclient;
9 import java.beans.EventHandler;
10 import java.beans.PropertyChangeEvent;
11 import java.beans.PropertyChangeListener;
12 import java.beans.PropertyChangeSupport;
13 import java.io.BufferedReader;
15 import java.io.IOException;
16 import java.net.MalformedURLException;
17 import java.util.Hashtable;
18 import java.util.Vector;
20 import org.apache.commons.logging.Log;
21 import org.apache.commons.logging.LogFactory;
22 import org.vamsas.client.ClientHandle;
23 import org.vamsas.client.Events;
24 import org.vamsas.client.IClient;
25 import org.vamsas.client.IClientDocument;
26 import org.vamsas.client.IObjectUpdate;
27 import org.vamsas.client.InvalidSessionUrnException;
28 import org.vamsas.client.SessionHandle;
29 import org.vamsas.client.UserHandle;
30 import org.vamsas.objects.core.ApplicationData;
31 import org.vamsas.objects.core.Entry;
32 import org.vamsas.objects.core.LockFile;
33 import org.vamsas.objects.core.VamsasDocument;
34 import org.vamsas.objects.utils.AppDataReference;
35 import org.vamsas.objects.utils.ProvenanceStuff;
36 import org.vamsas.objects.utils.document.VersionEntries;
41 public class SimpleClient implements IClient {
43 private static Log log = LogFactory.getLog(SimpleClient.class);
45 protected UserHandle user = null;
47 protected SessionUrn session = null;
48 protected VamsasSession _session;
49 protected ClientHandle client = null;
50 protected EventGeneratorThread evgen = null;
51 protected ClientDocument cdocument = null;
53 * object hash table that persists in each client holding vorbaIds and hash values after a document write
55 protected Hashtable extantobjects=null;
57 * construct a transient IdFactory instance - this should last only as long as the
58 * SimpleClient object holds the lock on the vamsas document being created/manipulated.
61 private IdFactory makeVorbaIdFactory() {
62 return new IdFactory(getSessionHandle(), client, user);
66 * construct SimpleClient for user, client and VamsasSession directory
67 * use the SimpleClientFactory rather than this constructor directly.
72 protected SimpleClient(UserHandle user, ClientHandle client, VamsasSession sess) throws InvalidSessionUrnException {
73 // TODO: validate user/client/session
78 session = new SessionUrn(_session);
79 } catch (MalformedURLException e) {
80 log.error("Couldn't form a valid SessionUrn object!",e);
81 throw new InvalidSessionUrnException(_session.toString());
85 * construct new session by importing objects from an existing vamsas document
89 * @param importingArchive
90 * @throws Exception IOExceptions for Session IO problems, and general Exception if importing document is invalid.
92 protected SimpleClient(UserHandle user, ClientHandle client, VamsasSession sess, File importingArchive) throws Exception {
93 this(user, client, sess);
94 VamsasArchive sessdoc = _session.getVamsasDocument();
96 VamsasArchiveReader odoc = new VamsasArchiveReader(importingArchive);
97 SimpleDocument sdoc = new SimpleDocument(makeVorbaIdFactory());
98 VamsasDocument doc = sdoc.getVamsasDocument(odoc);
99 sessdoc.putVamsasDocument(doc, sdoc.vorba);
100 sessdoc.closeArchive();
101 } catch (Exception e) {
102 sessdoc.cancelArchive();
103 // write a dummy archive
104 _session.slog.info("Exception when importing document data from "+importingArchive);
105 throw new Exception("Failed to import data from "+importingArchive, e);
111 * LATER: check that build substitution variables are correct
112 * @see org.vamsas.client.IClient#getAbout()
114 public String getAbout() {
115 return new String("VORBA SimpleClient version $version$ build $build$");
121 * @see org.vamsas.client.IClient#getSessionUrn()
123 public String getSessionUrn() {
124 return session.getSessionUrn();
130 * @see org.vamsas.client.IClient#getSessionHandle()
132 public SessionHandle getSessionHandle() {
133 // TODO: eliminate SessionHandle ? need to refactor interfaces.
134 SessionHandle sh = new SessionHandle(session.getSessionUrn());
141 * @see org.vamsas.client.IClient#getClientHandle()
143 public ClientHandle getClientHandle() {
150 * @see org.vamsas.client.IClient#getUserHandle()
152 public UserHandle getUserHandle() {
157 * @return user field for a provenance entry
159 protected String getProvenanceUser() {
160 return new String(user.getFullName());
163 * construct a provenance entry for this client with the specified action string.
165 * @return properly completed provenance entry
167 protected Entry getProvenanceEntry(String action) {
168 Entry prov = ProvenanceStuff.newProvenanceEntry(client.getClientUrn(), getProvenanceUser(), action);
171 private Hashtable handlers = initHandlers();
173 private Vector listeners = new Vector();
176 * make all the PropertyChangeSupport objects for the
177 * events described in org.vamsas.client.Event
180 private static Hashtable initHandlers() {
181 Hashtable events = new Hashtable();
182 java.util.Iterator evt = Events.EventList.iterator();
183 while (evt.hasNext()) {
184 Object ths = evt.next();
185 events.put(ths, (Object) new PropertyChangeSupport(ths));
193 * @see org.vamsas.client.IClient#addDocumentUpdateHandler(java.util.EventListener)
195 public void addDocumentUpdateHandler(PropertyChangeListener evt) {
196 if (handlers.containsKey(Events.DOCUMENT_UPDATE)) {
198 ((PropertyChangeSupport) (handler = handlers.get(Events.DOCUMENT_UPDATE)))
199 .addPropertyChangeListener(evt);
200 listeners.add(handler);
201 listeners.add((Object) evt);
204 boolean finalized=false;
208 * @see org.vamsas.client.IClient#finalizeClient()
210 public void finalizeClient() {
211 // TODO: determine if this is last client in session
212 // TODO: raise events like : ((lst_client && document.request.to.close), (client_finalization), (
214 // if (handlers.containsKey(Events.))
215 // if (handlers.containsKey(Events.CLIENT_FINALIZATION))
216 // deregister listeners.
217 // mark this instance as finalized
223 * @see org.vamsas.client.IClient#getClientDocument()
225 public IClientDocument getClientDocument() throws IOException {
226 if (cdocument!=null) {
227 // cdocument is non-nill if the ClientDocument.finalise() method hasn't been called.
230 VamsasArchive va = null;
232 // LATER: bail out if it takes too long to get the lock ?
233 va = _session.getVamsasDocument();
235 catch (IOException e) {
236 throw new IOException("Failed to get lock on session document");
238 VamsasDocument doc=null;
239 IdFactory vorba = null;
240 // TODO: reduce size of vorba ids generated from these parameters to IdFactory (mainly sessionHandle rationalization ?)
242 va.setVorba(vorba=makeVorbaIdFactory());
243 // if session currently holds data - read it in - or get a dummy
244 _session.slog.debug("Accessing document");
246 va.getVamsasDocument(getProvenanceUser(),
247 "created new session document.", null);
249 _session.slog.debug("Successfully retrieved document.");
251 log.error("Unexpectedly retrieved null document!");
253 catch (Exception e) {
254 log.error("Failed to get session document for session directory '"+_session.sessionDir+"'", e);
255 throw new IOException("Failed to get session document for session directory '"+_session.sessionDir+"'");
257 // Construct the IClientDocument instance
259 ClientDocument cdoc = new ClientDocument(doc, va, vorba, this);
265 * @throws Errors for invalid newdoc parameter
266 * @see org.vamsas.client.IClient#updateDocument(org.vamsas.client.IClientDocument)
268 public void updateDocument(IClientDocument newdoc) {
269 if (!(newdoc instanceof ClientDocument)) {
270 throw new Error("Invalid IClientDocument instance for SimpleClient.");
273 throw new Error("Client Error - updateDocument() called before getClientDocument().");
274 if (newdoc!=cdocument)
275 throw new Error("Client Error - SimpleClient.updateDocument() can only take the IClientDocument instance returned from SimpleClient.getClientDocument()");
276 if (!cdocument.isModified()) {
277 if (log.isDebugEnabled())
278 log.debug("updateDocument for "+session.getSessionUrn()+" with unmodified IClientDocument.");
281 if (!cdocument.updateSessionDocument()) {
282 log.warn("Session document did not update properly for session directory "+_session.sessionDir);
283 // cdocument.archive.cancelArchive(); // LATER: could be done - would need to prevent updateSessionDocument closing the archive.
284 _session.slog.warn("Session Document updated but may not be valid (false return from org.vamsas.simpleclient.ClientDocument.updateSessionDocument()");
287 catch (IOException e) {
288 log.warn("IO Problems when updating document!",e);
289 _session.slog.error("IO problems when attempting to update document.");
292 // garbage collect the ClientDocument instance.
294 cdocument.finalize();
296 } catch (Throwable e) {
297 log.error("Exception when trying to garbage collect ClientDocument for "+session.getSessionUrn(), e);
299 cdocument = null; // this is probably done by finalize
305 * @see org.vamsas.client.IClient#storeDocument(java.io.File)
307 public void storeDocument(File location) {
309 // write storeDocument file to inform other clients that they should raise
310 Lock vamlock = evgen.want_to_store();
311 // Events.DOCUMENT_FINALIZEAPPDATA
313 _session.writeVamsasDocument(location, vamlock);
314 _session.clearUnsavedFlag();
315 } catch (Exception e) {
316 log.warn("Exception whilst trying to store document in "+location,e);
325 * @see org.vamsas.client.IClient#addVorbaEventHandler(java.lang.String,
326 * java.beans.PropertyChangeListener)
328 public void addVorbaEventHandler(String EventChain, PropertyChangeListener evt) {
329 if (handlers.containsKey(EventChain)) {
331 ((PropertyChangeSupport) (handler = handlers.get(EventChain)))
332 .addPropertyChangeListener(evt);
333 listeners.add(handler);
334 listeners.add((Object) evt);
339 * @see org.vamsas.client.IClient#pollUpdate()
341 public void pollUpdate() {
344 log.warn("pollUpdate called on incomplete SimpleClient object.");
348 if (!evgen.isAlive()) {
349 log.warn("pollUpdate called before joinSession() - trying to do this.");
352 } catch (Exception e) {
353 log.error("Unexpected exception on default call to joinSession",e);
357 //TODO ensure event generator robustly handles these interrupts.
358 log.debug("interrrupting event generator.");
360 log.debug("interrrupted event generator.");
364 * @see org.vamsas.client.IClient#joinSession()
366 public void joinSession() throws Exception {
367 // start the EventGenerator thread.
369 log.warn("joinSession called on incomplete SimpleClient object.");
373 throw new Error("Join session called twice for the same SimpleClient (IClient instance).");
376 log.debug("Started EventGenerator thread.");
378 log.warn("Failed to start EventGenerator thread.");
379 throw new Exception("Failed to start event generator thread - client cannot be instantiated.");
381 if (evgen.countHandlersFor(Events.DOCUMENT_CREATE)>0) {
382 //TODO: is this application connecting to a newly created session document ?
383 //evgen.raise(Events.DOCUMENT_CREATE);
390 * @see org.vamsas.client.IClient#importDocument(java.io.File)
392 public void importDocument(File location) {
393 // TODO LATER: implement SimpleClient.importDocument()
394 log.error("importDocument is not yet implemented for a SimpleClient Session.");
397 public IObjectUpdate getUpdateHandler(Class rootObject) {
398 // TODO Auto-generated method stub
402 public IObjectUpdate[] getUpdateHandlers() {
403 // TODO Auto-generated method stub
407 public void removeUpdateHandler(Class rootObject) {
408 // TODO Auto-generated method stub
412 public void setUpdateHandler(IObjectUpdate handler) {
413 // TODO Auto-generated method stub