4 package uk.ac.vamsas.client;
6 import java.lang.reflect.Field;
7 import java.lang.reflect.InvocationTargetException;
8 import java.lang.reflect.Method;
9 import java.util.Iterator;
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;
17 import uk.ac.vamsas.test.simpleclient.VamsasArchive;
20 * Base class for all Vamsas objects extracted from an IClientDocument. An
21 * Vobject maybe registered or unregistered.
26 public abstract class Vobject {
27 static Log log = LogFactory.getLog(Vobject.class);
30 * true if Vobject was stored in a vamsas Document or has been retrieved from it
32 protected boolean __stored_in_document = false;
34 * true if Vobject was updated since the vamsas library last read a Vobj with the same VorbaId from a document.
36 protected boolean __updated_since_last_read = false;
38 * true if Vobject appeared in the document after the last access by this vamsas library instance
40 protected boolean __added_since_last_read = false;
42 * memory of the last doHash() value computed for the Vobject
45 protected int __last_hash = 0;
47 * set by testInstanceForIdField() if Vobject should have a VorbaId
49 protected boolean registerable = false;
50 protected boolean __visited = false;
52 * reference to containing object for this Vobject.
54 protected Vobject V_parent=null;
56 * unique id for all vamsas objects allows unambiguous referencing to any
57 * Vobject in the vamsas document
59 protected VorbaId vorbaId = null;
62 * the source of unique VorbaIds.
64 protected IVorbaIdFactory __vorba = null;
67 * @see java.lang.Object#finalize()
69 protected void finalize() throws Throwable {
81 testInstanceForIdField();
83 java.lang.reflect.Field ___id_field=null; // set to ease pain of reflection
85 * set the isRegisterable flag based on the presence of a 'private String _id' field in
86 * the reflected class instance.
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)
92 Class thisclass=this.getClass();
93 setRegisterable(false);
94 while (!thisclass.equals(Vobject.class)) {
96 java.lang.reflect.Field fd = thisclass.getDeclaredField("_id");
97 if (String.class.isAssignableFrom(fd.getType())) {
99 this.setRegisterable(true);
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();
109 // boolean __testedInstance=false;
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!
114 protected void setInstanceIdField() {
115 /*if (!registerable && !__testedInstance) {
116 testInstanceForIdField();
117 __testedInstance=true;
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);
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);
141 System.err.println("Client error. Trying to setInstanceIdField on a "
142 + this.getClass().toString() + " (which cannot be given a vorbaId)");
146 protected String __getInstanceIdField() {
147 /*if (!registerable && !__testedInstance) {
148 testInstanceForIdField();
149 __testedInstance=true;
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;
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);
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);
177 System.err.println("Client error. Trying to getInstanceIdField on a "
178 + this.getClass().toString() + " (which cannot be given a vorbaId)");
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
189 synchronized protected boolean doHash() {
190 long __old_hash = __last_hash;
192 Vobject _V_parent=V_parent;
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;
201 __updated_since_last_read=false;
206 __last_hash = this.hashCode();
207 // reset houseskeeping variables
211 __stored_in_document = stored;
212 __updated_since_last_read=updated;
215 return (__old_hash==0) || (__old_hash == __last_hash);
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
227 protected boolean merge(Vobject laterCopy) {
228 log.warn(this.getClass().getName()+".merge() not implemented.");
234 * @return true if Vobject is registered
236 public boolean isRegistered() {
237 return (registerable) ? (vorbaId != null) : false;
241 * Method to get fixed reference for the Vobject in the vamsas document.
243 * @returns null if Vobject is neither registered or not associated with a
244 * properly instantiated VorbaIdFactory.
246 public VorbaId getVorbaId() {
247 if (registerable && vorbaId == null) {
248 if (this.__stored_in_document) {
250 vorbaId=uk.ac.vamsas.client.VorbaId.newId(this.__getInstanceIdField());
252 // Try to use the associated factory.
254 if ((vorbaId = __vorba.makeVorbaId(this)) == null)
255 return null; // Factory not valid.
257 this.setInstanceIdField();
265 * used by the IClient implementation to generate unique Id based on client
266 * applications current namespace.
268 protected void setVorbaId(VorbaId newid) {
273 * @return true if Vobject is present in Vamsas Document.
275 public boolean is__stored_in_document() {
276 return __stored_in_document;
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
282 public boolean isUpdated() {
283 return __updated_since_last_read;
287 * @return true if this object was added to the document after the last time the vamsas library acessed the session document
289 public boolean isNewInDocument() {
290 return __added_since_last_read;
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
296 protected void set__updated_since_last_read(boolean __updated_since_last_read) {
297 this.__updated_since_last_read = __updated_since_last_read;
301 * for use by Vorba agent to reflect state of vamsas Vobject to client
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.
308 protected void set__stored_in_document(boolean __stored_in_document) {
309 this.__stored_in_document = __stored_in_document;
313 * @param __added_since_last_read the __added_since_last_read to set
315 protected void set__added_since_last_read(boolean __added_since_last_read) {
316 this.__added_since_last_read = __added_since_last_read;
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
324 * @return Returns the __last_hash.
326 public int get__last_hash() {
331 * @return true if Vobject can have a vorbaId
333 public boolean isRegisterable() {
338 * Called by __testInstanceForidField and the post-unmarshalling handler
339 * to indicate if Vobject will have a vorbaId.
340 * @param registerable
342 protected void setRegisterable(boolean registerable) {
343 this.registerable = registerable;
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
359 protected void __ensure_instance_ids() {
360 __ensure_instance_ids(!__visited);
362 protected void __ensure_instance_ids(boolean visited) {
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)
371 __vorba.updateHashValue(this);
373 Class descriptor = null;
374 XMLClassDescriptorImpl descimpl = null;
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?");
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)) {
391 Object val = fields[i].getHandler().getValue(this);
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);
403 catch (Exception e) {
404 log.error("Client error - could not access array "+type.getName()+" in "+this.getClass().getName(), e);
408 if (Vobject.class.isAssignableFrom(type)) {
410 FieldHandler fh = fields[i].getHandler();
413 Object fval = fh.getValue(this);
415 if (fval.getClass().isArray()) {
416 //if (Vobject[].class.isAssignableFrom(type)) {
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);
427 catch (Exception e) {
428 log.error("Client error - could not access (fhval)array "+type.getName()+" in "+this.getClass().getName(), e);
433 log.debug("Got value for "+fields[i].getFieldName());
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();
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);
449 log.warn("Couldn't find "+this.getClass().getName()+"."+methname);
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);
461 catch (Exception e) {
462 log.error("Client error - could not access "+type.getName()+" in "+this.getClass().getName(), e);
470 * @return the __parent
472 public Vobject getV_parent() {
477 * @param __parent the __parent to set
479 protected void setV_parent(Vobject V_parent) {
480 this.V_parent = V_parent;