KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > mdr > NBMDRepositoryImpl


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;
20
21 import org.netbeans.api.mdr.CreationFailedException;
22 import org.netbeans.api.mdr.MDRepository;
23 import org.netbeans.api.mdr.events.ExtentEvent;
24 import org.netbeans.api.mdr.events.MDRChangeEvent;
25 import org.netbeans.api.mdr.events.MDRChangeListener;
26 import org.netbeans.mdr.handlers.BaseObjectHandler;
27 import org.netbeans.mdr.handlers.ImmutableList;
28 import org.netbeans.mdr.handlers.InstanceHandler;
29 import org.netbeans.mdr.handlers.gen.TagSupport;
30 import org.netbeans.mdr.persistence.MOFID;
31 import org.netbeans.mdr.persistence.StorageBadRequestException;
32 import org.netbeans.mdr.persistence.StorageException;
33 import org.netbeans.mdr.persistence.btreeimpl.btreestorage.BtreeFactory;
34 import org.netbeans.mdr.storagemodel.*;
35 import org.netbeans.mdr.storagemodel.StorableClass.AttributeDescriptor;
36 import org.netbeans.mdr.util.DebugException;
37 import org.netbeans.mdr.util.Logger;
38 import org.netbeans.mdr.util.MountFailedException;
39 import org.netbeans.mdr.util.TransactionMutex;
40 import org.openide.util.Lookup;
41 import javax.jmi.model.*;
42 import javax.jmi.reflect.*;
43 import javax.jmi.xmi.XmiReader;
44 import java.lang.ref.ReferenceQueue JavaDoc;
45 import java.lang.ref.WeakReference JavaDoc;
46 import java.lang.reflect.Constructor JavaDoc;
47 import java.lang.reflect.InvocationTargetException JavaDoc;
48 import java.net.URL JavaDoc;
49 import java.util.*;
50
51 /** This is an implementation of MOF based repository.
52  *
53  * @author Petr Hrebejk, Martin Matula
54  */

55 public class NBMDRepositoryImpl implements MDRepository {
56     
57     /* -------------------------------------------------------------------- */
58     /* -- Private static constants ---------------------------------------- */
59     /* -------------------------------------------------------------------- */
60     
61     // private static final Collection instances = new HashSet();
62

63     private static final URL JavaDoc MOF_XML_URL = ModelPackage.class.getResource("resources/mof.xml");
64     private static final URL JavaDoc BOOTMOF_XML_URL = ModelPackage.class.getResource("resources/mof.xml");
65     
66     private static final String JavaDoc TAGID_INDEX = "org.netbeans.attributeIndex";
67     
68     private static final String JavaDoc PARAM_STORAGE_CLASS = "storage";
69     
70     private static final String JavaDoc TRANSIENT_TAG_ID = "org.netbeans.mdr.transient";
71     private static final String JavaDoc TAG_VALUE_TRUE = "true";
72     
73     public static final String JavaDoc BOOT_MOF = "BootMOF";
74     public static final String JavaDoc PURE_MOF = "MOF";
75     
76     /* -------------------------------------------------------------------- */
77     /* -- Private attributes ---------------------------------------------- */
78     /* -------------------------------------------------------------------- */
79     
80     private MdrStorage mdrStorage = null;
81     
82     private Map classProxies = null;
83     private Map associationProxies = null;
84     private Map classProxiesMofIds = null;
85     
86     private int waitCount = 0;
87
88     private final Map parameters;
89     
90     private Map constructorCache = new HashMap();
91     private Set shutdownListeners = new HashSet();
92     
93     /* -------------------------------------------------------------------- */
94     /* -- Chaches for JMI interfactes and implementation creation --------- */
95     /* -------------------------------------------------------------------- */
96     
97     /**
98      * Maps storage objects (instances of {@link StorableBaseObject}) to
99      * JMI compliant handler objects (instances of {@link RefBaseObject}).
100      */

101     private final Map facilityCache = new FacilityCache();
102     
103     /* --------------------------------------------------------------------- */
104     /* -- Constructors ----------------------------------------------------- */
105     /* --------------------------------------------------------------------- */
106     
107     /** Creates new {@link org.netbeans.api.mdr.MDRepository} with parameters
108      * given by system properties. The following system properties are
109      * evaluated:
110      *
111      * <table border cellspacing="1" cellpadding="2">
112      * <tr>
113      * <th>Property</th><th>Default</th><th>Description</th>
114      * </tr>
115      * <tr>
116      * <td><code>org.netbeans.mdr.storagemodel.StorageFactoryClassName</code></td>
117      * <td><code>org.netbeans.mdr.persistence.btreeimpl.btreestorage.BtreeFactory</code></td>
118      * <td>name of a class implementing {@link
119      * org.netbeans.mdr.persistence.StorageFactory}</td>
120      * </tr>
121      * <tr>
122      * <td><code>org.netbeans.mdr.persistence.Dir</code></td>
123      * <td>(no default)</td>
124      * <td>storage location</td>
125      * </tr>
126      * </table>
127      */

128     public NBMDRepositoryImpl() {
129         Properties props = System.getProperties();
130         String JavaDoc storageClass = props.getProperty("org.netbeans.mdr.storagemodel.StorageFactoryClassName", "org.netbeans.mdr.persistence.btreeimpl.btreestorage.BtreeFactory");
131         String JavaDoc storageFile = props.getProperty("org.netbeans.mdr.persistence.Dir");
132         String JavaDoc storageUUID = props.getProperty("org.netbeans.mdr.persistence.UUID");
133         
134         Logger.getDefault().log("Storage factory: " + storageClass);
135         
136         parameters = new HashMap();
137         parameters.put("storage", storageClass);
138         parameters.put(BtreeFactory.STORAGE_FILE_NAME, storageFile);
139         parameters.put(BtreeFactory.STORAGE_UUID, storageUUID);
140         
141         for (Enumeration e = props.propertyNames(); e.hasMoreElements();) {
142             String JavaDoc name = (String JavaDoc) e.nextElement();
143             if (name.startsWith("MDRStorageProperty.")) {
144                 parameters.put(name.substring(19), props.getProperty(name));
145             }
146         }
147         // instances.add(this);
148
}
149     
150     /** Creates new {@link org.netbeans.api.mdr.MDRepository} with given parameters.
151      * The following parameters are processed:
152      *
153      * <p><ol>
154      * <li><code>storage</code>: name of a class implementing {@link
155      * org.netbeans.mdr.persistence.StorageFactory}</li>
156      * <li><code>fileName</code>: storage location</li>
157      * </ol></p>
158      */

159     public NBMDRepositoryImpl(Map parameters) {
160         Logger.getDefault().log("Creating MDRepository implementation ...");
161         this.parameters = parameters;
162         // instances.add(this);
163
}
164     
165     /* -------------------------------------------------------------------- */
166     /* -- Implementation of org.netbeans.api.mdr.events.MDRChangeSource --- */
167     /* -------------------------------------------------------------------- */
168     
169     /** Registers a listener for receiving all event notifications.
170      *
171      * @param listener Object that implements {@link MDRChangeListener} interface.
172      */

173     public void addListener(MDRChangeListener listener) {
174         addListener(listener, MDRChangeEvent.EVENTMASK_ALL);
175     }
176     
177     /** Registers a listener for receiving event notifications.
178      * @param listener Object that implements {@link MDRChangeListener} interface.
179      * @param mask bitmask to filter types of events the listener listens on
180      */

181     public void addListener(MDRChangeListener listener, int mask) {
182         initCheck();
183         mdrStorage.getEventNotifier().REPOSITORY.addListener(listener, mask, mdrStorage);
184     }
185     
186     /** Removes listener from the list of objects registered for event notifications.
187      * @param listener Object that implements {@link MDRChangeListener} interface.
188      */

189     public void removeListener(MDRChangeListener listener) {
190         initCheck();
191         mdrStorage.getEventNotifier().REPOSITORY.removeListener(listener, mdrStorage);
192     }
193     
194     /** Removes listener from the list of objects registered for event notifications.
195      * @param listener Object that implements {@link MDRChangeListener} interface.
196      * @param mask determines type of the events the listeners stops to listen on
197      */

198     public void removeListener(MDRChangeListener listener, int mask) {
199         initCheck();
200         mdrStorage.getEventNotifier().REPOSITORY.removeListener(listener, mask, mdrStorage);
201     }
202     
203     public void enableEvents() {
204         initCheck();
205         mdrStorage.enableEvents();
206     }
207     
208     public void disableEvents() {
209         beginTrans(false);
210         mdrStorage.disableEvents();
211         endTrans();
212     }
213     
214     public MdrStorage getMdrStorage() {
215         initCheck();
216         return mdrStorage;
217     }
218     
219     /* -------------------------------------------------------------------- */
220     /* -- Implementation of org.netbeans.api.mdr.MDRepositry -------------- */
221     /* -------------------------------------------------------------------- */
222
223     public TransactionMutex getTransactionMutex() {
224         initCheck();
225         return mdrStorage.getRepositoryMutex();
226     }
227
228     public void beginTrans(boolean writeAccess) {
229         synchronized (this) {
230             initCheck();
231             waitCount++;
232         }
233         try {
234             mdrStorage.getRepositoryMutex().enter(writeAccess);
235         } catch (RuntimeException JavaDoc e) {
236             decrementWait();
237             throw e;
238         } catch (Error JavaDoc e) {
239             decrementWait();
240             throw e;
241         }
242     }
243     
244     private synchronized void decrementWait() {
245         waitCount--;
246     }
247     
248     public void endTrans() {
249         endTrans(false);
250     }
251     
252     public void endTrans(boolean rollback) {
253         initCheck();
254         try {
255             if (mdrStorage.getRepositoryMutex().leave(rollback)) {
256                 mdrStorage.enableEvents();
257             }
258         } catch (RuntimeException JavaDoc e) {
259             mdrStorage.enableEvents();
260             throw e;
261         } catch (Error JavaDoc e) {
262             mdrStorage.enableEvents();
263             throw e;
264         } finally {
265             decrementWait();
266         }
267     }
268     
269     /** Instantiates the MOF model package.
270      *
271      * @param substName the name of the new model
272      */

273     public RefPackage createExtent(String JavaDoc substName) throws CreationFailedException {
274         return createExtent(substName, null);
275     }
276     
277     /** Instantiates the outermost M2 package <code>metaPackage</code>
278      *
279      * @param substName the name of the new model
280      * @param metaPackage The meta-model to be instantiated. <code>null</code>
281      * is interpreted as the request to instantiate the MOF model
282      * package.
283      */

284     public RefPackage createExtent(String JavaDoc substName, RefObject metaPackage) throws CreationFailedException {
285         return createExtent(substName, metaPackage, null);
286     }
287     
288     /** Instantiates the outermost M2 package <code>metaPackage</code>
289      *
290      * @param substName the name of the new model
291      * @param metaPackage The meta-model to be instantiated. <code>null</code>
292      * is interpreted as the request to instantiate the MOF model
293      * package.
294      * @param existingInstances
295      */

296     public RefPackage createExtent(String JavaDoc substName, RefObject metaPackage, RefPackage[] existingInstances) throws CreationFailedException {
297         return createExtent(substName, metaPackage, existingInstances, null);
298     }
299     
300     /** Returns reference to an outermost package instance of a given name.
301      * @param name name of package instance to be returned
302      * @return reference to the outermost package instance or
303      * <code>null</code> if there is no package with the given name
304      */

305     public RefPackage getExtent(String JavaDoc name) {
306         StorablePackage pkg;
307         
308         initCheck();
309         
310         beginTrans(false);
311         try {
312             
313             try {
314                 // retrieve the package
315
pkg = mdrStorage.getContextOutermostPackage(name);
316             } catch (NullPointerException JavaDoc e) {
317                 pkg = null;
318             } catch ( StorageBadRequestException e ) {
319                 pkg = null;
320             } catch ( StorageException e ) {
321                 throw new DebugException("Storage exception: " + e);
322             }
323             // return the handler for the package
324
return (RefPackage) getHandler(pkg);
325         } finally {
326             endTrans();
327         }
328     }
329     
330     public boolean renameExtent(RefPackage extent, String JavaDoc newName) {
331         initCheck();
332         
333         boolean fail = true;
334         beginTrans(true);
335         try {
336             boolean result = mdrStorage.renameContext(((BaseObjectHandler) extent)._getMofId(), newName);
337             fail = false;
338             return result;
339         } catch (StorageException e) {
340             throw new DebugException("Renaming failed: " + e);
341         } finally {
342             endTrans(fail);
343         }
344     }
345     
346     /** Returns all name of registered outermost package instances,
347      * which can be passed to the {@link #getExtent(String)} method to obtain
348      * an outermost package instance.
349      *
350      * @return array of names of outermost package instances.
351      */

352     public String JavaDoc[] getExtentNames() {
353         initCheck();
354         
355         String JavaDoc result[] = new String JavaDoc[0];
356         beginTrans(false);
357         try {
358             result = (String JavaDoc[]) mdrStorage.getContexts().toArray(result);
359             return result;
360         } catch (StorageException e) {
361             throw (DebugException) Logger.getDefault().annotate(new DebugException(), e);
362         } finally {
363             endTrans();
364         }
365     }
366
367     /**
368      * Returns the object with the given <code>mofId</code>.
369      */

370     public RefBaseObject getByMofId(String JavaDoc mofId) {
371         return getByMofId(MOFID.fromString(mofId));
372     }
373     
374     public RefBaseObject getByMofId(MOFID mofId) {
375         initCheck();
376         beginTrans(false);
377         try {
378             StorableBaseObject storable = mdrStorage.getObject(mofId);
379             return getHandler(storable);
380         } catch (StorageException e) {
381             // ignore
382
} finally {
383             endTrans();
384         }
385         return null;
386     }
387     
388     public void removeHandler(MOFID mofId) {
389         synchronized (facilityCache) {
390             facilityCache.remove(mofId);
391         }
392     }
393      
394     public void addHandler(BaseObjectHandler handler) {
395         StorableBaseObject s = handler._getDelegate();
396         MOFID mofId = s.getMofId();
397         Object JavaDoc lock = s.getMdrStorage().getStorageByMofId(mofId);
398         if (lock == null)
399             lock = facilityCache;
400
401         synchronized (lock) {
402             synchronized (facilityCache) {
403                 facilityCache.put(mofId, handler);
404             }
405         }
406     }
407
408     /**
409      * Called on repository exit. Should perform all needed finalization actions.
410      */

411     public synchronized void shutdown() {
412         if (mdrStorage != null) {
413             try {
414                 while (waitCount > 0) {
415                     try {
416                         this.wait(100);
417                     } catch (InterruptedException JavaDoc e) {
418                         Logger.getDefault().notify(Logger.INFORMATIONAL, e);
419                     }
420                 }
421                 mdrStorage.shutDown();
422             } catch (StorageException e) {
423                 throw (DebugException) Logger.getDefault().annotate(new DebugException(), e);
424             } finally {
425                 mdrStorage = null;
426             }
427         }
428         notifyShutdownListeners();
429         notifyShutdownStep();
430     }
431     
432     /* -------------------------------------------------------------------- */
433     /* -- Extending java.lang.Object -------------------------------------- */
434     /* -------------------------------------------------------------------- */
435     
436     public String JavaDoc toString() {
437         StringBuffer JavaDoc sb = new StringBuffer JavaDoc("IDE MOF Repository");
438         return sb.toString();
439     }
440     
441     /* -------------------------------------------------------------------- */
442     /* -- Create an outermost package instance ---------------------------- */
443     /* -------------------------------------------------------------------- */
444     
445     /** Instantiates the outermost M2 package <code>metaPackage</code>
446      *
447      * @param substName the name of the new model
448      * @param metaPackage The meta-model to be instantiated. <code>null</code>
449      * is interpreted as the request to instantiate the MOF model
450      * package.
451      * @param existingInstances
452      * @param storageId id of the storage partition
453      */

454     public RefPackage createExtent(String JavaDoc substName, RefObject metaPackage, RefPackage[] existingInstances, String JavaDoc storageId) throws CreationFailedException {
455         initCheck();
456         
457         RefPackage result;
458
459         boolean fail = true;
460         if (metaPackage == null) {
461             metaPackage = getMOFModelPackage();
462         }
463
464         beginTrans(true);
465         try {
466             if (getExtent(substName) != null) {
467                 throw new CreationFailedException("Package extent named \'" + substName + "\' already exists.");
468             }
469             if (mdrStorage.eventsEnabled()) {
470                 ExtentEvent event = new ExtentEvent(
471                     this,
472                     ExtentEvent.EVENT_EXTENT_CREATE,
473                     substName,
474                     metaPackage,
475                     new ImmutableList(existingInstances)
476                 );
477                 mdrStorage.getEventNotifier().REPOSITORY.firePlannedChange(mdrStorage, event);
478             }
479             Map instancesToCluster = new HashMap();
480
481             // Traverse the metamodel containtment
482
classProxies = new HashMap();
483             associationProxies = new HashMap();
484             classProxiesMofIds = new HashMap();
485
486             if (existingInstances != null) {
487                 for (int i = 0; i < existingInstances.length; i++) {
488                     collectPackageInstances(existingInstances[i], instancesToCluster);
489                 }
490             }
491             try {
492                 instantiatePackage(substName, null, (MofPackage) metaPackage, instancesToCluster, storageId, false);
493             } catch (RuntimeException JavaDoc e) {
494                 throw (CreationFailedException) Logger.getDefault().annotate(new CreationFailedException("Cannot instantiate package because of unexpected exception: " + e), e);
495             }
496             
497             classProxies = null;
498             associationProxies = null;
499             classProxiesMofIds = null;
500
501             result = getExtent(substName);
502             if (result == null) {
503                 throw new CreationFailedException("Cannot find created package.");
504             }
505
506             fail = false;
507         } finally {
508             endTrans(fail);
509         }
510
511         return result;
512     }
513
514     /* -------------------------------------------------------------------- */
515     /* -- Storage partitions ---------------------------------------------- */
516     /* -------------------------------------------------------------------- */
517   
518     /**
519      * Mounts new partition into current repository,
520      * The partition is created and initialized, if it does not exist.
521      * @param storageFactoryClass name of storage factory class, which will create a new storage.
522      * Mounts new partition into current repository,
523      * The partition is created and initialized, if it does not exist.
524      * @param properties storage specific parameters (e.g. name of file for BTree)
525      * @return String id.
526      * @exception MountFailedException thrown when mounting fails.
527      */

528     public String JavaDoc mountStorage(String JavaDoc storageFactoryClass, Map properties) throws MountFailedException {
529         boolean failed = true;
530         beginTrans(true);
531         try {
532             // Firing of event is done inside a MdrStorage mountStorage method
533
String JavaDoc storageId = this.mdrStorage.mountStorage(storageFactoryClass, properties);
534             failed = false;
535             return storageId;
536         }catch (Exception JavaDoc e) {
537             e.printStackTrace();
538             throw new MountFailedException("Partition mount failed.", e);
539         }
540         finally {
541             endTrans(failed);
542         }
543     }
544     
545     /**
546      * Unmounts partition from current repository.
547      * Unmounting partition can affect validity of association links
548      * which cross partitions. Module developer is responsible for
549      * either removing cross partition links or handling exceptions
550      * caused by accessing these links.
551      * @param storageId id of storage.
552      */

553     public void unmountStorage(String JavaDoc storageId) {
554         boolean failed = true;
555         beginTrans(true);
556         try {
557             if (mdrStorage.eventsEnabled()) {
558                 Collection c = mdrStorage.getContexts(storageId);
559                 for (Iterator it = c.iterator(); it.hasNext();) {
560                     String JavaDoc extentName = (String JavaDoc)it.next();
561                     RefPackage pkg = this.getExtent(extentName);
562                     ExtentEvent event = new ExtentEvent(pkg, ExtentEvent.EVENT_EXTENT_DELETE, extentName, pkg.refMetaObject(), null);
563                     this.mdrStorage.getEventNotifier().PACKAGE.firePlannedChange(pkg, event);
564                 }
565             }
566             this.mdrStorage.unmountStorage(storageId);
567             failed = false;
568         }catch (StorageException e) {
569             throw new DebugException("Unmounting failed: "+e.toString());
570         }
571         finally {
572             endTrans(failed);
573         }
574     }
575     
576     /* -------------------------------------------------------------------- */
577     /* -- Public methods not specified by any interface ------------------- */
578     /* -------------------------------------------------------------------- */
579     
580     /** Gets JNDI name of connection to MOF model package. This package
581      * should be instantiated to create new metamodels.
582      */

583     public String JavaDoc getMOFInstanceName() {
584         return PURE_MOF;
585     }
586     
587     public String JavaDoc getParameter(String JavaDoc name) {
588         return (String JavaDoc) parameters.get(name);
589     }
590     
591     /* --------------------------------------------------------------------- */
592     /* -- Methods for working with handlers -------------------------------- */
593     /* --------------------------------------------------------------------- */
594
595     /**
596      * Frees the caches of JMI compliant handler objects (for storage objects)
597      * and of JMI implementation classes (for meta-objects).
598      */

599     public void freeCache() {
600         facilityCache.clear();
601     }
602     
603     public RefBaseObject getHandler(MOFID mofId) {
604         synchronized (facilityCache) {
605             return (BaseObjectHandler) (facilityCache.get(mofId));
606         }
607     }
608     
609     /**
610      * Returns JMI compliant handler object for <code>s</code>.
611      *
612      * @param s the storage object to be wrapped or <code>null</code>
613      * @return handler implementing JMI interface or <code>null</code>
614      */

615     public RefBaseObject getHandler(StorableBaseObject s) {
616         if (s == null) {
617             return null;
618         }
619
620         RefBaseObject refBO = getHandler(s.getMofId());
621         if (refBO == null) {
622             Class JavaDoc ifc = BaseObjectHandler.resolveClass(s);
623             refBO = getHandler(s, ifc);
624         }
625         return refBO;
626     }
627     
628     /**
629      * Returns JMI compliant handler object for <code>s</code>.
630      *
631      * @param s the storage object to be wrapped or <code>null</code>
632      * @param ifc the JMI interface to be implemented by the handler
633      * @return handler implementing JMI interface or <code>null</code>
634      */

635     public RefBaseObject getHandler(StorableBaseObject s, Class JavaDoc ifc) {
636     if (s == null) {
637         return null;
638     }
639
640         /* load the handler class */
641     Class JavaDoc cl = BaseObjectHandler.getHandlerClass(ifc, s);
642
643     try {
644             Class JavaDoc cls = s.getClass();
645             if (cls.equals (TransientStorableClass.class)) {
646                 cls = StorableClass.class;
647             }
648             else if (cls.equals (TransientStorableObject.class)) {
649                 cls = StorableObject.class;
650             }
651             else if (cls.equals (TransientStorableAssociation.class)) {
652                 cls = StorableAssociation.class;
653             }
654             else if ((cls != StorableObject.class) && (StorableObject.class.isAssignableFrom(cls))) {
655                 cls = StorableObject.class;
656             }
657             /* create handler object, if necessary */
658             MOFID mofId = s.getMofId();
659             Object JavaDoc lock = s.getMdrStorage().getStorageByMofId(mofId);
660             if (lock == null)
661                 lock = facilityCache;
662             
663             synchronized (lock) {
664                 synchronized (facilityCache) {
665                     Object JavaDoc oldRecord = facilityCache.get(mofId);
666                     if (oldRecord == null) {
667                         Constructor JavaDoc cons = (Constructor JavaDoc) constructorCache.get(cl);
668                         
669                         if (cons == null) {
670                             cons = cl.getConstructor(new Class JavaDoc[] {cls});
671                             constructorCache.put(cl,cons);
672                         }
673                         oldRecord = cons.newInstance(new Object JavaDoc[] {s});
674                         facilityCache.put(mofId, oldRecord);
675                     }
676                     return (BaseObjectHandler) oldRecord;
677                 }
678             }
679     } catch (NoSuchMethodException JavaDoc e) {
680             throw (DebugException) Logger.getDefault().annotate(new DebugException(), e);
681     } catch (IllegalAccessException JavaDoc e) {
682             throw (DebugException) Logger.getDefault().annotate(new DebugException(), e);
683     } catch (InstantiationException JavaDoc e) {
684             throw (DebugException) Logger.getDefault().annotate(new DebugException(), e);
685     } catch (InvocationTargetException JavaDoc e) {
686             throw (DebugException) Logger.getDefault().annotate(new DebugException(), e);
687     }
688     }
689     
690     /* -------------------------------------------------------------------- */
691     /* -- Shutdown listeners support -------------------------------------- */
692     /* -------------------------------------------------------------------- */
693     
694     public void addShutdownListener(ShutdownListener listener) {
695         synchronized (shutdownListeners) {
696             shutdownListeners.add(listener);
697         }
698     }
699     
700     public void removeShutdownListener(ShutdownListener listener) {
701         synchronized (shutdownListeners) {
702             shutdownListeners.remove(listener);
703         }
704     }
705     
706     private void notifyShutdownListeners() {
707         synchronized (shutdownListeners) {
708             for (Iterator iter = shutdownListeners.iterator(); iter.hasNext();) {
709                 ShutdownListener listener = (ShutdownListener) iter.next();
710                 listener.shutdown();
711             }
712         }
713     }
714     
715     public int getShutdownSteps() {
716         return mdrStorage != null ? mdrStorage.getShutdownSteps() + 1 : 1;
717     }
718     
719     public void notifyShutdownStep() {
720         synchronized (shutdownListeners) {
721             for (Iterator iter = shutdownListeners.iterator(); iter.hasNext();) {
722                 ShutdownListener listener = (ShutdownListener) iter.next();
723                 listener.stepFinished();
724             }
725         }
726     }
727     
728     /* -------------------------------------------------------------------- */
729     /* -- Private helper methods ------------------------------------------ */
730     /* -------------------------------------------------------------------- */
731     
732     /** Returns the M3 version of the MOF Model package, i.e. the MOF Model
733      * as a model element of the MOF model. */

734     private MofPackage getMOFModelPackage() {
735         ModelPackage mofPackage = (ModelPackage) getExtent(getMOFInstanceName());
736         MofPackage result;
737         
738         for (Iterator it = mofPackage.getMofPackage().refAllOfClass().iterator(); it.hasNext();) {
739             result = (MofPackage) it.next();
740             if (result.getName().equals("Model")) {
741                 return result;
742             }
743         }
744         
745         return null;
746     }
747     
748     /**
749      * Initializes the repository, if not already initialized: creates and
750      * initializes the {@link org.netbeans.mdr.storagemodel.MdrStorage}. If
751      * necessary the repository is bootstrapped.
752      */

753     private synchronized void initCheck() {
754         if (mdrStorage == null) {
755             String JavaDoc storageClass = (String JavaDoc) parameters.get(PARAM_STORAGE_CLASS);
756             
757             mdrStorage = new MdrStorage(this, storageClass, this.parameters);
758             try {
759                 Logger.getDefault().log("initializing...");
760                 // initialize storage
761
if (!mdrStorage.init()) {
762                     Logger.getDefault().log("booting...");
763                     // bootstrapping the repository
764
boot();
765                 }
766                 return;
767             } catch (StorageException e) {
768                 throw (DebugException) Logger.getDefault().annotate(new DebugException("Fatal error: Repository boot/initialization failed with message: " + e.getMessage()), e);
769             }
770         }
771     }
772     
773     /* -------------------------------------------------------------------- */
774     /* -- Helper methods for extent creation (private) -------------------- */
775     /* -------------------------------------------------------------------- */
776     
777     /**
778      * Helper method needed for the creation of a new outermost package instance.
779      * Puts <code>pkg</code> and, recursively, all its nested packages
780      * into <code>packages</code>.
781      *
782      * @param pkg package instance
783      * @param packages map containing package instances as value and the MOF IDs
784      * of their meta-objects as key
785      * @exception CreationFailedException if two different packages with the
786      * same keys are added to <code>packages</code>
787      *
788      */

789     private void collectPackageInstances(RefPackage pkg, Map packages) throws CreationFailedException {
790         Object JavaDoc result = packages.put(((BaseObjectHandler)pkg.refMetaObject())._getDelegate().getMofId(), pkg);
791         if (result != null && !result.equals(pkg)) {
792             throw new CreationFailedException("The provided list of existing package instances contains duplicities.");
793         }
794         for (Iterator it = pkg.refAllPackages().iterator(); it.hasNext();) {
795             RefPackage nested = (RefPackage) it.next();
796             collectPackageInstances(nested, packages);
797         }
798     }
799     
800     /** Instantiates given package, i.e. packageProxies, classProxies,
801      * associationProxies.
802      *
803      * @param substName the name of the new model
804      * @param metaPackage outermost M2 package
805      * @param clusteredInstances maps MOF IDs of M2 packages to M1 package instances
806      * @param storageId ID of the storage partition
807      */

808     private RefPackage instantiatePackage(String JavaDoc substName, StorablePackage immediatePackage, MofPackage metaPackage, Map clusteredInstances, String JavaDoc storageId, boolean clustered) {
809         // Create package proxy
810
StorablePackage newPackage = createPackageHandler(metaPackage, immediatePackage, substName, storageId, clustered);
811         RefPackage result = (RefPackage) getHandler(newPackage);
812         Logger.getDefault().log("new package: " + newPackage.getMofId() + ", metapackage: " + metaPackage.refMofId());
813         
814         Set localAssocProxies = new HashSet();
815         List localClassProxies = new ArrayList();
816         instantiatePackageContent(metaPackage, newPackage, clusteredInstances, localClassProxies, localAssocProxies, storageId);
817         resolveSuperclasses(metaPackage, localClassProxies);
818         resolveAssociations(localAssocProxies);
819
820         return result;
821     }
822     
823     private void resolveAssociations(Collection localAssocProxies) {
824         try {
825             for (Iterator it = localAssocProxies.iterator(); it.hasNext();) {
826                 MOFID saMofId = (MOFID) it.next();
827                 StorableAssociation sa = (StorableAssociation) mdrStorage.getObject(saMofId);
828                 if (!((Association) getHandler(sa.getMetaObject())).isDerived()) {
829                     Object JavaDoc metaCls = ((AssociationEnd) getByMofId(sa.getEnd1Id())).getType();
830                     StorableClass cls = (StorableClass) classProxies.get(metaCls);
831                     cls.addAssociationEnd(saMofId, sa.getEnd1Name(), sa.isAggregateA());
832                     metaCls = ((AssociationEnd) getByMofId(sa.getEnd2Id())).getType();
833                     cls = (StorableClass) classProxies.get(metaCls);
834                     if (cls != null) {
835                         cls.addAssociationEnd(saMofId, sa.getEnd2Name(), sa.isAggregateB());
836                     }
837                 }
838             }
839         } catch (StorageException e) {
840             throw (DebugException) Logger.getDefault().annotate(new DebugException(), e);
841         }
842     }
843     
844     /**
845      * @param localClassProxies
846      */

847     private void resolveSuperclasses(MofPackage metaPackage, List localClassProxies) {
848         StorableClass sc;
849         ModelElement me;
850         AssociationEnd end;
851         StorableClass current;
852         MofClass cls;
853         List indexTags;
854         
855         Map indexes = new HashMap ();
856         if (!localClassProxies.isEmpty ()) {
857             ModelPackage modelPackage = (ModelPackage) metaPackage.refImmediatePackage();
858             Iterator iter = modelPackage.getTag ().refAllOfClass ().iterator ();
859             while (iter.hasNext ()) {
860                 Tag tag = (Tag) iter.next ();
861                 if (TAGID_INDEX.equals (tag.getTagId ())) {
862                     Iterator elements = tag.getElements ().iterator ();
863                     MofClass tempOwner = null, owner = null;
864                     boolean oneClass = true;
865                     while (elements.hasNext ()) {
866                         ModelElement elem = (ModelElement) elements.next ();
867                         if (elem instanceof MofClass) {
868                             oneClass = true;
869                             owner = (MofClass) elem;
870                             break;
871                         } else {
872                             if (elem instanceof Attribute)
873                                 tempOwner = (MofClass) elem.getContainer ();
874                             else if (elem instanceof AssociationEnd)
875                                 tempOwner = (MofClass) ((AssociationEnd) elem).otherEnd ().getType ();
876                             if ((owner == null) && (tempOwner != null))
877                                 owner = tempOwner;
878                             else
879                                 oneClass = oneClass && (owner == tempOwner);
880                         }
881                     } // while
882
if ((owner != null) && oneClass) {
883                         List tags = (List) indexes.get (owner);
884                         if (tags == null)
885                             indexes.put (owner, tags = new LinkedList ());
886                         tags.add (tag);
887                     }
888                 } // if
889
} // while
890
} // if
891

892         for (Iterator it = localClassProxies.iterator(); it.hasNext();) {
893             sc = (StorableClass) it.next();
894             try {
895                 cls = (MofClass) getHandler(sc.getMetaObject());
896             } catch (StorageException e) {
897                 throw (DebugException) Logger.getDefault().annotate(new DebugException(), e);
898             }
899             for (Iterator supers = cls.getSupertypes().iterator(); supers.hasNext();) {
900                 Object JavaDoc superMeta = supers.next();
901                 current = ((StorableClass) classProxies.get(superMeta));
902                 if (current == null) {
903                     throw new DebugException("Package definition is incomplete: class " + cls.getName() + " super = " + ((superMeta instanceof MofClass) ? ((MofClass) superMeta).getName() : superMeta));
904                 }
905                 sc.addSuperclass(current.getMofId());
906                 current.addSubclass(sc.getMofId());
907             }
908             for (Iterator contents = cls.getContents().iterator(); contents.hasNext();) {
909                 me = (ModelElement) contents.next();
910                 if (me instanceof Reference JavaDoc) {
911                     end = ((Reference JavaDoc) me).getExposedEnd();
912                     //Logger.getDefault().log("registering reference: " + me.getName() + " for end: " + end.getName());
913
sc.addReferenceDescriptor(((BaseObjectHandler)me)._getDelegate().getMofId(), me.getName(), (MOFID) associationProxies.get(((BaseObjectHandler)end.getContainer())._getDelegate().getMofId()), end.getName());
914                 }
915             } // for
916
indexTags = (List) indexes.get (cls);
917             if (indexTags != null) {
918                 try {
919                     sc.buildAdditionalIndexes (indexTags, associationProxies);
920                 } catch (StorageException e) {
921                     throw new DebugException ("Storage exception: " + e);
922                 }
923             }
924         } // for
925

926         Class JavaDoc iface[] = new Class JavaDoc[1];
927         for (Iterator it = localClassProxies.iterator(); it.hasNext();) {
928             sc = (StorableClass) it.next();
929             try {
930                 iface[0] = null;
931                 sc.initInstanceSuperclass(iface);
932                 sc.initClassSuperclass(null);
933             } catch (Exception JavaDoc e) {
934                 throw (DebugException) Logger.getDefault().annotate(new DebugException(), e);
935             }
936         }
937     }
938     
939     /**
940      * @param metaPackage
941      * @param newPackage
942      * @param clusteredInstances
943      * @param localClassProxies
944      * @param localAssocProxies
945      */

946     private void instantiatePackageContent(MofPackage metaPackage, StorablePackage newPackage, Map clusteredInstances, List localClassProxies, Set localAssocProxies, String JavaDoc storageId) {
947         Iterator superTypes = metaPackage.allSupertypes().iterator();
948         boolean thisTypeNotProcessed = true;
949         while (thisTypeNotProcessed || superTypes.hasNext()) {
950             Iterator it;
951             if (thisTypeNotProcessed) {
952                 it = metaPackage.getContents().iterator();
953                 thisTypeNotProcessed = false;
954             } else
955                 it = ((MofPackage) superTypes.next()).getContents().iterator();
956             
957             while (it.hasNext()) {
958                 Object JavaDoc o = it.next();
959                 ModelElement element = (ModelElement) o;
960                 
961                 if (element instanceof MofClass) {
962                     createClassProxyHandler((MofClass) element, newPackage, localClassProxies);
963                 } else if (element instanceof Association) {
964                     Association assoc = (Association) element;
965                     
966                     Collection content = assoc.getContents();
967                     int i = 0;
968                     AssociationEnd ends[] = new AssociationEnd[2];
969                     for(Iterator cit = content.iterator(); i < 2 && cit.hasNext();) {
970                         ModelElement containedElement = (ModelElement) cit.next();
971                         if (containedElement instanceof AssociationEnd) {
972                             ends[i++] = (AssociationEnd) containedElement;
973                         }
974                     }
975                     // Change multiplicities
976
boolean orderA, orderB, uniqueA, uniqueB, aggrA, aggrB, indexedA, indexedB;
977                     int minA, maxA, minB, maxB;
978                     Class JavaDoc typeA, typeB;
979                     
980                     minA = ends[0].getMultiplicity().getLower();
981                     maxA = ends[0].getMultiplicity().getUpper();
982                     minB = ends[1].getMultiplicity().getLower();
983                     maxB = ends[1].getMultiplicity().getUpper();
984                     try {
985                         typeA = BaseObjectHandler.resolveInterface(TagSupport.getDataTypeName((StorableObject)((InstanceHandler)ends[0].getType())._getDelegate()));
986                         typeB = BaseObjectHandler.resolveInterface(TagSupport.getDataTypeName((StorableObject)((InstanceHandler)ends[1].getType())._getDelegate()));
987                     } catch (java.lang.Exception JavaDoc e) {
988                         throw (DebugException) Logger.getDefault().annotate(new DebugException(), e);
989                     }
990                     orderA = (ends[0].getMultiplicity().isOrdered());
991                     orderB = (ends[1].getMultiplicity().isOrdered());
992                     uniqueA = (ends[0].getMultiplicity().isUnique());
993                     uniqueB = (ends[1].getMultiplicity().isUnique());
994                     
995                     aggrA = ends[0].getAggregation().equals(AggregationKindEnum.COMPOSITE);
996                     aggrB = ends[1].getAggregation().equals(AggregationKindEnum.COMPOSITE);
997                     
998                     indexedA = TagSupport.getTagValue((StorableObject) ((BaseObjectHandler) ends[0])._getDelegate(), TAGID_INDEX) != null;
999                     indexedB = TagSupport.getTagValue((StorableObject) ((BaseObjectHandler) ends[1])._getDelegate(), TAGID_INDEX) != null;
1000                    if (TagSupport.getTagValue((StorableObject) ((BaseObjectHandler) ends[0].getType())._getDelegate(), TRANSIENT_TAG_ID, "").equals(TAG_VALUE_TRUE)
1001                    || TagSupport.getTagValue((StorableObject) ((BaseObjectHandler) ends[1].getType())._getDelegate(), TRANSIENT_TAG_ID, "").equals(TAG_VALUE_TRUE)) {
1002                        createTransientAssociationHandler((Association) element, newPackage, ends[0].getName(), ((BaseObjectHandler)ends[0])._getDelegate().getMofId(), ends[1].getName(),((BaseObjectHandler)ends[1])._getDelegate().getMofId(), typeA, typeB, minA, maxA, minB, maxB, orderA, orderB, uniqueA, uniqueB, aggrA, aggrB, localAssocProxies);
1003                    }
1004                    else {
1005                        createAssociationHandler((Association) element, newPackage, ends[0].getName(), ((BaseObjectHandler)ends[0])._getDelegate().getMofId(), ends[1].getName(), ((BaseObjectHandler)ends[1])._getDelegate().getMofId(), typeA, typeB, minA, maxA, minB, maxB, orderA, orderB, uniqueA, uniqueB, aggrA, aggrB, indexedA, indexedB, localAssocProxies);
1006                    }
1007                    
1008                } else if (element instanceof MofPackage) {
1009                    // Logger.getDefault().log("found inner package");
1010
// Logger.getDefault().log("creating: META: " + element.refMofId() + ", IMMEDIATE: " + newPackage.refMofId() + ", CONTEXT: " + context);
1011
StorablePackage pkg = createPackageHandler((MofPackage) element, newPackage, null, storageId, false);
1012                    instantiatePackageContent((MofPackage) element, pkg, clusteredInstances, localClassProxies, localAssocProxies, storageId);
1013                } else if (element instanceof Import) {
1014                    Import imp = (Import) element;
1015                    ModelElement metaElement = imp.getImportedNamespace();
1016                    if (metaElement instanceof MofPackage) {
1017                        MofPackage metaPkg = (MofPackage) metaElement;
1018                        collectDTDescriptors(storageId, metaPkg, new HashSet());
1019                        if (imp.isClustered()) {
1020                            RefPackage pkg = (RefPackage) clusteredInstances.get(((BaseObjectHandler)metaPkg)._getDelegate().getMofId());
1021                            if (pkg == null) {
1022                                pkg = instantiatePackage(null, newPackage, metaPkg, clusteredInstances, storageId, true);
1023                                clusteredInstances.put(((BaseObjectHandler)metaPkg)._getDelegate().getMofId(), pkg);
1024                            } else {
1025                                collectAllProxies(pkg);
1026                            }
1027                            try {
1028                                newPackage.clusterPackage(imp.getName(), ((BaseObjectHandler)pkg)._getDelegate().getMofId());
1029                            } catch (StorageException e) {
1030                                throw (DebugException) Logger.getDefault().annotate(new DebugException(), e);
1031                            }
1032                        } // if
1033
} else if (metaElement instanceof EnumerationType) {
1034                        createDTDescriptor(storageId, (EnumerationType) metaElement);
1035                    } else if (metaElement instanceof StructureType) {
1036                        createDTDescriptor(storageId, (StructureType) metaElement);
1037                    } else if (metaElement instanceof MofClass) {
1038                        collectDTDescriptors(storageId, (MofClass) metaElement, new HashSet());
1039                    }
1040                } // if
1041
} // while
1042
} // while
1043
}
1044    
1045    private void collectDTDescriptors(String JavaDoc storageId, GeneralizableElement metaElement, Set visited) {
1046        Iterator superTypes = metaElement.allSupertypes().iterator();
1047        boolean thisTypeNotProcessed = true;
1048        while (thisTypeNotProcessed || superTypes.hasNext()) {
1049            Iterator it;
1050            if (thisTypeNotProcessed) {
1051                it = metaElement.getContents().iterator();
1052                thisTypeNotProcessed = false;
1053            } else {
1054                GeneralizableElement ge = (GeneralizableElement) superTypes.next();
1055                if (!visited.add(ge)) continue;
1056                it = ge.getContents().iterator();
1057            }
1058            
1059            collectDTDescriptors(storageId, it, visited);
1060        }
1061    }
1062    
1063    private void collectDTDescriptors(String JavaDoc storageId, Iterator it, Set visited) {
1064        while (it.hasNext()) {
1065            Object JavaDoc element = it.next();
1066            if (element instanceof MofPackage || element instanceof MofClass) {
1067                if (visited.add(element)) {
1068                    collectDTDescriptors(storageId, (GeneralizableElement) element, visited);
1069                }
1070            } else if (element instanceof EnumerationType) {
1071                createDTDescriptor(storageId, (EnumerationType) element);
1072            } else if (element instanceof StructureType) {
1073                createDTDescriptor(storageId, (StructureType) element);
1074            }
1075        }
1076    }
1077    
1078    /**
1079     * Fills {@link #associationProxies}, {@link #classProxies} and
1080     * {@link #classProxiesMofIds} with the proxies contained in <code>pkg</code>
1081     * and all nested packages.
1082     *
1083     * @param pkg the package for which to collect all proxies
1084     */

1085    private void collectAllProxies(RefPackage pkg) {
1086        for (Iterator it = pkg.refAllAssociations().iterator(); it.hasNext();) {
1087            RefAssociation assoc = (RefAssociation) it.next();
1088            if (associationProxies.put(((BaseObjectHandler)assoc.refMetaObject())._getDelegate().getMofId(), ((BaseObjectHandler)assoc)._getDelegate().getMofId()) != null) {
1089                // this package was already collected
1090
return;
1091            }
1092        }
1093        
1094        for (Iterator it = pkg.refAllClasses().iterator(); it.hasNext();) {
1095            RefClass cls = (RefClass) it.next();
1096            if (classProxiesMofIds.put(((BaseObjectHandler)cls.refMetaObject())._getDelegate().getMofId(), ((BaseObjectHandler)cls)._getDelegate().getMofId()) != null) {
1097                // this package was already collected
1098
return;
1099            }
1100            classProxies.put(cls.refMetaObject(), ((BaseObjectHandler) cls)._getDelegate());
1101        }
1102        
1103        for (Iterator it = pkg.refAllPackages().iterator(); it.hasNext();) {
1104            collectAllProxies((RefPackage) it.next());
1105        }
1106    }
1107    
1108    /* -------------------------------------------------------------------- */
1109    /* -- Helper methods for handler creation (private) ------------------- */
1110    /* -------------------------------------------------------------------- */
1111    // --- creators
1112

1113    /** Creates handler for Package Proxy */
1114    private StorablePackage createPackageHandler(MofPackage metaObject,StorablePackage immediatePackage, String JavaDoc context, String JavaDoc storageId, boolean clustered) {
1115        try {
1116            Map datatypes = new HashMap();
1117            // collect datatypes
1118
Iterator supers = null;
1119            
1120            while (supers == null || supers.hasNext()) {
1121                MofPackage metaPackage;
1122                if (supers == null) {
1123                    supers = metaObject.allSupertypes().iterator();
1124                    metaPackage = metaObject;
1125                } else {
1126                    metaPackage = (MofPackage) supers.next();
1127                }
1128                for (Iterator it = metaPackage.getContents().iterator(); it.hasNext();) {
1129                    ModelElement element = (ModelElement) it.next();
1130                    if (element instanceof EnumerationType) {
1131                        datatypes.put(element.getName(), createDTDescriptor(storageId, (EnumerationType) element));
1132                    } else if (element instanceof StructureType) {
1133                        datatypes.put(element.getName(), createDTDescriptor(storageId, (StructureType) element));
1134                    }
1135                }
1136            }
1137            
1138            StorablePackage result = null;
1139            if (storageId != null) {
1140                result = new StorablePackage(mdrStorage, immediatePackage == null ? null : immediatePackage.getMofId(), ((BaseObjectHandler)metaObject)._getDelegate().getMofId(), context, datatypes, storageId);
1141            }
1142            else {
1143                result = new StorablePackage(mdrStorage, immediatePackage == null ? null : immediatePackage.getMofId(), ((BaseObjectHandler)metaObject)._getDelegate().getMofId(), context, datatypes);
1144            }
1145            if (immediatePackage != null && !clustered) {
1146                immediatePackage.addPackage(metaObject.getName(), result.getMofId());
1147            }
1148            
1149            return result;
1150        } catch ( StorageException e ) {
1151            throw new DebugException("Storage exception: " + e.getMessage());
1152        }
1153    }
1154    
1155    private DatatypeDescriptor createDTDescriptor(String JavaDoc storageId, EnumerationType e) {
1156        List members = new ArrayList(e.getLabels());
1157        String JavaDoc ifcName = TagSupport.getTypeFullName((StorableObject) ((BaseObjectHandler) e)._getDelegate());
1158        return new DatatypeDescriptor(mdrStorage, members, ifcName, storageId);
1159    }
1160    
1161    private DatatypeDescriptor createDTDescriptor(String JavaDoc storageId, StructureType struct) {
1162        ModelElement me;
1163        List members = new ArrayList();
1164        List memberTypes = new ArrayList();
1165
1166        for (Iterator it2 = struct.getContents().iterator(); it2.hasNext();) {
1167            me = (ModelElement) it2.next();
1168            if (me instanceof StructureField) {
1169                members.add(me.getName());
1170                try {
1171                    memberTypes.add(BaseObjectHandler.resolveInterface(TagSupport.getDataTypeName((StorableObject) ((BaseObjectHandler) ((StructureField) me).getType())._getDelegate())));
1172                } catch (ClassNotFoundException JavaDoc e) {
1173                    throw (DebugException) Logger.getDefault().annotate(new DebugException(), e);
1174                }
1175            }
1176        }
1177        String JavaDoc ifcName = TagSupport.getTypeFullName((StorableObject) ((BaseObjectHandler) struct)._getDelegate());
1178        return new DatatypeDescriptor(mdrStorage, struct.getQualifiedName(), members, memberTypes, ifcName, storageId);
1179    }
1180    
1181    /** Creates handler for Class Proxy */
1182    private StorableClass createClassProxyHandler(MofClass metaObject, StorablePackage immediatePackage, List localClassProxies) {
1183        ModelElement element;
1184        StorableClass storable;
1185        boolean classDerived = false;
1186        boolean instanceDerived = false;
1187        boolean isDerived = false;
1188        
1189        try {
1190            ArrayList attrDescs = new ArrayList();
1191            ArrayList clAttrDescs = new ArrayList();
1192            Map datatypes = new HashMap();
1193            // create attribute indexes, collect information about attributes and references
1194
for (Iterator it = metaObject.getContents().iterator(); it.hasNext();) {
1195                element = (ModelElement) it.next();
1196                if (element instanceof Attribute) {
1197                    Attribute attr = (Attribute) element;
1198                    isDerived = attr.isDerived();
1199                    if (!isDerived) {
1200                        Class JavaDoc type;
1201                        try {
1202                            type = BaseObjectHandler.resolveInterface(TagSupport.getDataTypeName((StorableObject)((InstanceHandler)attr.getType())._getDelegate()));
1203                        } catch (java.lang.Exception JavaDoc e) {
1204                            throw (DebugException) Logger.getDefault().annotate(new DebugException(), e);
1205                        }
1206                        AttributeDescriptor desc = new AttributeDescriptor(mdrStorage, ((BaseObjectHandler)attr)._getDelegate().getMofId(), attr.getName(), type, attr.getMultiplicity().getLower(), attr.getMultiplicity().getUpper(), attr.getMultiplicity().isUnique(), attr.getMultiplicity().isOrdered(), attr.isChangeable(), MdrStorage.getStorageIdFromMofId(immediatePackage.getMofId()));
1207                        if (ScopeKindEnum.INSTANCE_LEVEL.equals(attr.getScope())) {
1208                            attrDescs.add(desc);
1209                        } else {
1210                            clAttrDescs.add(desc);
1211                        }
1212                    }
1213                } else if (element instanceof Operation) {
1214                    isDerived = true;
1215                } else {
1216                    if (element instanceof EnumerationType) {
1217                        List members = new ArrayList(((EnumerationType) element).getLabels());
1218                        String JavaDoc ifcName = TagSupport.getTypeFullName((StorableObject) ((BaseObjectHandler) element)._getDelegate());
1219                        datatypes.put(element.getName(), new DatatypeDescriptor(mdrStorage, members, ifcName, MdrStorage.getStorageIdFromMofId(immediatePackage.getMofId())));
1220                    } else if (element instanceof StructureType) {
1221                        ModelElement me;
1222                        List members = new ArrayList();
1223                        List memberTypes = new ArrayList();
1224                        
1225                        for (Iterator it2 = ((StructureType) element).getContents().iterator(); it2.hasNext();) {
1226                            me = (ModelElement) it2.next();
1227                            if (me instanceof StructureField) {
1228                                members.add(me.getName());
1229                                try {
1230                                    memberTypes.add(BaseObjectHandler.resolveInterface(TagSupport.getDataTypeName((StorableObject) ((BaseObjectHandler) ((StructureField) me).getType())._getDelegate())));
1231                                } catch (ClassNotFoundException JavaDoc e) {
1232                                    throw (DebugException) Logger.getDefault().annotate(new DebugException(), e);
1233                                }
1234                            }
1235                        }
1236                        String JavaDoc ifcName = TagSupport.getTypeFullName((StorableObject) ((BaseObjectHandler) element)._getDelegate());
1237                        datatypes.put(element.getName(), new DatatypeDescriptor(mdrStorage, element.getQualifiedName(), members, memberTypes, ifcName, MdrStorage.getStorageIdFromMofId(immediatePackage.getMofId())));
1238                    }
1239                    isDerived = false;
1240                }
1241                
1242                if (isDerived) {
1243                    if (((Feature) element).getScope().equals(ScopeKindEnum.CLASSIFIER_LEVEL)) {
1244                        classDerived = true;
1245                    } else {
1246                        instanceDerived = true;
1247                    }
1248                }
1249            }
1250            String JavaDoc tagValue = TagSupport.getTagValue((StorableObject) ((BaseObjectHandler) metaObject)._getDelegate(), TRANSIENT_TAG_ID, "");
1251            if (tagValue.equals(TAG_VALUE_TRUE)) {
1252                storable = new TransientStorableClass(mdrStorage, immediatePackage.getMofId(),
1253                ((BaseObjectHandler)metaObject)._getDelegate().getMofId(), attrDescs, clAttrDescs, datatypes, classDerived,
1254                instanceDerived, metaObject.isSingleton(), metaObject.isAbstract());
1255            }
1256            else {
1257                storable = new StorableClass(mdrStorage, immediatePackage.getMofId(),
1258                ((BaseObjectHandler)metaObject)._getDelegate().getMofId(), attrDescs, clAttrDescs, datatypes, classDerived,
1259                instanceDerived, metaObject.isSingleton(), metaObject.isAbstract());
1260            }
1261            
1262            immediatePackage.addClass(metaObject.getName(), storable.getMofId());
1263            classProxies.put(metaObject, storable);
1264            classProxiesMofIds.put(((BaseObjectHandler)metaObject)._getDelegate().getMofId(), storable.getMofId());
1265            localClassProxies.add(storable);
1266            return storable;
1267        } catch ( StorageException e ) {
1268            throw (DebugException) Logger.getDefault().annotate(new DebugException(), e);
1269        }
1270    }
1271    
1272    /** Creates handler for Association */
1273    private StorableAssociation createAssociationHandler(Association metaObject, StorablePackage immediatePackage, String JavaDoc assocationEnd1, MOFID assocEnd1MofId, String JavaDoc assocationEnd2, MOFID assocEnd2MofId, Class JavaDoc type1, Class JavaDoc type2, int min1, int max1, int min2, int max2, boolean isOrdered1, boolean isOrdered2, boolean isUnique1, boolean isUnique2, boolean isAggr1, boolean isAggr2, boolean isIndexed1, boolean isIndexed2, Set localAssocProxies) {
1274        try {
1275            StorableAssociation result = new StorableAssociation(
1276            mdrStorage,
1277            immediatePackage.getMofId(),
1278            ((BaseObjectHandler)metaObject)._getDelegate().getMofId(),
1279            assocationEnd1, assocEnd1MofId, assocationEnd2, assocEnd2MofId,
1280            type1, type2,
1281            min1, max1, min2, max2,
1282            isOrdered1, isOrdered2,
1283            isUnique1, isUnique2,
1284            isAggr1, isAggr2,
1285            isIndexed1, isIndexed2);
1286            immediatePackage.addAssociation(metaObject.getName(), result.getMofId());
1287            associationProxies.put(((BaseObjectHandler)metaObject)._getDelegate().getMofId(), result.getMofId());
1288            localAssocProxies.add(result.getMofId());
1289            return result;
1290        } catch ( StorageException e ) {
1291            throw new DebugException("Storage exception: " + e);
1292        }
1293    }
1294    
1295    private StorableAssociation createTransientAssociationHandler(Association metaObject, StorablePackage immediatePackage, String JavaDoc assocationEnd1, MOFID assocEnd1MofId, String JavaDoc assocationEnd2, MOFID assocEnd2MofId, Class JavaDoc type1, Class JavaDoc type2, int min1, int max1, int min2, int max2, boolean isOrdered1, boolean isOrdered2, boolean isUnique1, boolean isUnique2, boolean isAggr1, boolean isAggr2, Set localAssocProxies) {
1296        
1297        try {
1298            StorableAssociation result = new TransientStorableAssociation(
1299            mdrStorage,
1300            immediatePackage.getMofId(),
1301            ((BaseObjectHandler)metaObject)._getDelegate().getMofId(),
1302            assocationEnd1, assocEnd1MofId, assocationEnd2, assocEnd2MofId,
1303            type1, type2,
1304            min1, max1, min2, max2,
1305            isOrdered1, isOrdered2,
1306            isUnique1, isUnique2,
1307            isAggr1, isAggr2);
1308            immediatePackage.addAssociation(metaObject.getName(), result.getMofId());
1309            associationProxies.put(((BaseObjectHandler)metaObject)._getDelegate().getMofId(), result.getMofId());
1310            localAssocProxies.add(result.getMofId());
1311            return result;
1312        } catch ( StorageException e ) {
1313            throw new DebugException("Storage exception: " + e);
1314        }
1315    }
1316    
1317    /* -------------------------------------------------------------------- */
1318    /* -- Methods for bootstrapping (private) ----------------------------- */
1319    /* -------------------------------------------------------------------- */
1320    
1321    /**
1322     * Main bootstrapping method.
1323     */

1324    private void boot() {
1325        boolean fail = true;
1326        Logger.getDefault().log( "Booting repository ..." );
1327        mdrStorage.setBooting(true);
1328        beginTrans(true);
1329        try {
1330            installFakeMof();
1331            installPureMof();
1332            fail = false;
1333        } catch (Throwable JavaDoc e) {
1334            Logger.getDefault().notify(Logger.INFORMATIONAL, e);
1335        } finally {
1336            mdrStorage.setBooting(false);
1337            endTrans(fail);
1338        }
1339    }
1340    
1341    /** Installs the fake MOF
1342     */

1343    private void installFakeMof() {
1344        Logger.getDefault().log("Creating boot MOF metamodel ...");
1345        
1346        createBootMOF();
1347        if (getExtent(BOOT_MOF) == null) {
1348            throw new DebugException("Cannot create instance of BOOT_MOF: Fatal error during bootstrapping.");
1349        }
1350    }
1351    
1352    /** Programatically installs the pure MOF model.
1353     */

1354    private void installPureMof() {
1355        Logger.getDefault().log("Installing pure MOF Metamodel ... ");
1356        
1357        try {
1358            Logger.getDefault().log("Parsing MOF model to DOM represtentation ....");
1359            ModelPackage modelPackage = (ModelPackage) createExtent(PURE_MOF, getBMModelPackage());
1360            XmiReader xmiReader = (XmiReader) Lookup.getDefault().lookup(XmiReader.class);
1361            xmiReader.read(MOF_XML_URL.toString(), modelPackage);
1362            mdrStorage.rebuildMofContext();
1363        } catch (Exception JavaDoc e) {
1364            throw (DebugException) Logger.getDefault().annotate(new DebugException("Boot failed."), e);
1365        }
1366    }
1367    
1368    /**
1369     * Returns the MOF Model package as a model element of the
1370     * bootstrapping MOF model. Needed only during bootstrapping.
1371     *
1372     * <p>[PENDING]: Common code of this method and of {@link #getMOFModelPackage()}
1373     * should be factored out.
1374     */

1375    private MofPackage getBMModelPackage() {
1376        MofPackage result;
1377        for (Iterator it = ((ModelPackage) getExtent(BOOT_MOF)).getMofPackage().refAllOfClass().iterator(); it.hasNext();) {
1378            result = (MofPackage) it.next();
1379            if (result.getName().equals("Model")) {
1380                return result;
1381            }
1382        }
1383        return null;
1384    }
1385    
1386    /** Reads the XMI description of the mof directly into reporitory
1387     */

1388    private void createBootMOF() {
1389        try {
1390            BootReader br = new BootReader(mdrStorage, BOOTMOF_XML_URL);
1391            br.read();
1392        } catch (Exception JavaDoc e) {
1393            throw (DebugException) Logger.getDefault().annotate(new DebugException("Unable to read MOF XMI: " + e.getMessage()), e);
1394        }
1395    }
1396
1397    /* --------------------------------------------------------------------- */
1398    /* -- FacilityCache (static inner class) ------------------------------- */
1399    /* --------------------------------------------------------------------- */
1400
1401    /** Weak cache for created Handlers
1402    */

1403    private static class FacilityCache extends HashMap {
1404        private final ReferenceQueue JavaDoc queue = new ReferenceQueue JavaDoc();
1405        private boolean cleaningUp = false;
1406
1407        private class HandlerReference extends WeakReference JavaDoc {
1408            private MOFID mofId;
1409            // hard reference on an element when it should not be garbagecollected
1410
private RefBaseObject baseObject;
1411
1412            public HandlerReference(BaseObjectHandler handler) {
1413                super(handler, queue);
1414
1415                mofId = handler._getMofId();
1416                
1417                if (handler.refImmediatePackage() instanceof javax.jmi.model.ModelPackage || !(handler instanceof RefObject)) {
1418                    // the object is from a metamodel or it is a proxy => we will keep "hard" reference
1419
baseObject = handler;
1420                } else {
1421                    // the object is not a metamodel object => we will not keep "hard" reference on it
1422
baseObject = null;
1423                }
1424            }
1425
1426            public MOFID getProxyMofId() {
1427                return mofId;
1428            }
1429        }
1430
1431        private void cleanUp() {
1432            assert !cleaningUp;
1433            HandlerReference reference;
1434            cleaningUp = true;
1435            try {
1436                while ((reference = (HandlerReference) queue.poll()) != null) {
1437    // Logger.getDefault().log("Removing: " + reference.getProxyMofId());
1438
MOFID mofId = reference.getProxyMofId();
1439                    java.lang.ref.Reference JavaDoc currentRef = (java.lang.ref.Reference JavaDoc) super.remove(mofId);
1440                    if (currentRef != null && currentRef != reference && currentRef.get() != null) {
1441                        super.put(mofId, currentRef);
1442                    }
1443                }
1444            } finally {
1445                cleaningUp = false;
1446            }
1447        }
1448
1449        public Object JavaDoc put(Object JavaDoc key, Object JavaDoc value) {
1450            cleanUp();
1451            Object JavaDoc result = super.put(key, new HandlerReference((BaseObjectHandler) value));
1452            assert result == null || ((HandlerReference) result).get() == null : "replacing non-null reference";
1453            return null;
1454        }
1455        
1456        public Object JavaDoc remove(Object JavaDoc key) {
1457            cleanUp();
1458            Object JavaDoc result = super.remove(key);
1459            return result == null ? null : ((HandlerReference) result).get();
1460        }
1461
1462        public Object JavaDoc get(Object JavaDoc key) {
1463            cleanUp();
1464            Object JavaDoc result = super.get(key);
1465            return result == null ? null : ((HandlerReference) result).get();
1466        }
1467    }
1468    
1469    /* --------------------------------------------------------------------- */
1470    /* -- ShutdownListener ------------------------------------------------- */
1471    /* --------------------------------------------------------------------- */
1472
1473    public interface ShutdownListener {
1474        public void shutdown();
1475        
1476        public void stepFinished();
1477    }
1478    
1479    
1480}
1481
Popular Tags