5029a3131cae27f58628bd995317fcb5ec99e780
[vamsas.git] / src / uk / ac / vamsas / client / Vobject.java
1 /**
2  * 
3  */
4 package uk.ac.vamsas.client;
5
6 import java.lang.reflect.Field;
7 import java.lang.reflect.InvocationTargetException;
8 import java.lang.reflect.Method;
9 import java.util.Iterator;
10
11 import org.apache.commons.logging.Log;
12 import org.apache.commons.logging.LogFactory;
13 import org.exolab.castor.mapping.FieldDescriptor;
14 import org.exolab.castor.mapping.FieldHandler;
15 import org.exolab.castor.xml.util.XMLClassDescriptorImpl;
16
17 import uk.ac.vamsas.test.simpleclient.VamsasArchive;
18
19 /**
20  * Base class for all Vamsas objects extracted from an IClientDocument. An
21  * Vobject maybe registered or unregistered.
22  * 
23  * @author jimp
24  * 
25  */
26 public abstract class Vobject {
27   static Log log = LogFactory.getLog(Vobject.class);
28   
29   /**
30    * true if Vobject was stored in a vamsas Document or has been retrieved from it
31    */
32   protected boolean __stored_in_document = false;
33   /**
34    * true if Vobject was updated since the vamsas library last read a Vobj with the same VorbaId from a document.
35    */
36   protected boolean __updated_since_last_read = false;
37   /**
38    * true if Vobject appeared in the document after the last access by this vamsas library instance
39    */
40   protected boolean __added_since_last_read = false;
41   /**
42    * memory of the last doHash() value computed for the Vobject 
43    * @see doHash()
44    */
45   protected int __last_hash = 0; 
46   /**
47    * set by testInstanceForIdField() if Vobject should have a VorbaId
48    */
49   protected boolean registerable = false; 
50   protected boolean __visited = false;
51   /**
52    * reference to containing object for this Vobject.
53    */
54   protected Vobject V_parent=null;
55   /**
56    * unique id for all vamsas objects allows unambiguous referencing to any
57    * Vobject in the vamsas document
58    */
59   protected VorbaId vorbaId = null;
60
61   /**
62    * the source of unique VorbaIds.
63    */
64   protected IVorbaIdFactory __vorba = null;
65   
66   /* (non-Javadoc)
67    * @see java.lang.Object#finalize()
68    */
69   protected void finalize() throws Throwable {
70     V_parent=null;
71     __vorba=null;
72     vorbaId=null;
73     super.finalize();
74   }
75
76   /**
77    * 
78    */
79   protected Vobject() {
80     super();
81     testInstanceForIdField();
82   }
83   java.lang.reflect.Field ___id_field=null; // set to ease pain of reflection
84   /**
85    * set the isRegisterable flag based on the presence of a 'private String _id' field in
86    * the reflected class instance.
87    */
88   private void testInstanceForIdField() {
89     // TODO: decide if 'id' is an appropriate reserved attribute name for the VorbaId
90     // look for the id field in all castor classes (should be an NCName string)
91     
92     Class thisclass=this.getClass();
93     setRegisterable(false);
94     while (!thisclass.equals(Vobject.class)) {
95       try {
96         java.lang.reflect.Field fd = thisclass.getDeclaredField("_id");
97         if (String.class.isAssignableFrom(fd.getType())) {
98           ___id_field=fd;
99           this.setRegisterable(true);
100           break;
101         }
102       } catch (SecurityException e) {
103         log.error("Unexpected Security Exception whilst finding id fields to set!",e);
104       } catch (NoSuchFieldException e) {
105         thisclass=thisclass.getSuperclass();
106       }
107     }
108   }
109   // boolean __testedInstance=false;
110   /**
111    * update the Vobject instance's _id field, based on the contents of the
112    * VorbaId. Only call this if you mean to do it!
113    */
114   protected void setInstanceIdField() {
115     /*if (!registerable && !__testedInstance) {
116       testInstanceForIdField();
117       __testedInstance=true;
118     }*/
119     if (registerable) {
120       if (__vorba != null)
121         try {
122           Method fd = this.getClass().getMethod("setId", new Class[] { String.class });
123           fd.invoke((Object) this, new Object[] {new String(this.getVorbaId().id)});
124           log.debug(this.getClass().getName()+" called setInstanceIdField!");
125         } catch (InvocationTargetException e) { 
126           log.error("SourceGeneration of "
127               + this.getClass().toString()
128               + "\n has resulted in an inaccessible 'setId' method!\nCannot set ID from the vorbaId Vobject.", e);
129         }
130         catch (IllegalAccessException e) {
131           log.error("SourceGeneration of "
132                   + this.getClass().toString()
133                   + "\n has resulted in an inaccessible 'setId' method!\nCannot set ID from the vorbaId Vobject.", e);
134         } catch (SecurityException e) {
135           log.error("Security access violation for "+this.getClass().toString(),e);
136         } catch (NoSuchMethodException e) {
137           log.warn(this.getClass().toString()+" was erroneously marked as a Vorba Vobject class (Implementation error?)");
138           this.setRegisterable(false);
139         }
140     } else {
141       System.err.println("Client error. Trying to setInstanceIdField on a "
142           + this.getClass().toString() + " (which cannot be given a vorbaId)");
143     }
144   }
145   
146   protected String __getInstanceIdField() {
147     /*if (!registerable && !__testedInstance) {
148       testInstanceForIdField();
149       __testedInstance=true;
150     }*/
151     if (registerable) {
152       if (__vorba != null)
153         try {
154           Method fd = this.getClass().getMethod("getId", (Class[]) null);
155           Object idstring = fd.invoke((Object) this, (Object[]) null);
156           log.debug(this.getClass().getName()+" called getInstanceIdField!");
157           if (idstring!=null && idstring instanceof String) {
158             if (((String) idstring).length()>0)
159               return (String) idstring;
160           }
161         } catch (InvocationTargetException e) { 
162           log.error("SourceGeneration of "
163               + this.getClass().toString()
164               + "\n has resulted in an inaccessible 'getId' method!\nCannot set ID from the vorbaId Vobject.", e);
165         }
166         catch (IllegalAccessException e) {
167           log.error("SourceGeneration of "
168                   + this.getClass().toString()
169                   + "\n has resulted in an inaccessible 'getId' method!\nCannot set ID from the vorbaId Vobject.", e);
170         } catch (SecurityException e) {
171           log.error("Security access violation for "+this.getClass().toString(),e);
172         } catch (NoSuchMethodException e) {
173           log.warn(this.getClass().toString()+" was erroneously marked as a Vorba Vobject class (Implementation error?)");
174           this.setRegisterable(false);
175         }
176     } else {
177       System.err.println("Client error. Trying to getInstanceIdField on a "
178           + this.getClass().toString() + " (which cannot be given a vorbaId)");
179     }
180     return null;
181   }
182
183   /**
184    * calculate a hash for the Vobject with all housekeeping fields at standard
185    * values. (isRegisterable is an immutable attribute property)
186    * TODO: decide if __stored_in_document should be included in the hash or not.
187    * @return true if new hash different to last hash
188    */
189   synchronized protected boolean doHash() {
190     long __old_hash = __last_hash;
191     __last_hash = 0;
192     Vobject _V_parent=V_parent;
193     V_parent=null;
194     VorbaId thisid = vorbaId;
195     IVorbaIdFactory factory = __vorba;
196     boolean stored = __stored_in_document;
197     boolean updated = __updated_since_last_read;
198     boolean visited = __visited;
199     java.lang.reflect.Field idfield = ___id_field;
200     ___id_field=null;
201     __updated_since_last_read=false;
202     vorbaId = null;
203     __vorba = null;
204     __visited=false;
205     // compute hash
206     __last_hash = this.hashCode();
207     // reset houseskeeping variables
208     ___id_field=idfield;
209     vorbaId = thisid;
210     __vorba = factory;
211     __stored_in_document = stored;
212     __updated_since_last_read=updated;
213     V_parent=_V_parent;
214     __visited=visited;
215     return (__old_hash==0) || (__old_hash == __last_hash);
216   }
217
218   /**
219    * TODO: combine two versions of the same collection Vobject to resolve
220    * asynchronous updates to the same vamsas Vobject Merges two vamsas objects,
221    * one of which is a later version of the earlier (ie they have the same
222    * vorbaId but one is a later version recently read from the vamsasDocument
223    * collection.
224    * 
225    * @return
226    */
227   protected boolean merge(Vobject laterCopy) {
228     log.warn(this.getClass().getName()+".merge() not implemented.");
229     return true;
230   }
231
232   /**
233    * 
234    * @return true if Vobject is registered
235    */
236   public boolean isRegistered() {
237     return (registerable) ? (vorbaId != null) : false;
238   }
239
240   /**
241    * Method to get fixed reference for the Vobject in the vamsas document.
242    * 
243    * @returns null if Vobject is neither registered or not associated with a
244    *          properly instantiated VorbaIdFactory.
245    */
246   public VorbaId getVorbaId() {
247     if (registerable && vorbaId == null) {
248       if (this.__stored_in_document) {
249         if (__vorba!=null)
250           vorbaId=uk.ac.vamsas.client.VorbaId.newId(this.__getInstanceIdField());
251       }
252       // Try to use the associated factory.
253       if (__vorba != null)
254         if ((vorbaId = __vorba.makeVorbaId(this)) == null)
255           return null; // Factory not valid.
256         else {
257           this.setInstanceIdField();
258           return vorbaId;
259         }
260     }
261     return vorbaId;
262   }
263
264   /**
265    * used by the IClient implementation to generate unique Id based on client
266    * applications current namespace.
267    */
268   protected void setVorbaId(VorbaId newid) {
269     vorbaId = newid;
270   }
271
272   /**
273    * @return true if Vobject is present in Vamsas Document.
274    */
275   public boolean is__stored_in_document() {
276     return __stored_in_document;
277   }
278
279   /**
280    * @return true if this object has been updated in the currently stored document since the last time a Vobject with the same ID was read from a Vamsas Document
281    */
282   public boolean isUpdated() {
283     return __updated_since_last_read;
284   }
285   /**
286    * 
287    * @return true if this object was added to the document after the last time the vamsas library acessed the session document
288    */
289   public boolean isNewInDocument() {
290     return __added_since_last_read;
291   }
292   /**
293    * Set internal flag to indicate this object was updated since the last document read
294    * @param __updated_since_last_read the __updated_since_last_read to set
295    */
296   protected void set__updated_since_last_read(boolean __updated_since_last_read) {
297     this.__updated_since_last_read = __updated_since_last_read;
298   }
299
300   /**
301    * for use by Vorba agent to reflect state of vamsas Vobject to client
302    * application.
303    * Setting stored_in_document on a registerable Vobject without a 
304    * vorbaId will mean is will *never* get a vorbaId and 
305    * horrible things will happen.
306    * @param __stored_in_document true if Vobject has been marshalled into current document.
307    */
308   protected void set__stored_in_document(boolean __stored_in_document) {
309     this.__stored_in_document = __stored_in_document;
310   }
311
312   /**
313    * @param __added_since_last_read the __added_since_last_read to set
314    */
315   protected void set__added_since_last_read(boolean __added_since_last_read) {
316     this.__added_since_last_read = __added_since_last_read;
317   }
318
319   /**
320    * __last_hash is the hash value computed when the Vobject was last checked
321    * against a IClientDocument generated by the Vobject's parent IClient
322    * instance.
323    * 
324    * @return Returns the __last_hash.
325    */
326   public int get__last_hash() {
327     return __last_hash;
328   }
329
330   /**
331    * @return true if Vobject can have a vorbaId
332    */
333   public boolean isRegisterable() {
334     return registerable;
335   }
336
337   /**
338    * Called by __testInstanceForidField and the post-unmarshalling handler
339    * to indicate if Vobject will have a vorbaId.
340    * @param registerable 
341    */
342   protected void setRegisterable(boolean registerable) {
343     this.registerable = registerable;
344   }
345   /**
346    * ensure's internal id field corresponds to vorbaId and
347    * cascade through all fields referring to an instance of Vobject
348    * calling the same method on them.
349    * TODO: LATER: properly apply castors own field mechanisms to get at accessors
350    * TODO: FIX CYCLIC __ensure+instance_ids
351    * Implementation note for the todo:
352    * this works like a depth-first search over all vamsas objects in an vamsasDocument. 
353    * __visited is the visited flag, any Vobj who's flag is of a different parity 
354    * to the visited argument will be recursed on. 
355    * note - the doHash() function used to be used as the 'visited' flag - 
356    * this *is not* a valid heuristic, although it will work "most of the time".
357    * TODO: LATER? Add another method for setDefaultProvenanceField (in the spirit of setInstanceIdField) using the info from the __vorba.getClient/User/Session methods 
358    */
359   protected void __ensure_instance_ids() {
360     __ensure_instance_ids(!__visited);
361   }
362   protected void __ensure_instance_ids(boolean visited) {
363     if (__vorba==null)
364       throw new Error("Improperly intialised uk.ac.vamsas.client.Vobject - no VorbaFactory given.");
365     log.debug("doing "+this.getClass()+".__ensure_instance_ids()");
366     if (!__stored_in_document && registerable)
367       setInstanceIdField();
368     if (__visited==visited)
369       return;
370     __visited=visited;
371     __vorba.updateHashValue(this);
372     
373     Class descriptor = null;
374     XMLClassDescriptorImpl descimpl = null;
375     try {
376       // castor descriptor resolver magic
377       descriptor = this.getClass().getClassLoader().loadClass(this.getClass().getName()+"Descriptor");
378       descimpl = (XMLClassDescriptorImpl) descriptor.getConstructor((Class[])null).newInstance((Object[])null);
379     } catch (Exception e) {
380       log.fatal("Source Generation Error!: Couldn't resolve descriptor for "
381           +this.getClass().getName()
382           +" was 'generate descriptors' set for castorbuilder.properties?");
383       return;
384     }
385     FieldDescriptor fields[] = descimpl.getFields();
386     for (int i=0,j=fields.length; i<j; i++) {
387       Class type= fields[i].getFieldType();
388       if (type.isArray()) {
389         if (Vobject[].class.isAssignableFrom(type)) {
390           try {
391             Object val = fields[i].getHandler().getValue(this);
392             if (val!=null) {
393               Vobject vals[] = (Vobject[]) val; 
394               for (int k=0, l=vals.length; k<l; k++) {
395                 if (vals[k].__vorba==null)
396                   vals[k].__vorba = __vorba; // propagate IVorbaIdFactory
397                 if (vals[k].V_parent==null)
398                   vals[k].V_parent=this; // propagate parent reference to this element.
399                 vals[k].__ensure_instance_ids(visited);
400               }
401             }
402           }
403           catch (Exception e) {
404             log.error("Client error - could not access array "+type.getName()+" in "+this.getClass().getName(), e);
405           }
406         }
407       } else
408         if (Vobject.class.isAssignableFrom(type)) {
409           try {
410             FieldHandler fh = fields[i].getHandler();
411             Vobject rf = null;
412             if (fh != null) {
413               Object fval = fh.getValue(this);
414               if (fval!=null) {
415                 if (fval.getClass().isArray()) {
416                   //if (Vobject[].class.isAssignableFrom(type)) {
417                     try {
418                       Vobject vals[] = (Vobject[]) fval; 
419                       for (int k=0, l=vals.length; k<l; k++) {
420                         if (vals[k].__vorba==null)
421                           vals[k].__vorba = __vorba; // propagate IVorbaIdFactory
422                         if (vals[k].V_parent==null)
423                           vals[k].V_parent=this; // propagate parent reference to this field object
424                         vals[k].__ensure_instance_ids(visited);
425                       }
426                     }
427                     catch (Exception e) {
428                       log.error("Client error - could not access (fhval)array "+type.getName()+" in "+this.getClass().getName(), e);
429                     }
430                   //}
431                 } else {
432                   rf = (Vobject) fval;
433                   log.debug("Got value for "+fields[i].getFieldName());
434                 }
435               }
436             } else {
437               // castor's mechanism doesn't work for this object... so...*/
438               // fuck around, fuck around, jump up jump up and get down! */
439               Object o = fields[i].getClassDescriptor();
440               if (o!=null) {
441                 // XMLClassDescriptorImpl fclasdes = (XMLClassDescriptorImpl) o;
442                 String methname = "get"+fields[i].getFieldName();
443                 Method fgetmeth = this.getClass().getMethod(methname,(Class[])null);
444                 if (fgetmeth!=null) {
445                   Object fval = fgetmeth.invoke(this,(Object[])null);
446                   if (fval!=null)
447                     rf = (Vobject) fval;
448                 } else {
449                   log.warn("Couldn't find "+this.getClass().getName()+"."+methname);
450                 }
451               }
452             }
453             if (rf!=null) {
454               if (rf.__vorba==null)
455                 rf.__vorba = __vorba; // propagate IVorbaIdFactory
456               if (rf.V_parent==null)
457                 rf.V_parent=this; // propagate parent reference
458              rf.__ensure_instance_ids(visited);
459             }
460           }
461           catch (Exception e) {
462             log.error("Client error - could not access "+type.getName()+" in "+this.getClass().getName(), e);
463           }
464         }
465     }
466     
467   }
468
469   /**
470    * @return the __parent
471    */
472   public Vobject getV_parent() {
473     return V_parent;
474   }
475
476   /**
477    * @param __parent the __parent to set
478    */
479   protected void setV_parent(Vobject V_parent) {
480     this.V_parent = V_parent;
481   }
482 }