KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > mdr > storagemodel > StorableClass


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19 package org.netbeans.mdr.storagemodel;
20
21 import java.util.*;
22 import java.io.IOException JavaDoc;
23
24 import javax.jmi.model.*;
25 import javax.jmi.reflect.*;
26
27 import org.netbeans.mdr.util.*;
28 import org.netbeans.mdr.persistence.*;
29 import org.netbeans.mdr.handlers.*;
30 import org.netbeans.mdr.handlers.gen.TagSupport;
31
32 /** Class representing a class proxy.
33  *
34  * @author Martin Matula, Petr Hrebejk
35  * @version 0.2
36  */

37 public class StorableClass extends StorableFeatured {
38
39     private AttributeDescriptor attrDescs[];
40     private Map clAttrDescs;
41     private Map clAttrValues;
42     private Map datatypes;
43     private List superclasses;
44     private List subclasses;
45     private Map references;
46     private Collection associationEnds;
47     private boolean classDerived;
48     private boolean instanceDerived;
49     private String JavaDoc classSuperclass = null;
50     private String JavaDoc instanceSuperclass = null;
51     private boolean singletonClass;
52     private boolean abstractClass;
53     private IndexDescriptor[] indexDescs;
54
55     // transient variables
56
private final Hashtable refCache = new Hashtable();
57
58     /**
59      * Names of all instance-level attributes of the class corresponding to
60      * this classproxy collected from
61      * the metaclass and its superclasses. Order of the names match exactly
62      * order of attribute descriptors in the attributeDecs array and the
63      * array of attr values in instances.
64      */

65     private List attributes;
66     
67     /**
68      * Collected attribute descriptors from this classproxy's metaclass and
69      * its superclasses. They're stored as array because of convenient fast access
70      * by index.
71      */

72     private AttributeDescriptor[] attributeDescs;
73
74     /**
75      * Collected additional index descriptors from this classproxy's metaclass and
76      * its superclasses.
77      */

78     private List indexDescriptors;
79
80     /**
81      * Maps attribute's ant assoc. end's ids to list of related additional indexes.
82      */

83     private HashMap indexMap;
84     
85     /**
86      * Map of all additional indexes by name.
87      */

88     private HashMap indexesByName;
89     
90     /** Replaces MOFIDs using the passed map. (This method is used when rebuilding metaobjects.)
91      * @param table Map of old MOFIDs to new MOFIDs.
92      */

93     protected void replaceValues(Map table) {
94         objectWillChange();
95         super.replaceValues(table);
96
97         // rebuild all attributes
98
for (int i = 0; i < attrDescs.length; i++) {
99             attrDescs[i].replaceValues(table);
100         }
101
102         if (clAttrDescs != null) {
103             for (Iterator it = clAttrDescs.values().iterator(); it.hasNext();) {
104                 ((AttributeDescriptor) it.next()).replaceValues(table);
105             }
106         }
107
108         // rebuild all references
109
for (Iterator it = references.values().iterator(); it.hasNext();) {
110             ((ReferenceDescriptor) it.next()).replaceValues(table);
111         }
112         objectChanged();
113     }
114
115     /** Creates a new StorableClass.
116      * This default constructor is to be called only when deserializing class proxy.
117      * <code>read</code> method is called immediately after this constructor.
118      */

119     public StorableClass() {
120         super();
121     }
122
123     /** Creates new StorableClass providing all needed arguments.
124      * @param mdrStorage parent storage
125      * @param packageId MOFID of immediate package
126      * @param metaId MOFID of metaobject
127      * @param attrDescriptors mapping from attribute names to attribute mofids
128      * @param clAttrDescriptors mapping from attribute names to attribute mofids (for classifier-level attributes)
129      * @throws StorageException problem in storage
130      */

131     public StorableClass(MdrStorage mdrStorage, org.netbeans.mdr.persistence.MOFID packageId, org.netbeans.mdr.persistence.MOFID metaId,
132         List attrDescs, List clAttrDescs, Map datatypes, boolean classDerived,
133         boolean instanceDerived, boolean isSingleton, boolean isAbstract) throws StorageException {
134
135         super(mdrStorage, packageId, metaId);
136
137         this.attrDescs = (AttributeDescriptor[]) attrDescs.toArray(new AttributeDescriptor[attrDescs.size()]);
138         
139         int size = clAttrDescs.size();
140         if (size > 0) {
141             this.clAttrDescs = new HashMap(size * 2);
142             this.clAttrValues = new HashMap(size * 2);
143             for (Iterator it = clAttrDescs.iterator(); it.hasNext();) {
144                 AttributeDescriptor desc = (AttributeDescriptor) it.next();
145                 this.clAttrDescs.put(desc.getName(), desc);
146                 this.clAttrValues.put(desc.getName(), getInitialValue(desc, null));
147             }
148         }
149
150         this.datatypes = datatypes;
151         subclasses = new ArrayList();
152         superclasses = new ArrayList();
153         references = new HashMap();
154         associationEnds = new ArrayList();
155
156         this.classDerived = classDerived;
157         this.instanceDerived = instanceDerived;
158         this.singletonClass = isSingleton;
159         this.abstractClass = isAbstract;
160         
161         getMdrStorage().addObject(this);
162         initFinished = true;
163     }
164
165     public void buildAdditionalIndexes(List indexTags, Map associationProxies) throws StorageException {
166         objectWillChange();
167         indexDescs = new IndexDescriptor [indexTags.size ()];
168         Iterator iter = indexTags.iterator ();
169         for (int y = 0; iter.hasNext (); y++) {
170             Tag tag = (Tag) iter.next ();
171             List values = tag.getValues ();
172             if ((values == null) || (values.size () == 0)) {
173                 throw new DebugException ("Cannot create unnamed additional index.");
174             }
175             String JavaDoc indexName = (String JavaDoc) values.get (0);
176             List elements = new ArrayList (tag.getElements ());
177             Iterator elementsIter = elements.iterator ();
178             List collectedFields = new ArrayList (elements.size ());
179             
180             while (elementsIter.hasNext()) {
181                 ModelElement elem = (ModelElement) elementsIter.next ();
182                 if (((org.netbeans.mdr.handlers.InstanceHandler)elem)._getDelegate().getMofId().equals (getMetaObjectId()))
183                     continue;
184                 if (elem instanceof Attribute) {
185                     collectedFields.add (new IndexDescriptor.Attrib (((org.netbeans.mdr.handlers.InstanceHandler)elem)._getDelegate().getMofId(), elem.getName (), ((Attribute)elem).getMultiplicity().isOrdered()));
186                 } else if (elem instanceof AssociationEnd) {
187                     org.netbeans.mdr.persistence.MOFID assocId = (org.netbeans.mdr.persistence.MOFID) associationProxies.get (((org.netbeans.mdr.handlers.InstanceHandler)elem.getContainer ())._getDelegate().getMofId());
188                     collectedFields.add (new IndexDescriptor.AssocEnd (((org.netbeans.mdr.handlers.InstanceHandler)elem)._getDelegate().getMofId(), elem.getName(), ((AssociationEnd)elem).getMultiplicity().isOrdered(), assocId));
189                 } else {
190                     throw new DebugException ("Cannot create additional index " + indexName + ", element " + elem.getName() + " is not an attribute or an association end.");
191                 }
192             } // for
193
IndexDescriptor indexDesc = new IndexDescriptor (indexName, (IndexDescriptor.Field []) collectedFields.toArray (new IndexDescriptor.Field [collectedFields.size()]));
194             indexDescs [y] = indexDesc;
195             getMdrStorage().createAdditionalIndex(getOutermostPackageId(), indexName, getMofId ());
196         } // for
197
objectChanged ();
198     }
199
200     /**
201      * Creates map storing all additional indexes related to attribute's or assoc. end's id.
202      */

203     private void buildIndexMap () throws StorageException {
204         indexMap = new HashMap();
205         indexesByName = new HashMap();
206         Iterator iter = indexDescriptors.iterator();
207         while (iter.hasNext()) {
208             IndexDescriptor desc = (IndexDescriptor) iter.next();
209             indexesByName.put (desc.getName(), desc);
210             Object JavaDoc [] fields = desc.getFields();
211             for (int x = 0; x < fields.length; x++) {
212                 org.netbeans.mdr.persistence.MOFID id;
213                 if (fields[x] instanceof IndexDescriptor.Attrib) {
214                     id = ((IndexDescriptor.Attrib) fields[x]).getId();
215                     String JavaDoc name = ((IndexDescriptor.Attrib) fields[x]).getName();
216                     attributeDescs [getAttrIndex(name)].setIndexed(true);
217                 } else
218                     id = ((IndexDescriptor.AssocEnd) fields[x]).getId();
219                 List list = (List) indexMap.get(id);
220                 if (list == null)
221                     indexMap.put(id, list = new LinkedList());
222                 list.add(desc);
223             } // for
224
} // while
225
}
226
227     List getIndexes(org.netbeans.mdr.persistence.MOFID mofId) throws StorageException {
228         checkAttributes();
229         return (List) indexMap.get(mofId);
230     }
231     
232     public IndexDescriptor getAdditionalIndex(String JavaDoc indexName) throws StorageException {
233         checkAttributes();
234         return (IndexDescriptor) indexesByName.get (indexName);
235     }
236
237     public DatatypeDescriptor getDatatypeDesc(String JavaDoc name) {
238         return (DatatypeDescriptor) datatypes.get(name);
239     }
240
241     /** Returns immutable, live collection of all instances of MOF class
242      * represented by this proxy.
243      *
244      * @param subclasses if <code>true</code> also the instances of sub-classes
245      * will be returned, otherwise only the instances of the current class
246      * @return collection of instances of this class (and its sub-classes)
247      * @throws StorageException problem in storage
248      */

249     public Collection allObjects(boolean subclasses) throws StorageException {
250         if (subclasses) {
251             CompositeCollection result = new CompositeCollection();
252             collectObjects(result, new HashSet());
253             return result;
254         } else {
255             MdrStorage storage = getMdrStorage();
256             org.netbeans.mdr.persistence.MOFID mofId = getMofId();
257             return new IndexImmutSet(storage, storage.getInstancesIndex(mofId), mofId);
258         }
259     }
260
261     /**
262      * Adds the instances of this class and its super-classes to <code>result</code>
263      * and adds the MOF IDs of all visited class proxies to <code>visited</code>.
264      * Instances of a class already being a member of <code>visited</code> are
265      * not added to <code>result</code> a second time.
266      *
267      * @param result the collection where to add the instances
268      * @param visited MOF IDs of class proxies already visited
269      */

270     private void collectObjects(CompositeCollection result, Set visited) throws StorageException {
271         if (visited.add(getMofId())) {
272             result.addCollection(allObjects(false));
273             for (Iterator it = subclasses.iterator(); it.hasNext();) {
274                 ((StorableClass) getMdrStorage().getObject((org.netbeans.mdr.persistence.MOFID) it.next())).collectObjects(result, visited);
275             }
276         }
277     }
278     
279     public void addAssociationEnd(org.netbeans.mdr.persistence.MOFID mofId, String JavaDoc endName, boolean aggregate) {
280         objectWillChange();
281         associationEnds.add(new AssocEndDescriptor(mofId, endName, aggregate));
282         objectChanged();
283     }
284     
285     // this is always called from a synchronized section
286
public void addSubclass(org.netbeans.mdr.persistence.MOFID mofId) {
287         objectWillChange();
288         subclasses.add(mofId);
289         objectChanged();
290     }
291
292     // this is always called from a synchronized section
293
public void addSuperclass(org.netbeans.mdr.persistence.MOFID mofId) {
294         if (attributes != null) {
295             throw new DebugException("bad thing in: " + getMofId());
296         }
297         objectWillChange();
298         superclasses.add(mofId);
299         objectChanged();
300     }
301
302     // always synchronized
303
public void addReferenceDescriptor(org.netbeans.mdr.persistence.MOFID mofId, String JavaDoc name, org.netbeans.mdr.persistence.MOFID assocProxyId, String JavaDoc endName) {
304         objectWillChange();
305         references.put(name, new ReferenceDescriptor(mofId, assocProxyId, endName));
306         objectChanged();
307     }
308     
309     public void verify(Collection violations) {
310         // [PENDING] should check all components and classifier attributes
311
}
312     
313     /** Returns value of a given classifier-level attribute
314      * @param name attribute name.
315      * @throws StorageException
316      */

317     public Object JavaDoc getAttribute(String JavaDoc name) throws StorageException {
318         StorableClass cls = getClsForAttr(name);
319         if (cls == null) throw new DebugException("Classifier-level attribute '" + name + "' not found.");
320         return cls.clAttrValues.get(name);
321     }
322     
323     /** Sets value of a given classifier-level attribute
324      * @param name attribute name
325      * @param value attribute value
326      */

327     public void setAttribute(String JavaDoc name, Object JavaDoc value) throws StorageException {
328         StorableClass cls = getClsForAttr(name);
329         if (cls == null) throw new DebugException("Classifier-level attribute '" + name + "' not found.");
330         
331         cls.objectWillChange();
332         AttributeDescriptor attribute = (AttributeDescriptor) cls.clAttrDescs.get(name);
333         Object JavaDoc oldValue = cls.clAttrValues.put(name, value);
334
335         if (!attribute.isMultivalued() && (value instanceof RefObject)) {
336             StorableObject storableObj = (StorableObject) ((BaseObjectHandler) value)._getDelegate();
337             storableObj.setComposite(getMofId(), storableObj.getMofId(), attribute.getMofId());
338             if (oldValue != null) {
339                 storableObj = (StorableObject) ((BaseObjectHandler) oldValue)._getDelegate();
340                 storableObj.clearComposite();
341             }
342         }
343         cls.objectChanged();
344     }
345
346     private StorableClass getClsForAttr(String JavaDoc name) throws StorageException {
347         if (clAttrDescs == null || clAttrDescs.get(name) == null) {
348             StorableClass result = null;
349             for (Iterator it = superclasses.iterator(); it.hasNext() && result == null;) {
350                 result = ((StorableClass) getMdrStorage().getObject((org.netbeans.mdr.persistence.MOFID) it.next())).getClsForAttr(name);
351             }
352             return result;
353         } else {
354             return this;
355         }
356     }
357     
358     public StorableClass getClassProxy() throws StorageException {
359         return this;
360     }
361     
362     public final int getAttrIndex(String JavaDoc attributeName) throws StorageException {
363         checkAttributes();
364
365         int result = attributes.indexOf(attributeName);
366         if (result < 0) {
367             Logger.getDefault().log("attribute not found: " + attributeName);
368             Logger.getDefault().log("collected attributes of " + getMofId() + ":");
369             for (Iterator it = attributes.iterator(); it.hasNext();) {
370                 Logger.getDefault().log("\t" + it.next());
371             }
372             Logger.getDefault().log("registered superclasses:");
373             for (Iterator it = superclasses.iterator(); it.hasNext();) {
374                 Logger.getDefault().log("\t" + it.next());
375             }
376             Logger.getDefault().log("registered subclasses:");
377             for (Iterator it = subclasses.iterator(); it.hasNext();) {
378                 Logger.getDefault().log("\t" + it.next());
379             }
380             throw new DebugException();
381         }
382         return result;
383     }
384
385     public final int getAttrCount() throws StorageException {
386         checkAttributes();
387         return attributeDescs.length;
388     }
389
390     public final AttributeDescriptor getAttrDesc(int attrIndex) throws StorageException {
391         checkAttributes();
392         return attributeDescs[attrIndex];
393     }
394     
395     public final AttributeDescriptor getAttrDesc(String JavaDoc attrName) throws StorageException {
396         try {
397             int index = getAttrIndex(attrName);
398             return getAttrDesc(index);
399         } catch (DebugException e) {
400             StorableClass cls = getClsForAttr(attrName);
401             if (cls == null) throw new DebugException("Attribute '" + attrName + "' not found.");
402             return (AttributeDescriptor) cls.clAttrDescs.get(attrName);
403         }
404     }
405     
406     public ReferenceDescriptor getReferenceDescriptor(String JavaDoc referenceName) throws StorageException {
407         ReferenceDescriptor result = (ReferenceDescriptor) refCache.get(referenceName);
408
409         if (result == null) {
410             result = (ReferenceDescriptor) references.get(referenceName);
411
412             if (result == null) {
413                 for (Iterator it = superclasses.iterator(); it.hasNext();) {
414                     result = ((StorableClass) getMdrStorage().getObject((org.netbeans.mdr.persistence.MOFID) it.next())).getReferenceDescriptor(referenceName);
415                     if (result != null) {
416                         break;
417                     }
418                 }
419             }
420             if (result != null) refCache.put(referenceName, result);
421         }
422
423         return result;
424     }
425     
426     public Collection getAllReferenceDescriptors() throws StorageException {
427         return collectReferences(new ArrayList(), new HashSet());
428     }
429     
430     private Collection collectReferences(Collection descs, Set visited) throws StorageException {
431         descs.addAll(references.values());
432         visited.add(getMofId());
433         for (Iterator it = superclasses.iterator(); it.hasNext();) {
434             org.netbeans.mdr.persistence.MOFID mofId = (org.netbeans.mdr.persistence.MOFID) it.next();
435             if (!visited.contains(mofId)) {
436                 ((StorableClass) getMdrStorage().getObject(mofId)).collectReferences(descs, visited);
437             }
438         }
439         return descs;
440     }
441     
442     private synchronized void checkAttributes() throws StorageException {
443         if (attributes == null) {
444             //Logger.getDefault().log("collecting attributes for: " + getMofId());
445
attributes = new ArrayList();
446             List attribDescs = new ArrayList();
447             indexDescriptors = new ArrayList();
448             collectAttributes(attributes, attribDescs, indexDescriptors, new HashSet());
449             this.attributeDescs = (AttributeDescriptor[])attribDescs.toArray(
450                 new AttributeDescriptor[attribDescs.size()]);
451             buildIndexMap();
452         }
453     }
454     
455     void collectAssociationEnds(Collection result, Set visited) throws StorageException {
456         org.netbeans.mdr.persistence.MOFID mofId;
457         for (Iterator it = superclasses.iterator(); it.hasNext();) {
458             mofId = (org.netbeans.mdr.persistence.MOFID) it.next();
459             if (!visited.contains(mofId)) {
460                 ((StorableClass) getMdrStorage().getObject(mofId)).collectAssociationEnds(result, visited);
461             }
462         }
463         result.addAll(associationEnds);
464         visited.add(getMofId());
465     }
466
467     private void collectAttributes(List attrs, List descs, List indexes, Set visited) throws StorageException {
468         org.netbeans.mdr.persistence.MOFID mofId;
469         for (Iterator it = superclasses.iterator(); it.hasNext();) {
470             mofId = (org.netbeans.mdr.persistence.MOFID) it.next();
471             if (!visited.contains(mofId)) {
472                 ((StorableClass) getMdrStorage().getObject(mofId)).collectAttributes(attrs, descs, indexes, visited);
473             }
474         }
475
476         for (int i = 0; i < attrDescs.length; i++) {
477             attrs.add(attrDescs[i].getName());
478             descs.add(attrDescs[i]);
479         }
480         if (indexDescs != null) {
481             for (int i = 0; i < indexDescs.length; i++) {
482                 indexes.add(indexDescs[i]);
483             }
484         }
485         visited.add(getMofId());
486     }
487
488     /**
489      * Returns the super-class for generated handler classes.
490      */

491     public Class JavaDoc getClassSuperclass() throws StorageException, ClassNotFoundException JavaDoc {
492         return resolveClass(classSuperclass);
493     }
494     
495     public Class JavaDoc getClassCustomImpl() {
496         try {
497             return getClassSuperclass();
498         } catch (Exception JavaDoc e) {}
499         return null;
500     }
501
502     public Class JavaDoc getInstanceSuperclass() throws StorageException, ClassNotFoundException JavaDoc {
503         return resolveClass(instanceSuperclass);
504     }
505
506     public Class JavaDoc getInstanceCustomImpl() {
507         try {
508             Class JavaDoc sup = getInstanceSuperclass();
509             return sup == InstanceHandler.class ? null : sup;
510         } catch (Exception JavaDoc e) {}
511         return null;
512     }
513
514     public boolean isAbstract() {
515         return abstractClass;
516     }
517
518     public boolean isSingleton() {
519         return singletonClass;
520     }
521     
522     public boolean isTransient () {
523         return false;
524     }
525
526     /**
527      * Returns the implementation super-class for the generated handler.
528      *
529      * <p>If the class has derived or inceptable members, {@link
530      * TagSupport#getImplFullName(StorableObject, int)} determines the class
531      * name.</p>
532      *
533      * <p>If this model class has model super-classes then the return value
534      * depends on if there is a most specific implementation class among the
535      * implementation classes of those super-classes. If yes, this most
536      * specific implementation class is returned, otherwise {@link
537      * TagSupport#getImplFullName(StorableObject, int)} determines the class
538      * name.</p>
539      *
540      * <p>If non of the cases above applies, <code>ClassProxyHandler.class</code>
541      * is returned as default value.</p>
542      */

543     public Class JavaDoc initClassSuperclass(Class JavaDoc iface[]) throws StorageException, ClassNotFoundException JavaDoc {
544         Class JavaDoc result = null;
545         if (classSuperclass == null) {
546             try {
547                 result = resolveClass(this, TagSupport.CLASS);
548     // iface[0] = resolveInterface(this, TagSupport.CLASS);
549
} catch (ClassNotFoundException JavaDoc e) {
550     // if (classDerived)
551
// throw e;
552
// Class current;
553
// Class currentIface[] = new Class[1];
554
// for (Iterator it = superclasses.iterator(); it.hasNext();) {
555
// current = ((StorableClass) getMdrStorage().getObject((org.netbeans.mdr.persistence.MOFID) it.next())).initClassSuperclass(currentIface);
556
// if (result == null || iface[0] == null || iface[0].isAssignableFrom(currentIface[0])) {
557
// result = current;
558
// iface[0] = currentIface[0];
559
// } else if (!currentIface[0].isAssignableFrom(iface[0])) {
560
// throw e;
561
// }
562
// }
563
// if (result == null) {
564
result = ClassProxyHandler.class;
565     // iface[0] = RefClass.class;
566
// }
567
}
568             objectWillChange();
569             classSuperclass = result.getName();
570             objectChanged();
571 // } else {
572
// result = resolveClass(classSuperclass);
573
}
574         return result;
575     }
576
577     private static Class JavaDoc resolveClass(StorableClass cls, int type) throws ClassNotFoundException JavaDoc, StorageException {
578         return resolveClass(TagSupport.getImplFullName(cls.getMetaObject(), type));
579     }
580
581     private static Class JavaDoc resolveClass(String JavaDoc className) throws ClassNotFoundException JavaDoc {
582         return BaseObjectHandler.resolveImplementation(className);
583     }
584     
585     private static Class JavaDoc resolveInterface(StorableClass cls, int type) throws ClassNotFoundException JavaDoc, StorageException {
586         return BaseObjectHandler.resolveInterface(TagSupport.getTypeFullName(cls.getMetaObject(), type));
587     }
588     
589     public Class JavaDoc initInstanceSuperclass(Class JavaDoc iface[]) throws StorageException, ClassNotFoundException JavaDoc {
590         Class JavaDoc result = null;
591         try {
592             result = resolveClass(this, TagSupport.INSTANCE);
593             iface[0] = resolveInterface(this, TagSupport.INSTANCE);
594         } catch (ClassNotFoundException JavaDoc e) {
595 // if (instanceDerived)
596
// throw e;
597
Class JavaDoc current;
598             Class JavaDoc currentIface[] = new Class JavaDoc[1];
599             for (Iterator it = superclasses.iterator(); it.hasNext();) {
600                 current = ((StorableClass) getMdrStorage().getObject((org.netbeans.mdr.persistence.MOFID) it.next())).initInstanceSuperclass(currentIface);
601                 if (result == null || iface[0] == null || iface[0].isAssignableFrom(currentIface[0])) {
602                     result = current;
603                     iface[0] = currentIface[0];
604                 } else if (!currentIface[0].isAssignableFrom(iface[0]))
605                     throw e;
606             }
607             if (result == null) {
608                 result = InstanceHandler.class;
609                 iface[0] = RefObject.class;
610             }
611         }
612         if (instanceSuperclass == null) {
613             objectWillChange();
614             this.instanceSuperclass = result.getName();
615             objectChanged();
616         }
617         return result;
618     }
619
620     protected void deleteRecursive() throws StorageException {
621         MOFID thisMofId = this.getMofId();
622         MdrStorage storage = this.getMdrStorage ();
623         MultivaluedIndex instancesIndex = storage.getInstancesIndex(thisMofId);
624         Collection instances = instancesIndex.getItems (thisMofId);
625         for (Iterator it = instances.iterator(); it.hasNext();) {
626             MOFID instanceMofId = (MOFID) it.next();
627             storage.removeObject (instanceMofId);
628             it.remove ();
629         }
630         super.deleteRecursive();
631     }
632
633     public List getIndexDescriptors () throws StorageException {
634         checkAttributes();
635         return indexDescriptors;
636     }
637
638     /**
639      * @param outputStream
640      */

641     public void write(java.io.OutputStream JavaDoc outputStream) {
642         super.write(outputStream);
643         try {
644             IOUtils.write (outputStream, meta, this);
645             IOUtils.write (outputStream, immediatePackage, this);
646
647             if (attrDescs == null) {
648                 IOUtils.writeInt(outputStream, 0);
649             } else {
650                 IOUtils.writeInt(outputStream, attrDescs.length + 1);
651                 for (int i = 0; i < attrDescs.length; i++) {
652                     attrDescs[i].write(outputStream);
653                 }
654             }
655             
656             IOUtils.writeInt(outputStream, datatypes.size());
657             for (Iterator it = datatypes.keySet().iterator(); it.hasNext();) {
658                 String JavaDoc name = (String JavaDoc) it.next();
659                 IOUtils.writeString(outputStream, name);
660                 ((DatatypeDescriptor) datatypes.get(name)).write(outputStream);
661             }
662
663             // can be null
664
IOUtils.write(outputStream, subclasses, this);
665             // can be null
666
IOUtils.write(outputStream, superclasses, this);
667             // can be null
668
IOUtils.write(outputStream, references, this);
669
670             IOUtils.writeInt(outputStream, associationEnds.size());
671             for (Iterator it = associationEnds.iterator(); it.hasNext();) {
672                 AssocEndDescriptor item = (AssocEndDescriptor) it.next();
673                 IOUtils.writeMOFID(outputStream, item.mofId, getMdrStorage(), getMofId());
674                 IOUtils.writeString(outputStream, item.endName);
675                 IOUtils.writeBoolean(outputStream, item.isAggregate);
676             }
677
678             IOUtils.writeBoolean(outputStream, classDerived);
679             IOUtils.writeBoolean(outputStream, instanceDerived);
680             IOUtils.writeBoolean(outputStream, singletonClass);
681             IOUtils.writeBoolean(outputStream, abstractClass);
682
683             IOUtils.writeString(outputStream, classSuperclass);
684             IOUtils.writeString(outputStream, instanceSuperclass);
685             
686             if (indexDescs == null) {
687                 IOUtils.writeInt(outputStream, 0);
688             } else {
689                 IOUtils.writeInt(outputStream, indexDescs.length);
690                 for (int i = 0; i < indexDescs.length; i++) {
691                     indexDescs[i].write(outputStream,this);
692                 }
693             }
694             
695             if (clAttrDescs == null) {
696                 IOUtils.writeInt(outputStream, 0);
697             } else {
698                 IOUtils.writeInt(outputStream, clAttrDescs.size());
699                 for (Iterator it = clAttrDescs.values().iterator(); it.hasNext();) {
700                     AttributeDescriptor desc = (AttributeDescriptor) it.next();
701                     desc.write(outputStream);
702                     IOUtils.write(outputStream, clAttrValues.get(desc.getName()), this);
703                 }
704             }
705
706         } catch (java.io.IOException JavaDoc e) {
707             Logger.getDefault().notify(Logger.INFORMATIONAL, e);
708         }
709     }
710
711     /**
712      * @param inputStream
713      */

714     public void read(java.io.InputStream JavaDoc inputStream) {
715         super.read(inputStream);
716         try {
717             meta = (org.netbeans.mdr.persistence.MOFID) IOUtils.read(inputStream, this);
718             immediatePackage = (org.netbeans.mdr.persistence.MOFID) IOUtils.read (inputStream, this);
719
720             int objCount = IOUtils.readInt(inputStream);
721             if (objCount != 0) {
722                 int arrayLength = objCount - 1;
723                 attrDescs = new AttributeDescriptor[arrayLength];
724
725                 for (int i = 0; i < arrayLength; i++) {
726                     attrDescs[i] = AttributeDescriptor.readResolve(inputStream, this);
727                 }
728             }
729
730             objCount = IOUtils.readInt(inputStream);
731             datatypes = new HashMap(objCount, 1);
732             for (int i = 0; i < objCount; i++) {
733                 String JavaDoc name = IOUtils.readString(inputStream);
734                 datatypes.put(name, DatatypeDescriptor.readResolve(inputStream, this));
735             }
736
737             subclasses = (List) IOUtils.read(inputStream, this);
738             superclasses = (List) IOUtils.read(inputStream, this);
739             references = (Map) IOUtils.read(inputStream, this);
740             
741             objCount = IOUtils.readInt(inputStream);
742             associationEnds = new ArrayList(objCount);
743             for (int i = 0; i < objCount; i++) {
744                 associationEnds.add(new AssocEndDescriptor(
745                     IOUtils.readMOFID(inputStream, getMdrStorage(), getMofId()),
746                     IOUtils.readString(inputStream),
747                     IOUtils.readBoolean(inputStream)
748                 ));
749             }
750
751             classDerived = IOUtils.readBoolean(inputStream);
752             instanceDerived = IOUtils.readBoolean(inputStream);
753             singletonClass = IOUtils.readBoolean(inputStream);
754             abstractClass = IOUtils.readBoolean(inputStream);
755
756             classSuperclass = IOUtils.readString(inputStream);
757             instanceSuperclass = IOUtils.readString(inputStream);
758             
759             objCount = IOUtils.readInt(inputStream);
760             if (objCount != 0) {
761                 indexDescs = new IndexDescriptor[objCount];
762                 for (int i = 0; i < objCount; i++) {
763                     indexDescs[i] = IndexDescriptor.readResolve(inputStream, this);
764                 }
765             }
766             
767             objCount = IOUtils.readInt(inputStream);
768             if (objCount > 0) {
769                 clAttrDescs = new HashMap(objCount * 2);
770                 clAttrValues = new HashMap(objCount * 2);
771                 for (int i = 0; i < objCount; i++) {
772                     AttributeDescriptor desc = AttributeDescriptor.readResolve(inputStream, this);
773                     clAttrDescs.put(desc.getName(), desc);
774                     Object JavaDoc value = IOUtils.read(inputStream, this, desc.getType().getName());
775                     if (value instanceof MOFID) {
776                         value = getMdrStorage().getRepository().getByMofId((MOFID) value);
777                     }
778                     clAttrValues.put(desc.getName(), value);
779                 }
780             }
781         } catch (IOException JavaDoc e) {
782             throw (DebugException) Logger.getDefault().annotate(new DebugException(), e);
783         }
784     }
785
786     public final class ReferenceDescriptor {
787         private org.netbeans.mdr.persistence.MOFID mofId;
788         private final org.netbeans.mdr.persistence.MOFID proxyId;
789         private final String JavaDoc endName;
790         private StorableAssociation proxy = null;
791
792         void replaceValues(Map table) {
793             if (mofId != null) {
794                 mofId = (org.netbeans.mdr.persistence.MOFID) table.get(mofId);
795             }
796         }
797
798         public ReferenceDescriptor(org.netbeans.mdr.persistence.MOFID mofId, org.netbeans.mdr.persistence.MOFID proxyId, String JavaDoc endName) {
799             this.mofId = mofId;
800             this.proxyId = proxyId;
801             this.endName = endName;
802         }
803         
804         public org.netbeans.mdr.persistence.MOFID getMofId() {
805             return mofId;
806         }
807
808         public org.netbeans.mdr.persistence.MOFID getAssociationId() {
809             return proxyId;
810         }
811
812         public String JavaDoc getEndName() {
813             return endName;
814         }
815
816         public synchronized StorableAssociation getAssociation() {
817             if (proxy == null) {
818                 try {
819                     proxy = (StorableAssociation) getMdrStorage().getObject(proxyId);
820                 } catch (StorageException e) {
821                     throw (DebugException) Logger.getDefault().annotate(new DebugException(), e);
822                 }
823             }
824             return proxy;
825         }
826
827         public boolean isFirstEnd() {
828             return getAssociation().getEnd2Name().equals(endName);
829         }
830
831     }
832
833     public static final class AttributeDescriptor {
834         private final int typeIndex;
835         private final int maxSize;
836         private final int minSize;
837         private final boolean unique;
838         private final boolean ordered;
839         private final boolean changeable;
840         private org.netbeans.mdr.persistence.MOFID mofId;
841         private final String JavaDoc name;
842
843         private final transient MdrStorage mdrStorage;
844         private transient boolean indexed = false;
845         private transient Class JavaDoc type = null;
846         private transient String JavaDoc storageId = null;
847
848         public AttributeDescriptor(MdrStorage storage, org.netbeans.mdr.persistence.MOFID mofId, String JavaDoc name, Class JavaDoc type, int minSize, int maxSize, boolean isUnique, boolean isOrdered, boolean isChangeable, String JavaDoc storageId) {
849             this(storage, mofId, name, storage.storageValues(storageId).store(type.getName()), minSize, maxSize, isUnique, isOrdered, isChangeable, storageId);
850             this.type = type;
851         }
852
853         public AttributeDescriptor(MdrStorage storage, org.netbeans.mdr.persistence.MOFID mofId, String JavaDoc name, int typeIndex, int minSize, int maxSize, boolean isUnique, boolean isOrdered, boolean isChangeable, String JavaDoc storageId) {
854             this.mdrStorage = storage;
855             this.typeIndex = typeIndex;
856             this.minSize = minSize;
857             this.maxSize = maxSize;
858             this.unique = isUnique;
859             this.ordered = isOrdered;
860             this.changeable = isChangeable;
861             this.mofId = mofId;
862             this.name = name;
863             this.storageId = storageId;
864         }
865
866         void replaceValues(Map table) {
867             if (mofId != null) {
868                 mofId = (org.netbeans.mdr.persistence.MOFID) table.get(mofId);
869             }
870         }
871
872         public Class JavaDoc getType() {
873             if (type == null) {
874                 try {
875                     type = BaseObjectHandler.resolveInterface((String JavaDoc) mdrStorage.storageValues(this.storageId).resolve(typeIndex));
876                 } catch (ClassNotFoundException JavaDoc e) {
877                     throw new DebugException();
878                 }
879             }
880             return type;
881         }
882
883         public int getTypeIndex() {
884             return typeIndex;
885         }
886
887         public int getMinSize() {
888             return minSize;
889         }
890
891         public int getMaxSize() {
892             return maxSize;
893         }
894
895         public boolean isMultivalued() {
896             return (maxSize > 1) || (maxSize == -1);
897         }
898
899         public boolean isUnique() {
900             return unique;
901         }
902
903         public boolean isOrdered() {
904             return ordered;
905         }
906
907         public boolean isChangeable() {
908             return changeable;
909         }
910
911         public org.netbeans.mdr.persistence.MOFID getMofId() {
912             return mofId;
913         }
914
915         public String JavaDoc getName() {
916             return name;
917         }
918
919         public void setIndexed(boolean indexed) {
920             this.indexed = indexed;
921         }
922
923         public boolean isIndexed() {
924             return indexed;
925         }
926
927         static AttributeDescriptor readResolve(java.io.InputStream JavaDoc stream, StorableClass storable) throws IOException JavaDoc {
928             return new AttributeDescriptor(storable.getMdrStorage(), IOUtils.readMOFID(stream, storable.getMdrStorage(),storable.getMofId()), IOUtils.readString(stream), IOUtils.readInt(stream), IOUtils.readInt(stream), IOUtils.readInt(stream), IOUtils.readBoolean(stream), IOUtils.readBoolean(stream), IOUtils.readBoolean(stream), MdrStorage.getStorageIdFromMofId (storable.getMofId()));
929         }
930
931         void write(java.io.OutputStream JavaDoc outputStream) throws IOException JavaDoc {
932             IOUtils.writeMOFID (outputStream, mofId, mdrStorage.getStorageById(storageId));
933             IOUtils.writeString(outputStream, name);
934             IOUtils.writeInt(outputStream, typeIndex);
935             IOUtils.writeInt(outputStream, minSize);
936             IOUtils.writeInt(outputStream, maxSize);
937             IOUtils.writeBoolean(outputStream, unique);
938             IOUtils.writeBoolean(outputStream, ordered);
939             IOUtils.writeBoolean(outputStream, changeable);
940         }
941     }
942     
943     static final class AssocEndDescriptor {
944         final MOFID mofId;
945         final String JavaDoc endName;
946         final boolean isAggregate;
947         
948         AssocEndDescriptor(MOFID mofId, String JavaDoc endName, boolean aggregate) {
949             this.mofId = mofId;
950             this.endName = endName;
951             this.isAggregate = aggregate;
952         }
953     }
954
955     public static final class IndexDescriptor {
956
957         private static final int ATTRIB_ID = 0;
958         private static final int ASSOC_END_ID = 1;
959         
960         private final String JavaDoc indexName;
961         private final Field [] fields;
962
963         public IndexDescriptor (String JavaDoc name, Field [] fields) {
964             this.indexName = name;
965             this.fields = fields;
966         }
967
968         public String JavaDoc getName () {
969             return indexName;
970         }
971
972         public Field [] getFields () {
973             return fields;
974         }
975
976         void write (java.io.OutputStream JavaDoc stream, StorableBaseObject storable) throws IOException JavaDoc {
977             IOUtils.writeString(stream, indexName);
978             IOUtils.writeInt(stream, fields.length);
979             for (int i = 0; i < fields.length; i++) {
980                 // Since reading of field id is not part of Field.read() method, we exclude it from write method too.
981
if (fields[i] instanceof Attrib) {
982                     IOUtils.writeInt(stream, ATTRIB_ID);
983                 } else {
984                     IOUtils.writeInt(stream, ASSOC_END_ID);
985                 }
986                 fields[i].write (stream, storable);
987             } // for
988
}
989         
990         static IndexDescriptor readResolve(java.io.InputStream JavaDoc stream, StorableBaseObject storable) throws IOException JavaDoc {
991             String JavaDoc indexName = IOUtils.readString(stream);
992             int fieldsCount = IOUtils.readInt(stream);
993             Field [] fields = new Field [fieldsCount];
994             for (int i = 0; i < fieldsCount; i++) {
995                 int id = IOUtils.readInt(stream);
996                 switch (id) {
997                     case ATTRIB_ID:
998                         fields[i] = new Attrib(null, null, false);
999                     break;
1000                    case ASSOC_END_ID:
1001                        fields[i] = new AssocEnd(null, null, false, null);
1002                } // switch
1003
fields[i].read (stream, storable);
1004            } // for
1005
return new IndexDescriptor (indexName, fields);
1006        }
1007    
1008        public static abstract class Field {
1009            protected org.netbeans.mdr.persistence.MOFID id;
1010            protected String JavaDoc name;
1011            protected boolean isOrdered;
1012            
1013            public Field (org.netbeans.mdr.persistence.MOFID id, String JavaDoc name, boolean ordered) {
1014                this.id = id;
1015                this.name = name;
1016                this.isOrdered = ordered;
1017            }
1018            
1019            public org.netbeans.mdr.persistence.MOFID getId () {
1020                return id;
1021            }
1022            
1023            public String JavaDoc getName () {
1024                return name;
1025            }
1026            
1027            public boolean isOrdered () {
1028                return isOrdered;
1029            }
1030            
1031            public void write (java.io.OutputStream JavaDoc stream, StorableBaseObject storable) throws IOException JavaDoc {
1032                IOUtils.writeMOFID(stream, id, storable.getMdrStorage(), storable.getMofId());
1033                IOUtils.writeString(stream, name);
1034                IOUtils.writeBoolean(stream, isOrdered);
1035            }
1036            
1037            public void read (java.io.InputStream JavaDoc stream, StorableBaseObject storable) throws IOException JavaDoc {
1038                id = IOUtils.readMOFID(stream, storable.getMdrStorage(), storable.getMofId());
1039                name = IOUtils.readString(stream);
1040                isOrdered = IOUtils.readBoolean(stream);
1041            }
1042        } // class Field
1043

1044        
1045        public static final class Attrib extends Field {
1046            
1047            public Attrib (org.netbeans.mdr.persistence.MOFID id, String JavaDoc name, boolean ordered) {
1048                super (id, name, ordered);
1049            }
1050            
1051            // no additional features required at the moment ...
1052

1053        } // class Attrib
1054

1055        
1056        public static final class AssocEnd extends Field {
1057            
1058            private org.netbeans.mdr.persistence.MOFID assocId;
1059
1060            public AssocEnd (org.netbeans.mdr.persistence.MOFID id, String JavaDoc name, boolean ordered, org.netbeans.mdr.persistence.MOFID assocId) {
1061                super (id, name, ordered);
1062                this.assocId = assocId;
1063            }
1064
1065            public org.netbeans.mdr.persistence.MOFID getAssociation () {
1066                return assocId;
1067            }
1068            
1069            public void write (java.io.OutputStream JavaDoc stream, StorableBaseObject storable) throws IOException JavaDoc {
1070                super.write (stream, storable);
1071                IOUtils.write (stream, assocId, storable);
1072            }
1073            
1074            public void read (java.io.InputStream JavaDoc stream, StorableBaseObject storable) throws IOException JavaDoc {
1075                super.read (stream, storable);
1076                assocId = (org.netbeans.mdr.persistence.MOFID) IOUtils.read(stream, storable);
1077            }
1078            
1079        } // class AssocEnd
1080

1081    } // IndexDescriptor
1082

1083}
1084
Popular Tags