KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > lib > jmi > xmi > XmiContext


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.lib.jmi.xmi;
20
21 import java.util.*;
22 import java.net.*;
23 import java.io.*;
24
25 import org.xml.sax.*;
26 import org.xml.sax.helpers.DefaultHandler JavaDoc;
27 import javax.xml.parsers.SAXParserFactory JavaDoc;
28 import javax.xml.parsers.ParserConfigurationException JavaDoc;
29 import javax.xml.parsers.SAXParser JavaDoc;
30
31 import org.netbeans.api.xmi.*;
32 import org.netbeans.lib.jmi.util.DebugException;
33
34 import javax.jmi.reflect.*;
35 import javax.jmi.model.*;
36 import javax.jmi.xmi.MalformedXMIException;
37 import javax.jmi.primitivetypes.PrimitiveTypesPackage;
38 import org.netbeans.lib.jmi.util.Logger;
39
40 public class XmiContext implements XMIReferenceResolver {
41
42     private static final String JavaDoc ANNOTATION = ""; //"Created by XMI SAX Reader to substitute Corba types.";
43

44     private static final String JavaDoc [] PRIMITIVE_TYPES = {
45         XmiConstants.BOOLEAN_TYPE, XmiConstants.DOUBLE_TYPE,
46         XmiConstants.FLOAT_TYPE, XmiConstants.INTEGER_TYPE,
47         XmiConstants.LONG_TYPE, XmiConstants.STRING_TYPE
48     };
49     
50     // shared XmiElements .......................................................
51

52     XmiElement.PrimitiveValue PRIMITIVE_VALUE = new XmiElement.PrimitiveValue (this);
53     XmiElement.EnumerationValue ENUMERATION_VALUE = new XmiElement.EnumerationValue (this);
54     XmiElement.ReferenceValue REFERENCE_VALUE = new XmiElement.ReferenceValue (this);
55     
56     // variables ................................................................
57

58     String JavaDoc XMI_HREF; // name of attributes storing an href in XMI
59
String JavaDoc XMI_IDREF; // name of attributes storing an idref in XMI
60
String JavaDoc XMI_ID; // name of attributes storing an id in XMI
61

62     boolean isXmi20; // if true, XMI version is 2.0
63
String JavaDoc xmiNsPrefix; // prefix of XMI namespace in case of XMI 2.0 (followed by ':' if the prefix is non-empty)
64
String JavaDoc xmlNsPrefix; // prefix of XML namespace in case of XMI 2.0 (followed by ':' if the prefix is non-empty)
65
private HashMap nsURIToPrefix = new HashMap (); // XMI 2.0 only - namespase URI to namespace prefix mapping
66

67     // storage of all outermost packages
68
private HashMap outermostPackages = new HashMap ();
69     // storage of all available namespaces
70
private HashMap namespaces = new HashMap ();
71
72     // extents passed as a parameter
73
private RefPackage [] extents;
74     // stores ModelPackage if it is one of the input packages
75
private ModelPackage modelPackage = null;
76     // primitive types package
77
private MofPackage primitiveTypesPackage = null;
78     // stores primitive types contained in @link #primitiveTypesPackage
79
private HashMap primitiveTypes = null;
80     // stores all Alias instances created instead of Corba primitive types
81
private List corbaTypesReferencingPrimitiveTypes = new LinkedList ();
82
83     // cache storing instance level attributes
84
private HashMap instanceAttributes_cache = new HashMap ();
85     // cache storing references
86
private HashMap instanceReferences_cache = new HashMap ();
87     // cache storing instance level attributes and references by names
88
private HashMap instanceElementsByName_cache = new HashMap ();
89     // cache storing class level attributes
90
private HashMap classAttributes_cache = new HashMap ();
91     // cache storing class level attributes by names
92
private HashMap classElementsByName_cache = new HashMap ();
93     
94     // cache storing structures' fields
95
private HashMap structureFields_cache = new HashMap ();
96     // cache storing labels' prefixes
97
private HashMap labelPrefix_cache = new HashMap ();
98
99     // list of all currently created outermost composite objects
100
private Collection outermostInstances = new LinkedList ();
101     // cache storing all already resolved names
102
private HashMap resolvedNames_cache = new HashMap ();
103     
104     // all currently known references given by xmi.id, each element is a hashtable
105
// containing references related to one XMI document
106
private HashMap allXmiReferences = new HashMap ();
107     /*
108     // xmi references resolved for the currently read document
109     private HashMap xmiReferences;
110      */

111     // internal unresolved reference, stores systemId -> ids_map, where ids_map is a
112
// xmiId -> List of UnresolvedReferences mapping
113
private HashMap unresolvedRefs = new HashMap ();
114     // external unresolved references for the currently read document
115
private HashMap unresolvedExternalRefs = new HashMap ();
116     //
117
private List listOfUnresolvedHRefs = new LinkedList ();
118     //
119
private Set allUnresolvedHRefs = new HashSet ();
120     //
121
private HashMap hrefClients = new HashMap ();
122     // true if the main document (not some external) is being processed
123
boolean isMain = true;
124     // set storing systemId's of all already read or currently being read documents
125
private Set readDocuments = new HashSet ();
126     // flag indicating whether an unknown elements should be ignored (otherwise a DebugException is thrown)
127
private boolean ignoreUnknownElements = false;
128     // unknown elements listener that is being notified about names of ignored elements
129
private UnknownElementsListener elemsListener = null;
130     
131     // systemId of the currently read document
132
private String JavaDoc thisSystemId = null;
133     // mapping systemId (possibly relative) -> absolute systemId
134
private HashMap systemIds = new HashMap ();
135     // URL of the read document
136
private URL docURL = null;
137     // global cache used by @link #findOutermostPackages method
138
private HashMap trackedPackages;
139     // cache for resolved proxies enabling Enum and Struct creation and Association proxies
140
private HashMap proxies_cache = new HashMap ();
141     // configuration
142
private XMIInputConfig config;
143
144     // counter of created instances
145
public int instancesCounter = 0;
146     
147     // xmi reference resolver
148
private XMIReferenceResolver resolver = this;
149     // xmi header consumer
150
private XMIHeaderConsumer headerConsumer = null;
151     
152     // init .....................................................................
153

154     public XmiContext (RefPackage [] extents, URL docURL, XMIInputConfig config) {
155         this (extents, config);
156         this.docURL = docURL;
157         if (docURL == null)
158             thisSystemId = ""; // NOI18N
159
else
160             thisSystemId = docURL.toString ();
161         readDocuments.add (thisSystemId);
162     }
163     
164     public XmiContext (RefPackage [] extents, XMIInputConfig config) {
165         String JavaDoc name;
166         this.extents = extents;
167         this.config = config;
168         resolver = config.getReferenceResolver ();
169         if (resolver == null)
170             resolver = this;
171         if (config instanceof InputConfig) {
172             headerConsumer = ((InputConfig) config).getHeaderConsumer ();
173             ignoreUnknownElements = ((InputConfig) config).isUnknownElementsIgnored();
174             elemsListener = ((InputConfig) config).getUnknownElementsListener();
175         }
176
177         // check if ModelPackage is present among input packages (and store it)
178
for (int i = 0; i < extents.length; i++)
179             if (extents [i] instanceof ModelPackage) {
180                 modelPackage = (ModelPackage) extents [i];
181                 break;
182             }
183     
184         isMain = true;
185         unresolvedRefs = new HashMap ();
186         allUnresolvedHRefs = new HashSet ();
187         allXmiReferences = new HashMap ();
188     }
189
190     // methods ..................................................................
191

192     public void setVersion (Attributes attrs) {
193         xmiNsPrefix = null;
194         String JavaDoc version = attrs.getValue (XmiConstants.XMI_VersionAtt);
195         if (version != null) {
196             if (!(version.equals ("1.0") || version.equals ("1.1") || version.equals ("1.2"))) {
197                 throw new DebugException ("Malformed version parameter or unsupported verion of XMI: "
198                     + XmiConstants.XMI20_VERSION + " = " + version);
199             }
200             isXmi20 = false;
201         } else {
202             isXmi20 = true;
203             xmiNsPrefix = "";
204             for (int x = 0; x < attrs.getLength (); x++) {
205                 String JavaDoc attrValue = attrs.getValue (x);
206                 if (attrValue.equals (XmiConstants.XMI_NAMESPACE_URI)) {
207                     String JavaDoc attrName = attrs.getQName (x);
208                     if (attrName.startsWith ("xmlns:")) {
209                         xmiNsPrefix = attrName.substring (6, attrName.length ()) + ":";
210                         break;
211                     }
212                 } // if
213
} // for
214
version = attrs.getValue (xmiNsPrefix + XmiConstants.XMI20_VERSION);
215             if (version == null) {
216                 throw new DebugException ("XMI version attribute is missing.");
217             }
218             if (!version.equals ("2.0")) {
219                 throw new DebugException ("Malformed version parameter or unsupported verion of XMI: "
220                     + xmiNsPrefix + XmiConstants.XMI20_VERSION + " = " + version);
221             }
222         } // else
223

224         if (isXmi20) {
225             XMI_HREF = xmiNsPrefix + XmiConstants.XMI_HREF;
226             XMI_ID = xmiNsPrefix + XmiConstants.XMI20_ID;
227             XMI_IDREF = xmiNsPrefix + XmiConstants.XMI20_IDREF;
228             
229             // obtain namespace declarations
230
for (int x = 0; x < attrs.getLength (); x++) {
231                 String JavaDoc attrName = attrs.getQName (x);
232                 String JavaDoc attrValue = attrs.getValue (x);
233                 if (attrName.equals ("xmlns")) {
234                     if (attrValue.equals (XmiConstants.XML_SCHEMA_NAMESPACE_URI))
235                         xmlNsPrefix = "";
236                     else
237                         nsURIToPrefix.put (attrValue, null);
238                 } else if (attrName.startsWith ("xmlns:")) {
239                     String JavaDoc name = attrName.substring (6, attrName.length ());
240                     if (attrValue.equals (XmiConstants.XML_SCHEMA_NAMESPACE_URI))
241                         xmlNsPrefix = name + ":";
242                     else {
243                         nsURIToPrefix.put (attrValue, name);
244                     }
245                 }
246             } // for
247
} else {
248             XMI_HREF = XmiConstants.XMI_HREF;
249             XMI_ID = XmiConstants.XMI_ID;
250             XMI_IDREF = XmiConstants.XMI_IDREF;
251         }
252         
253         trackedPackages = new HashMap (); // used as global cache for findOutermostPackages calls
254
for (int i = 0; i < extents.length; i++)
255             findOutermostPackages (extents [i].refOutermostPackage());
256     }
257     
258     /**
259      * Detects all outermost packages related to the input extents and stores them.
260      * Stores all related namespaces as well.
261      */

262     private void findOutermostPackages (RefPackage pkg) {
263         if (trackedPackages.get (pkg) != null)
264             return;
265         String JavaDoc name, uri;
266         MofPackage metaObj = (MofPackage) pkg.refMetaObject ();
267         if (metaObj.getContainer () == null) {
268             Iterator iter = metaObj.getQualifiedName ().iterator ();
269             String JavaDoc fqName = (String JavaDoc) iter.next ();
270             while (iter.hasNext ())
271                 fqName = fqName.concat (XmiConstants.DOT_SEPARATOR).concat ((String JavaDoc) iter.next ());
272             outermostPackages.put (fqName, pkg);
273         }
274         
275         if (isXmi20) {
276             uri = getTagValue (metaObj, XmiConstants.TAG_NS_URI);
277             if (uri == null) {
278                 throw new DebugException ("No tag specifying a namespace uri is attached to MofPackage " + metaObj.getName ());
279             }
280             name = (String JavaDoc) nsURIToPrefix.get (uri);
281             if (name == null) {
282                 throw new DebugException ("XMI document does not contain namespace declaration for " + uri + ", MofPackage " + metaObj.getName ());
283             }
284         } else {
285             name = getTagValue (metaObj, XmiConstants.TAGID_XMI_NAMESPACE);
286         }
287         if (name != null) {
288             List list = (List) namespaces.get (name);
289             if (list == null) {
290                 list = new LinkedList ();
291                 namespaces.put (name, list);
292             }
293             list.add (pkg);
294         }
295         
296         trackedPackages.put (pkg, pkg);
297         Iterator iter = pkg.refAllPackages ().iterator ();
298         while (iter.hasNext ()) {
299             findOutermostPackages ((RefPackage) iter.next ());
300         }
301     }
302
303     public static String JavaDoc getTagValue (ModelElement element, String JavaDoc tagId) {
304         Collection tags = ((ModelPackage) element.refImmediatePackage()).
305             getAttachesTo().getTag (element);
306         Tag tag = null;
307         for (Iterator it = tags.iterator(); it.hasNext();) {
308             Object JavaDoc obj = it.next ();
309             if (!(obj instanceof Tag))
310                 continue;
311             Tag temp = (Tag) obj;
312             if (tagId.equals (temp.getTagId ())) {
313                 tag = temp;
314                 break;
315             }
316         }
317         if (tag == null)
318             return null;
319         Collection values = tag.getValues ();
320         if (values.size () == 0)
321             return null;
322         return (String JavaDoc) values.iterator ().next ();
323     }
324     
325     /**
326      * This method is called to applay already read differences on a given document.
327      *
328      * @param href link to an external document
329      * @param diffs list of differences (see @link #XmiElement.Difference.Diff) to be applyed
330      */

331     public void resolveDifferences (String JavaDoc href, HashMap diffs) {
332         if (href == null)
333             throw new DebugException ("External document to applay differences on is not specified.");
334         try {
335             XmiSAXReader reader = new XmiSAXReader (config);
336             URL doc;
337             if (docURL != null) {
338                 String JavaDoc path = docURL.getPath ();
339                 int copyTo = path.lastIndexOf ("/");
340                 if (copyTo > -1) {
341                     href = path.substring (0, copyTo) + "/" + href;
342                 }
343                 doc = new URL (docURL.getProtocol (), this.docURL.getHost (), href);
344             } else {
345                 doc = new URL (href);
346             }
347             Collection res = reader.read (doc, extents, null, diffs);
348             outermostInstances.addAll (res);
349         } catch (Exception JavaDoc e) {
350             throw new DebugException (e.getMessage ());
351         }
352     }
353     
354     /**
355      * This private method is called to obtain and cache all class and instance
356      * scoped attributes and references.
357      * Related caches are:
358      * @link #instanceAttributes_cache, @link #instanceReferences_cache,
359      * @link #instanceElementsByName_cache
360      */

361     private void cacheContainedElements (RefClass proxyClass) {
362         List temp = new LinkedList ();
363         MofClass metaProxyClass = (MofClass) proxyClass.refMetaObject ();
364         List superClasses = metaProxyClass.allSupertypes ();
365         Namespace namespace = null;
366         Iterator it = superClasses.iterator ();
367         while (it.hasNext ()) {
368             namespace = (Namespace) it.next ();
369             temp.addAll (namespace.getContents ());
370         }
371         temp.addAll (metaProxyClass.getContents ());
372         List instanceAttributes = new LinkedList ();
373         List instanceReferences = new LinkedList ();
374         List classAttributes = new LinkedList ();
375         HashMap instanceElementsByName = new HashMap ();
376         HashMap classElementsByName = new HashMap ();
377         
378         it = temp.iterator ();
379         while (it.hasNext ()) {
380             RefObject refObject = (RefObject) it.next ();
381             if (refObject instanceof Feature) {
382                 boolean instanceLevel = ((Feature) refObject).getScope ().equals (ScopeKindEnum.INSTANCE_LEVEL);
383                 if ((refObject instanceof Attribute) && (!((Attribute) refObject).isDerived ())) {
384                     if (instanceLevel) {
385                         instanceAttributes.add (refObject);
386                         instanceElementsByName.put
387                             (((Attribute) refObject).getName (), refObject);
388                     } else {
389                         classAttributes.add (refObject);
390                         classElementsByName.put
391                             (((Attribute) refObject).getName (), refObject);
392                     }
393                 } else if (refObject instanceof Reference) {
394                     if (instanceLevel) {
395                         instanceReferences.add (refObject);
396                         instanceElementsByName.put
397                             (((Reference) refObject).getName (), refObject);
398                     }
399                 } // else
400
} // if (refObject instanceof Feature)
401
} // while
402
instanceAttributes_cache.put (proxyClass, instanceAttributes);
403         instanceReferences_cache.put (proxyClass, instanceReferences);
404         instanceElementsByName_cache.put (proxyClass, instanceElementsByName);
405         classAttributes_cache.put (proxyClass, classAttributes);
406         classElementsByName_cache.put (proxyClass, instanceElementsByName);
407     }
408
409     /**
410      * For a given class proxy, returns list of all instance-scoped attributes
411      * (references are not included).
412      */

413     public List instanceAttributes (RefClass refClass) {
414         List list = (List) instanceAttributes_cache.get (refClass);
415         if (list == null) {
416             cacheContainedElements (refClass);
417             list = (List) instanceAttributes_cache.get (refClass);
418         }
419         return list;
420     }
421     
422     /**
423      * For a given class proxy, returns list of all (instance-scoped) references.
424      */

425     public List instanceReferences (RefClass refClass) {
426         List list = (List) instanceReferences_cache.get (refClass);
427         if (list == null) {
428             cacheContainedElements (refClass);
429             list = (List) instanceReferences_cache.get (refClass);
430         }
431         return list;
432     }
433
434     /**
435      * Returns an attribute, resp. a reference according to given class proxy and
436      * attribute, resp. reference name.
437      * Used when attribute values stored as XLM element attributes are being resolved.
438      */

439     public StructuralFeature instanceElementByName (RefClass refClass, String JavaDoc name) {
440         HashMap map = (HashMap) instanceElementsByName_cache.get (refClass);
441         if (map == null) {
442             cacheContainedElements (refClass);
443             map = (HashMap) instanceElementsByName_cache.get (refClass);
444         }
445         StructuralFeature feature = (StructuralFeature) map.get (name);
446         if (feature == null) {
447             // [PENDING]
448
// throw new DebugException ("Attribute name cannot be resolved: " + name);
449
}
450         return feature;
451     }
452
453     public List staticAttributes (RefClass refClass) {
454         List list = (List) classAttributes_cache.get (refClass);
455         if (list == null) {
456             cacheContainedElements (refClass);
457             list = (List) classAttributes_cache.get (refClass);
458         }
459         return list;
460     }
461     
462     public Attribute staticAttributeByName (RefClass refClass, String JavaDoc name) {
463         HashMap map = (HashMap) classElementsByName_cache.get (refClass);
464         if (map == null) {
465             cacheContainedElements (refClass);
466             map = (HashMap) classElementsByName_cache.get (refClass);
467         }
468         return (Attribute) map.get (name);
469     }
470     
471     /**
472      * Returns list of all fields belonging to the given StructureType.
473      */

474     public List structureFields (StructureType type) {
475         List fields = (List) structureFields_cache.get (type);
476         if (fields != null)
477             return fields;
478         // find fields and cache them
479
fields = new LinkedList ();
480         Iterator content = type.getContents ().iterator ();
481         while (content.hasNext ()) {
482             Object JavaDoc element = content.next ();
483             if (element instanceof StructureField)
484                 fields.add (element);
485         } // while
486
structureFields_cache.put (type, fields);
487         return fields;
488     }
489     
490     /**
491      * Returns labels prefix given by "unprefix" tag attached to EnumerationType or
492      * the empty String if no such tag is present.
493      */

494     public String JavaDoc labelPrefix (EnumerationType type) {
495         if (isXmi20)
496             return "";
497         String JavaDoc prefix = (String JavaDoc) labelPrefix_cache.get (type);
498         if (prefix != null)
499             return prefix;
500         prefix = getTagValue (type, XmiConstants.TAGID_XMI_ENUMERATION_UNPREFIX);
501         if (prefix == null)
502             prefix = "";
503         labelPrefix_cache.put (type, prefix);
504         return prefix;
505     }
506     
507     /**
508      * Resolves given fully qualified or namespace prefixed element name.
509      * If the name corresponds to MofClass, related proxy class is returned instead of it.
510      */

511     public Object JavaDoc resolveElementName (String JavaDoc fqName) {
512         Object JavaDoc result = resolvedNames_cache.get (fqName);
513         if (result != null)
514             return result;
515
516         int pos = fqName.indexOf (XmiConstants.NS_SEPARATOR);
517         RefPackage outermostPackage = null;
518         if ((pos < 0) && !isXmi20) {
519             // namespace not presented in name, fully qualified name is given
520
int index = fqName.indexOf (XmiConstants.DOT_SEPARATOR);
521             String JavaDoc packageName = fqName;
522             while (index > -1) {
523                 packageName = packageName.substring (0, index);
524                 outermostPackage = (RefPackage) outermostPackages.get (packageName);
525                 if (outermostPackage != null)
526                     break;
527                 index = packageName.indexOf (XmiConstants.DOT_SEPARATOR);
528             }
529             if (outermostPackage == null) {
530                 if (ignoreUnknownElements) {
531                     return null;
532                 } else {
533                     throw new DebugException ("Element name cannot be resolved, unknown package: " + fqName);
534                 }
535             }
536             StringTokenizer tokenizer = new StringTokenizer (fqName, ".");
537             LinkedList nameParts = new LinkedList ();
538             tokenizer.nextToken (); // skip the outermost package name
539
while (tokenizer.hasMoreTokens ())
540                 nameParts.add (tokenizer.nextToken ());
541             Namespace namespace = (Namespace) outermostPackage.refMetaObject ();
542             try {
543                 RefObject obj = namespace.resolveQualifiedName (nameParts);
544                 if (obj instanceof MofClass) {
545                     RefPackage refPkg = (RefPackage) findProxy ((MofClass)obj);
546                     if (refPkg != null)
547                         result = refPkg.refClass (obj);
548                 } else
549                     result = obj;
550             } catch (NameNotResolvedException e) {
551             }
552         } else {
553             // name contains namespace prefix, it is of the form NAMESPACE:NAME1(.NAME2)?
554
String JavaDoc nsPrefixName;
555             if (pos < 0) {
556                 nsPrefixName = ""; // XMI 2.0 & default namespace
557
} else {
558                 nsPrefixName = fqName.substring (0, pos);
559             }
560             List packages = (List) namespaces.get (nsPrefixName);
561             if (packages == null) {
562                 if (ignoreUnknownElements) {
563                     return null;
564                 } else {
565                     throw new DebugException ("Namespace cannot be resolved: " + nsPrefixName);
566                 }
567             }
568             
569             int pos2 = fqName.indexOf (XmiConstants.DOT_SEPARATOR);
570             Iterator iter = packages.iterator ();
571             while (iter.hasNext ()) {
572                 outermostPackage = (RefPackage) iter.next ();
573                 try {
574                     if (pos2 == -1) {
575                         // 1) a "class level" element
576
RefObject metaClass = ((GeneralizableElement) outermostPackage.refMetaObject ()).
577                             lookupElementExtended (fqName.substring (pos + 1, fqName.length ()));
578                         if (metaClass instanceof MofClass)
579                             result = outermostPackage.refClass (metaClass);
580                         else
581                            result = metaClass;
582                     } else {
583                         // 2) an "attribute level" element
584
Classifier element = (Classifier) ((GeneralizableElement) outermostPackage.refMetaObject ()).
585                             lookupElementExtended (fqName.substring (pos + 1, pos2));
586                         if (element == null)
587                             continue;
588                         result = element.lookupElementExtended (fqName.substring (pos2 + 1, fqName.length ()));
589                     } // else
590
} catch (NameNotFoundException e) {
591                 }
592                 if (result != null)
593                     break;
594             } // while
595

596         } // else
597

598         if (result == null) {
599             if (ignoreUnknownElements) {
600                 return null;
601             } else {
602                 throw new DebugException("Name cannot be resolved: " + fqName);
603             }
604         }
605         resolvedNames_cache.put (fqName, result);
606         return result;
607     }
608
609     /**
610      * Called by XMIElement.Header to process the read XMI reader.
611      */

612     public void receiveHeader (String JavaDoc header) {
613         if (headerConsumer != null) {
614             byte [] bytes = new byte [header.length()];
615             for (int x = 0; x < bytes.length; x++) {
616                 bytes [x] = (byte) header.charAt (x);
617             }
618             headerConsumer.consumeHeader (new ByteArrayInputStream (bytes));
619         } // if
620
}
621         
622     /**
623      * Called when the whole XMI document has been read.
624      * Handles setting of Imports related to Aliases created instead of Corba primitive types.
625      */

626     public void finish () {
627         if (!isMain)
628             return;
629         
630         HashMap checkedPackages = new HashMap ();
631         Iterator iter = corbaTypesReferencingPrimitiveTypes.iterator ();
632         while (iter.hasNext ()) {
633             ModelElement element = (ModelElement) iter.next ();
634             Namespace container = element.getContainer ();
635             Namespace owner = container.getContainer ();
636             while (owner != null) {
637                 container = owner;
638                 owner = owner.getContainer ();
639             }
640             while (container.getContainer () != null)
641                 container = container.getContainer ();
642             if ((container instanceof MofPackage) && (checkedPackages.get (container) == null)) {
643                 MofPackage pkg = (MofPackage) container;
644                 Iterator content = pkg.getContents ().iterator ();
645                 boolean found = false;
646                 while (content.hasNext ()) {
647                     ModelElement el = (ModelElement) content.next ();
648                     if (el instanceof Import) {
649                         if (primitiveTypesPackage.equals (((Import) el).getImportedNamespace ())) {
650                             found = true;
651                             break;
652                         } // if
653
} // if
654
} // while
655
if (!found) {
656                     Import imp = modelPackage.getImport ().createImport (
657                         XmiConstants.PRIMITIVE_TYPES_PACKAGE, ANNOTATION,
658                         VisibilityKindEnum.PUBLIC_VIS, false
659                     );
660                     imp.setImportedNamespace (primitiveTypesPackage);
661                     imp.setContainer (pkg);
662                 } // if
663
checkedPackages.put (pkg, pkg);
664             } // if
665
} // while
666
checkedPackages = null;
667         
668         Logger.getDefault().log ("Number of created instances: " + instancesCounter);
669         
670     }
671     
672     public XmiElement resolveInstanceOrReference (XmiElement parent,
673         String JavaDoc qName, Attributes attrs) {
674         String JavaDoc idRef = attrs.getValue (XMI_IDREF);
675         if (idRef != null) {
676             REFERENCE_VALUE.init (parent, idRef);
677             return REFERENCE_VALUE;
678         }
679         idRef = attrs.getValue (XMI_HREF);
680         if (idRef != null) {
681             REFERENCE_VALUE.initExternal (parent, idRef);
682             return REFERENCE_VALUE;
683         }
684         Object JavaDoc ref = resolveElementName (qName);
685         if (ref == null && ignoreUnknownElements) {
686             return new XmiElement.Dummy(parent, this, qName);
687         }
688         if (ref instanceof DataTypeClass) {
689             // ===================================
690
// MOF 1.3 compatibility
691
// ===================================
692
return new XmiElement.DataTypeElement (parent, this, qName, attrs);
693         }
694         return new XmiElement.Instance (parent, this, qName, (RefClass) ref, attrs);
695     }
696     
697     /**
698      * Adds created outermost object to the collection returned by
699      * @link #XmiSAXReader.read method as a result.
700      */

701     public void addOutermostObject (RefObject obj) {
702         outermostInstances.add (obj);
703     }
704     
705     /**
706      * When the reading of XMI is finished, returns collection of all created
707      * outermost objects.
708      */

709     public Collection getOutermostObjects () {
710         return outermostInstances;
711     }
712     
713     // XMIReferenceResolver implementation ......................................
714

715     public void register(String JavaDoc systemId, String JavaDoc xmiId, RefObject object) {
716         String JavaDoc href = systemId + '#' + xmiId;
717         List list = (List) hrefClients.remove (href);
718         if (list != null) {
719             Iterator iter = list.iterator ();
720             while (iter.hasNext ()) {
721                 ((Client) iter.next ()).resolvedReference (href, object, true);
722             } // while
723

724         } // if
725
}
726         
727     public void resolve(XMIReferenceResolver.Client client, RefPackage extent, String JavaDoc systemId, XMIInputConfig configuration, Collection hrefs) throws MalformedXMIException, IOException {
728         String JavaDoc href;
729         listOfUnresolvedHRefs = new LinkedList ();
730         unresolvedExternalRefs = new HashMap ();
731         
732         Iterator iter = hrefs.iterator ();
733         while (iter.hasNext ()) {
734             href = (String JavaDoc) iter.next ();
735             List list = (List) hrefClients.get (href);
736             if (list == null) {
737                 list = new LinkedList ();
738                 hrefClients.put (href, list);
739             }
740             list.add (client);
741         } // while
742

743         iter = hrefs.iterator ();
744         while (iter.hasNext ()) {
745             href = (String JavaDoc) iter.next ();
746             XMIReferenceProvider.XMIReference ref = toXMIReference (href);
747             String JavaDoc systId = ref.getSystemId ();
748             String JavaDoc xmiId = ref.getXmiId ();
749             RefObject obj = getReference (systId, xmiId);
750             if (obj != null) {
751                 register (systId, xmiId, obj);
752             } else {
753                 if (!readDocuments.contains (systId)) {
754                     URL url = toURL (systId);
755                     if ((url == null) || (!readDocuments.contains (url.toString ()))) {
756                         readExternalDocument (systId);
757                         obj = getReference (systId, xmiId);
758                         if (obj != null) {
759                             register (systId, xmiId, obj);
760                         }
761                     }
762                 } // if
763
}
764         } // while
765
}
766
767     // ..........................................................................
768

769     /**
770      * If an instance identified by a given xmiId has been created, it is returned,
771      * otherwise <code>null</code> is returned.
772      */

773     public RefObject getReference (String JavaDoc xmiId) {
774         return getReference (thisSystemId, xmiId);
775     }
776
777     public RefObject getReference (String JavaDoc docId, String JavaDoc xmiId) {
778         HashMap map = (HashMap) allXmiReferences.get (absoluteSystemId (docId));
779         return (map != null) ? (RefObject) map.get (xmiId) : null;
780     }
781
782     /**
783      * Stores a created instance having xmiId as a pair (xmiId, obj).
784      */

785     public void putReference (String JavaDoc systemId, String JavaDoc xmiId, RefObject obj) {
786         systemId = absoluteSystemId (systemId);
787         Map map = (Map) allXmiReferences.get (systemId);
788         if (map == null) {
789             map = new HashMap ();
790             allXmiReferences.put (systemId, map);
791         }
792         if (map.put (xmiId, obj) != null)
793             throw new DebugException ("The same value of xmi.idref used second time: " + xmiId + ", " + systemId);
794
795         map = (Map) unresolvedRefs.get (systemId);
796         if (map != null) {
797             List list = (List) map.remove (xmiId);
798             if (list != null) {
799                 Iterator iter = list.iterator ();
800                 while (iter.hasNext ()) {
801                     ((XmiElement.UnresolvedReference) iter.next ()).referenceResolved (obj);
802                 } // while
803
if (map.size () == 0)
804                     unresolvedRefs.remove (systemId);
805             } // if
806
} // if
807
resolver.register (systemId, xmiId, obj);
808     }
809
810     /**
811      * Registers UnresolvedReference, i.e. stores it in a HashMap using xmiId as a key.
812      */

813     public void registerUnresolvedRef (String JavaDoc xmiId, XmiElement.UnresolvedReference element) {
814         Map map = (Map) unresolvedRefs.get (thisSystemId);
815         if (map == null) {
816             map = new HashMap ();
817             unresolvedRefs.put (thisSystemId, map);
818         }
819         List list = (List) map.get (xmiId);
820         if (list == null) {
821             list = new LinkedList ();
822             map.put (xmiId, list);
823         }
824         list.add (element);
825     }
826
827     /**
828      * Registers external unresolved reference in context of given document.
829      */

830     public void registerUnresolvedExternalRef (String JavaDoc docId, String JavaDoc xmiId, XmiElement.UnresolvedReference element) {
831         String JavaDoc href = absoluteSystemId (docId) + '#' + xmiId;
832         List list = (List) unresolvedExternalRefs.get (href);
833         if (list == null) {
834             list = new LinkedList ();
835             unresolvedExternalRefs.put (href, list);
836             listOfUnresolvedHRefs.add (href);
837             allUnresolvedHRefs.add (href);
838         }
839         list.add (element);
840     }
841
842     public void resolveExternalReferences () {
843         try {
844             if (listOfUnresolvedHRefs.size () > 0) {
845                 resolver.resolve (
846                     new Client (unresolvedExternalRefs),
847                     extents [0], // [PENDING]
848
thisSystemId,
849                     config,
850                     listOfUnresolvedHRefs
851                 );
852                 listOfUnresolvedHRefs = new LinkedList ();
853                 unresolvedExternalRefs = new HashMap ();
854             } // if
855
} catch (MalformedXMIException e) {
856             throw new DebugException (e.getMessage ());
857         } catch (IOException e) {
858             throw new DebugException (e.getMessage ());
859         }
860     }
861
862     public XMIReferenceProvider.XMIReference toXMIReference (String JavaDoc href) {
863         int index = href.lastIndexOf ('#');
864         if (index < 0)
865             index = href.lastIndexOf ('|');
866         if (index < 0)
867             throw new DebugException ("Bad href, # delimiter character missing: " + href);
868         String JavaDoc docId = href.substring (0, index);
869         String JavaDoc xmiId = href.substring (index + 1, href.length ());
870         if (xmiId.length () == 0)
871             throw new DebugException ("Invalid href format: " + href);
872         return new XMIReferenceProvider.XMIReference (docId, xmiId);
873     }
874
875     public URL toURL (String JavaDoc systemId) {
876         URL doc = null;
877         try {
878             doc = new URL (systemId);
879         } catch (MalformedURLException e) {
880             if (docURL != null) {
881                 String JavaDoc path = docURL.getPath ();
882                 String JavaDoc href = systemId;
883                 int copyTo = path.lastIndexOf ("/");
884                 if (copyTo > -1) {
885                     href = path.substring (0, copyTo) + "/" + href;
886                 }
887                 try {
888                     doc = new URL (docURL.getProtocol (), this.docURL.getHost (), href);
889                     try {
890                         (doc.openStream ()).close ();
891                     } catch (IOException ioe) {
892                     }
893                 } catch (MalformedURLException mue) {
894                 }
895             } // if
896
}
897         return doc;
898     }
899
900     public String JavaDoc absoluteSystemId (String JavaDoc id) {
901         String JavaDoc result = (String JavaDoc) systemIds.get (id);
902         if (result == null) {
903             URL url = toURL (id);
904             if (url == null)
905                 result = id;
906             else
907                 result = url.toString ();
908             systemIds.put (id, result);
909         }
910         return result;
911     }
912
913     public void readExternalDocument (String JavaDoc systemId) {
914         try {
915             boolean temp_isMain = isMain;
916             String JavaDoc temp_thisSystemId = thisSystemId;
917             
918             isMain = false;
919             thisSystemId = absoluteSystemId (systemId);
920             
921             URL doc = toURL (systemId);
922             if (doc == null)
923                 throw new DebugException ("Cannot create URL: " + systemId);
924             
925             XmiSAXReader reader = new XmiSAXReader (this, config);
926             readDocuments.add (thisSystemId);
927             reader.read (doc, extents, null);
928             
929             isMain = temp_isMain;
930             thisSystemId = temp_thisSystemId;
931             
932         } catch (MalformedURLException e) {
933             throw new DebugException (e.getMessage ());
934         } catch (IOException e) {
935             throw new DebugException (e.getMessage ());
936         } catch (SAXException e) {
937             throw new DebugException (e.getMessage ());
938         } catch (ParserConfigurationException JavaDoc e) {
939             throw new DebugException (e.getMessage ());
940         }
941     }
942
943     public String JavaDoc getCurrentDocId () {
944         return thisSystemId;
945     }
946
947     /**
948      * True iff all registered unresolved references has been already resolved.
949      */

950     public boolean allReferencesResolved () {
951         return (unresolvedRefs.size () == 0) && (allUnresolvedHRefs.size () == 0);
952     }
953
954     /**
955      * Returns one of the unresolved references. (Used to report an error
956      * when the reading is finished and there are still some unresolved references.)
957      */

958     public String JavaDoc getUnresolvedRefId () {
959         if (unresolvedRefs.size () > 0) {
960             Map map = (Map) ((Map.Entry) unresolvedRefs.entrySet ().iterator ().next ()).getValue ();
961             return (String JavaDoc) map.keySet ().iterator ().next ();
962         } else if (allUnresolvedHRefs.size () > 0) {
963             return (String JavaDoc) allUnresolvedHRefs.iterator ().next ();
964         }
965         return null;
966     }
967
968     /**
969      * @param type type that should be resolved
970      * @param asText text representation of a value
971      *
972      * @return primitive type value
973      */

974     public static Object JavaDoc resolvePrimitiveValue (PrimitiveType type, String JavaDoc asText) {
975         String JavaDoc typeName = type.getName ();
976         if (XmiConstants.BOOLEAN_TYPE.equals (typeName))
977             return Boolean.valueOf(asText.toString ());
978         if (XmiConstants.DOUBLE_TYPE.equals (typeName))
979             return new Double JavaDoc (asText.toString ());
980         if (XmiConstants.FLOAT_TYPE.equals (typeName))
981             return new Float JavaDoc (asText.toString ());
982         if (XmiConstants.INTEGER_TYPE.equals (typeName))
983             return new Integer JavaDoc (asText.toString ());
984         if (XmiConstants.LONG_TYPE.equals (typeName))
985             return new Long JavaDoc (asText.toString ());
986         if (XmiConstants.STRING_TYPE.equals (typeName))
987             return (asText == null) ? "" : asText.toString ();
988         throw new DebugException ("unrecognized type name: " + typeName);
989     }
990
991     public RefEnum resolveEnumerationValue (EnumerationType type, String JavaDoc asText) {
992         RefBaseObject proxy = findProxy (type);
993         if (proxy == null) {
994             throw new DebugException ("Proxy not found: " + type.getName ());
995         }
996                 
997         // see @link #labelPrefix method for clarification ...
998
asText = labelPrefix (type) + asText;
999         
1000        try {
1001            if (proxy instanceof RefClass)
1002                return ((RefClass) proxy).refGetEnum (type, asText);
1003            else
1004                return ((RefPackage) proxy).refGetEnum (type, asText);
1005        } catch (InvalidCallException e) {
1006            throw new DebugException("Error creating literal \'" + asText + "\'. Probably invalid literal name for enumeration " + type.getName());
1007        }
1008    }
1009
1010    /**
1011     * Finds proxy object related to the container of a given meta model element.
1012     *
1013     * @param element meta model element
1014     * @return related proxy object or <code>null</code> if proxy cannot be found
1015     */

1016    public RefBaseObject findProxy (ModelElement element) {
1017        RefBaseObject proxy = (RefBaseObject) proxies_cache.get (element);
1018        if (proxy != null)
1019            return proxy;
1020        LinkedList path = new LinkedList ();
1021        ModelElement container = element.getContainer ();
1022        while (container != null) {
1023            path.add (container);
1024            container = container.getContainer ();
1025        }
1026        MofPackage mofPackage = (MofPackage) path.removeLast ();
1027        RefPackage refPackage = (RefPackage) outermostPackages.get (mofPackage.getName ());
1028        if (refPackage == null) {
1029            // try to find an outermost package such that its meta package is a subclass of the requsted mofPackage
1030
Iterator iter = outermostPackages.entrySet ().iterator ();
1031            while (iter.hasNext ()) {
1032                RefPackage ref = (RefPackage) ((Map.Entry) iter.next ()).getValue ();
1033                MofPackage meta = (MofPackage) ref.refMetaObject ();
1034                if (meta.allSupertypes().contains(mofPackage)) {
1035                    refPackage = ref;
1036                    break;
1037                }
1038            } // while
1039
} // if
1040

1041        if (refPackage == null)
1042            return null;
1043        if (path.size () == 0)
1044            proxy = refPackage;
1045        while (path.size () > 0) {
1046            ModelElement elem = (ModelElement) path.removeLast ();
1047            if (elem instanceof MofPackage) {
1048                refPackage = refPackage.refPackage (elem);
1049                if (path.size () == 0)
1050                    proxy = refPackage;
1051            } else {
1052                if ((elem instanceof MofClass) && (path.size () == 0)) {
1053                    RefClass refClass = refPackage.refClass (elem);
1054                    proxy = refClass;
1055                } else
1056                    break;
1057            } // else
1058
} // while
1059
if (proxy != null)
1060            proxies_cache.put (element, proxy);
1061        return proxy;
1062    }
1063
1064    /**
1065     * Returns true if given StructuralFeature is multivalued.
1066     */

1067    public static boolean isMultivalued (StructuralFeature attr) {
1068        MultiplicityType multType = attr.getMultiplicity ();
1069        int upper = multType.getUpper ();
1070        return upper != 1;
1071    }
1072
1073    /**
1074     * Returns fully qualified name of an element as a String.
1075     */

1076    public static String JavaDoc getQualifiedName (Classifier type) {
1077        List list = type.getQualifiedName ();
1078        Iterator iter = list.iterator ();
1079        String JavaDoc name = (String JavaDoc) iter.next ();
1080        while (iter.hasNext ())
1081            name = name + '.' + (String JavaDoc) iter.next ();
1082        return name;
1083    }
1084
1085    public XmiElement resolveValue (XmiElement parent, Classifier type, Attributes attrs) {
1086        while (type instanceof AliasType)
1087            type = ((AliasType) type).getType ();
1088        if (type instanceof PrimitiveType) {
1089            PRIMITIVE_VALUE.init (parent, (PrimitiveType) type, attrs);
1090            return PRIMITIVE_VALUE;
1091        }
1092        if (type instanceof EnumerationType) {
1093            ENUMERATION_VALUE.init (parent, (EnumerationType) type, attrs);
1094            return ENUMERATION_VALUE;
1095        }
1096        if (type instanceof MofClass) {
1097            boolean isNull = false;
1098            if (isXmi20) {
1099                String JavaDoc value = attrs.getValue (xmlNsPrefix + XmiConstants.XMI20_NIL);
1100                isNull = ((value != null) && value.equals ("true"));
1101            } // if
1102
return new XmiElement.ObjectValues
1103                (parent, this, (XmiElement.ReferencesCounter) parent, isNull);
1104        }
1105        if (type instanceof StructureType) {
1106            return new XmiElement.StructureValues
1107                (parent, this, (StructureType) type);
1108        }
1109        if (type instanceof CollectionType) {
1110            return new XmiElement.CollectionValues
1111                (parent, this, (CollectionType) type);
1112        }
1113        throw new DebugException ("Type not resolved: " + type.getName ());
1114    }
1115
1116    public boolean ignoreUnknownElements() {
1117        return ignoreUnknownElements;
1118    }
1119    
1120    public void unknownElementFound(String JavaDoc name) {
1121        if (elemsListener != null) {
1122            elemsListener.elementFound(name);
1123        }
1124    }
1125    
1126    /**
1127     * Returns default value for a given attribute.
1128     */

1129    public static Object JavaDoc defaultValue (Attribute attr) {
1130        Classifier type = attr.getType ();
1131        if (!(type instanceof PrimitiveType))
1132            return null;
1133        MultiplicityType multType = attr.getMultiplicity ();
1134        boolean isMultivalued = multType.getUpper () != 1;
1135        int lower = multType.getLower ();
1136        if (lower == 0) {
1137            if (isMultivalued)
1138                return new LinkedList ();
1139            else
1140                return null;
1141        }
1142        return defaultValue ((PrimitiveType) type, isMultivalued, lower);
1143    }
1144
1145    /**
1146     * Returns default (single-) value of a given type.
1147     */

1148    public static Object JavaDoc defaultValue (Classifier type) {
1149        if (type instanceof PrimitiveType)
1150            return defaultValue ((PrimitiveType) type, false, 1);
1151        return null;
1152    }
1153
1154    /**
1155     * Returns default value.
1156     *
1157     * @param type type of the value
1158     * @multiValued if true, multi-value is returned
1159     * @card cardinality of multi-value, it is ignored if multiValued is <code>false</code>
1160     *
1161     * @return default value
1162     */

1163    private static Object JavaDoc defaultValue (PrimitiveType type, boolean multiValued, int card) {
1164        Object JavaDoc baseValue = null;
1165        String JavaDoc typeName = type.getName ();
1166        if (XmiConstants.BOOLEAN_TYPE.equals (typeName))
1167            baseValue = Boolean.FALSE;
1168        else if (XmiConstants.DOUBLE_TYPE.equals (typeName))
1169            baseValue = new Double JavaDoc (0);
1170        else if (XmiConstants.FLOAT_TYPE.equals (typeName))
1171            baseValue = new Float JavaDoc (0);
1172        else if (XmiConstants.INTEGER_TYPE.equals (typeName))
1173            baseValue = new Integer JavaDoc (0);
1174        else if (XmiConstants.LONG_TYPE.equals (typeName))
1175            baseValue = new Long JavaDoc (0);
1176        else if (XmiConstants.STRING_TYPE.equals (typeName))
1177            baseValue = "";
1178        if (baseValue == null)
1179            return null;
1180        if (!multiValued)
1181            return baseValue;
1182        List multiValue = new LinkedList ();
1183        for (int x = 0; x < card; x++)
1184            multiValue.add (baseValue);
1185        return multiValue;
1186    }
1187    
1188    // ==========================================================================
1189
// Corba types resolving
1190
// ==========================================================================
1191

1192    public Classifier resolveCorbaType (XmiElement.DataTypeElement.Node node, boolean nestedCall) {
1193        node = node.firstSubNode ();
1194        String JavaDoc id = node.name;
1195        if (id.equals (XmiConstants.XMICorbaTcShort))
1196            return resolveCorbaPrimitive (node, XmiConstants.INTEGER_TYPE, nestedCall);
1197        if (id.equals (XmiConstants.XMICorbaTcLong))
1198            return resolveCorbaPrimitive (node, XmiConstants.INTEGER_TYPE, nestedCall);
1199        if (id.equals (XmiConstants.XMICorbaTcUShort))
1200            return resolveCorbaPrimitive (node, XmiConstants.INTEGER_TYPE, nestedCall);
1201        if (id.equals (XmiConstants.XMICorbaTcULong))
1202            return resolveCorbaPrimitive (node, XmiConstants.INTEGER_TYPE, nestedCall);
1203        if (id.equals (XmiConstants.XMICorbaTcFloat))
1204            return resolveCorbaPrimitive (node, XmiConstants.FLOAT_TYPE, nestedCall);
1205        if (id.equals (XmiConstants.XMICorbaTcDouble))
1206            return resolveCorbaPrimitive (node, XmiConstants.DOUBLE_TYPE, nestedCall);
1207        if (id.equals (XmiConstants.XMICorbaTcBoolean))
1208            return resolveCorbaPrimitive (node, XmiConstants.BOOLEAN_TYPE, nestedCall);
1209        if (id.equals (XmiConstants.XMICorbaTcChar))
1210            return resolveCorbaPrimitive (node, XmiConstants.INTEGER_TYPE, nestedCall);
1211        if (id.equals (XmiConstants.XMICorbaTcWChar))
1212            return resolveCorbaPrimitive (node, XmiConstants.INTEGER_TYPE, nestedCall);
1213        if (id.equals (XmiConstants.XMICorbaTcOctet))
1214            return resolveCorbaPrimitive (node, XmiConstants.INTEGER_TYPE, nestedCall);
1215        if (id.equals (XmiConstants.XMICorbaTcString))
1216            return resolveCorbaPrimitive (node, XmiConstants.STRING_TYPE, nestedCall);
1217        if (id.equals (XmiConstants.XMICorbaTcWString))
1218            return resolveCorbaPrimitive (node, XmiConstants.STRING_TYPE, nestedCall);
1219        if (id.equals (XmiConstants.XMICorbaTcLongLong))
1220            return resolveCorbaPrimitive (node, XmiConstants.LONG_TYPE, nestedCall);
1221        if (id.equals (XmiConstants.XMICorbaTcULongLong))
1222            return resolveCorbaPrimitive (node, XmiConstants.LONG_TYPE, nestedCall);
1223        if (id.equals (XmiConstants.XMICorbaTcLongDouble))
1224            return resolveCorbaPrimitive (node, XmiConstants.DOUBLE_TYPE, nestedCall);
1225        
1226        if (id.equals (XmiConstants.XMICorbaTcStruct))
1227            return resolveCorbaStruct (node);
1228        if (id.equals (XmiConstants.XMICorbaTcEnum))
1229            return resolveCorbaEnum (node);
1230        if (id.equals (XmiConstants.XMICorbaTcAlias))
1231            return resolveCorbaAlias (node);
1232        if (id.equals (XmiConstants.XMICorbaTcAny))
1233            return resolveCorbaPrimitive (node, XmiConstants.STRING_TYPE, nestedCall);
1234        
1235        throw new DebugException ("Unsupported Corba type: " + id);
1236    }
1237        
1238    private Classifier resolveCorbaStruct (XmiElement.DataTypeElement.Node node) {
1239        StructureField field;
1240        Classifier fieldType;
1241        boolean hasPrimType = false;
1242        String JavaDoc name = node.tcName;
1243        StructureFieldClass fieldProxy = modelPackage.getStructureField ();
1244        List fields = new LinkedList ();
1245        Iterator iter = node.subnodes.iterator ();
1246        while (iter.hasNext ()) {
1247            XmiElement.DataTypeElement.Node fieldNode =
1248                (XmiElement.DataTypeElement.Node) iter.next ();
1249            String JavaDoc fieldName = fieldNode.tcName;
1250            fieldType = resolveCorbaType (fieldNode.firstSubNode (), true);
1251            field = fieldProxy.createStructureField (
1252                fieldName, ANNOTATION
1253            );
1254            field.setType ((Classifier) fieldType);
1255            fields.add (field);
1256        }
1257        StructureTypeClass proxyClass = modelPackage.getStructureType();
1258        StructureType struct = proxyClass.createStructureType (
1259            name, ANNOTATION, false, false, false, VisibilityKindEnum.PUBLIC_VIS
1260        );
1261        iter = fields.iterator ();
1262        while (iter.hasNext ()) {
1263            field = (StructureField) iter.next ();
1264            field.setContainer (struct);
1265            fieldType = field.getType ();
1266            if (fieldType instanceof PrimitiveType) {
1267                hasPrimType = true;
1268            } else {
1269                fieldType.setContainer(struct);
1270            }
1271        }
1272        if (hasPrimType) {
1273            corbaTypesReferencingPrimitiveTypes.add (struct);
1274        }
1275        return struct;
1276    }
1277
1278    private Classifier resolveCorbaEnum (XmiElement.DataTypeElement.Node node) {
1279        String JavaDoc name = node.tcName;
1280        List labels = new LinkedList ();
1281        Iterator iter = node.subnodes.iterator ();
1282        while (iter.hasNext ()) {
1283            XmiElement.DataTypeElement.Node labelNode =
1284                (XmiElement.DataTypeElement.Node) iter.next ();
1285            labels.add (labelNode.tcName);
1286        }
1287        EnumerationTypeClass proxyClass = modelPackage.getEnumerationType();
1288        return proxyClass.createEnumerationType (
1289            name, ANNOTATION, false, false, false, VisibilityKindEnum.PUBLIC_VIS, labels
1290        );
1291    }
1292
1293    private Classifier resolveCorbaAlias (XmiElement.DataTypeElement.Node node) {
1294        String JavaDoc name = node.tcName;
1295        Classifier type = resolveCorbaType (node.firstSubNode (), true);
1296        AliasType alias = modelPackage.getAliasType ().createAliasType (
1297            name, ANNOTATION,
1298            false, false, false, VisibilityKindEnum.PUBLIC_VIS
1299        );
1300        alias.setType (type);
1301        if (type instanceof PrimitiveType) {
1302            corbaTypesReferencingPrimitiveTypes.add (alias);
1303        } else {
1304            type.setContainer (alias);
1305        }
1306        return alias;
1307    }
1308
1309    /**
1310     * Resolves Corba primitive type as an Alias pointing to an equivalent
1311     * of the primitive type.
1312     */

1313    private Classifier resolveCorbaPrimitive (XmiElement.DataTypeElement.Node node, String JavaDoc name, boolean nestedCall) {
1314        PrimitiveType primitive = substCorbaPrimitive (node, name);
1315        if (nestedCall) {
1316            return primitive;
1317        } else {
1318            AliasType alias = modelPackage.getAliasType ().createAliasType (
1319                name, ANNOTATION,
1320                false, false, false, VisibilityKindEnum.PUBLIC_VIS
1321            );
1322            alias.setType (primitive);
1323            // Store created Alias instance to be able set all needed Imports later when
1324
// all elements of XMI document are deserialized.
1325
corbaTypesReferencingPrimitiveTypes.add (alias);
1326            return alias;
1327        }
1328    }
1329    
1330    private PrimitiveType substCorbaPrimitive (XmiElement.DataTypeElement.Node node, String JavaDoc name) {
1331        if (primitiveTypes == null) {
1332            // locate PrimitiveTypes package, if it does not exist, create it
1333
if (modelPackage == null)
1334                throw new DebugException ("Unable to create PrimitiveType for " + name);
1335            MofPackageClass proxy = modelPackage.getMofPackage ();
1336            Iterator iter = proxy.refAllOfType ().iterator ();
1337            while (iter.hasNext ()) {
1338                MofPackage pckg = ((MofPackage) iter.next ());
1339                if (XmiConstants.PRIMITIVE_TYPES_PACKAGE.equals (pckg.getName ())) {
1340                    primitiveTypesPackage = pckg;
1341                    break;
1342                }
1343            } // while
1344
primitiveTypes = new HashMap ();
1345            if (primitiveTypesPackage == null) {
1346                /* <Model.Package name = 'CorbaIdlTypes' annotation = '' isRoot = 'false'
1347                 isLeaf = 'false' isAbstract = 'false' visibility = 'public_vis'> */

1348                primitiveTypesPackage = proxy.createMofPackage (
1349                    XmiConstants.PRIMITIVE_TYPES_PACKAGE, ANNOTATION,
1350                    false, false, false, VisibilityKindEnum.PUBLIC_VIS
1351                );
1352                Tag tag = modelPackage.getTag ().createTag ();
1353                tag.setTagId ("javax.jmi.packagePrefix");
1354                tag.getValues ().add ("javax.jmi");
1355                tag.getElements ().add (primitiveTypesPackage);
1356                PrimitiveType type;
1357                PrimitiveTypeClass typeProxy = modelPackage.getPrimitiveType ();
1358                for (int x = 0; x < PRIMITIVE_TYPES.length; x++) {
1359                    type = typeProxy.createPrimitiveType (
1360                        PRIMITIVE_TYPES [x], ANNOTATION, false, false, false,
1361                        VisibilityKindEnum.PUBLIC_VIS
1362                    );
1363                    type.setContainer (primitiveTypesPackage);
1364                    primitiveTypes.put (PRIMITIVE_TYPES [x], type);
1365                } // for
1366
} else {
1367                for (Iterator contents = primitiveTypesPackage.getContents().iterator();
1368                    contents.hasNext();) {
1369                    ModelElement type = (ModelElement) contents.next();
1370                    if (type instanceof PrimitiveType)
1371                        primitiveTypes.put (type.getName (), type);
1372                } // for
1373
} // else
1374
} // if
1375

1376        PrimitiveType type = (PrimitiveType) primitiveTypes.get (name);
1377        if (type == null) {
1378            type = modelPackage.getPrimitiveType ().createPrimitiveType (
1379                name, ANNOTATION, false, false, false, VisibilityKindEnum.PUBLIC_VIS
1380            );
1381            type.setContainer (primitiveTypesPackage);
1382            primitiveTypes.put (name, type);
1383        }
1384        return type;
1385    }
1386    
1387    public void countInstance () {
1388        instancesCounter++;
1389    }
1390
1391    // XMIReferenceResolver.Client implementation ...............................
1392

1393    public class Client implements XMIReferenceResolver.Client {
1394    
1395        private HashMap refs;
1396        
1397        public Client (HashMap refs) {
1398            this.refs = refs;
1399        }
1400        
1401        public void resolvedReference (String JavaDoc href, RefObject obj) {
1402            resolvedReference (href, obj, false);
1403        }
1404        
1405        public void resolvedReference (String JavaDoc href, RefObject obj, boolean internalCall) {
1406            if (!internalCall) {
1407                XMIReferenceProvider.XMIReference xmiRef = toXMIReference (href);
1408                putReference (xmiRef.getSystemId (), xmiRef.getXmiId (), obj);
1409            }
1410            allUnresolvedHRefs.remove (href);
1411            
1412            List list = (List) refs.remove (href);
1413            if (list != null) {
1414                Iterator iter = list.iterator ();
1415                while (iter.hasNext ()) {
1416                    ((XmiElement.UnresolvedReference) iter.next ()).referenceResolved (obj);
1417                } // while
1418
} // if
1419
}
1420    
1421    } // Client
1422

1423}
1424
Popular Tags