KickJava   Java API By Example, From Geeks To Geeks.

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


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.io.*;
22 import java.util.*;
23 import java.net.URL JavaDoc;
24
25 import org.xml.sax.ContentHandler JavaDoc;
26 import org.xml.sax.SAXException JavaDoc;
27 import org.xml.sax.helpers.AttributesImpl JavaDoc;
28
29 import org.netbeans.lib.jmi.util.DebugException;
30 import org.netbeans.api.xmi.*;
31
32 import javax.jmi.reflect.*;
33 import javax.jmi.model.*;
34 import org.netbeans.lib.jmi.util.Logger;
35
36 public class XMI20Writer extends WriterBase {
37
38     private static final String JavaDoc XMI_VERSION = "2.0";
39     private static final String JavaDoc XMI_NAMESPACE = "";
40
41     private Map nsPrefixToURI;
42     
43     // init .....................................................................
44

45     public XMI20Writer() {
46         super ();
47     }
48
49     public XMI20Writer(XMIOutputConfig config) {
50         super (config);
51     }
52     
53     public void init () throws IOException {
54         super.init ();
55         nsPrefixToURI = new HashMap ();
56     }
57     
58     // methods ..................................................................
59

60     protected void findNamespaces(RefPackage pkg) {
61         String JavaDoc name, uri;
62         Iterator iter;
63
64         if (processedPackages.contains (pkg))
65             return;
66
67         MofPackage metaPackage = (MofPackage) pkg.refMetaObject ();
68         
69         name = getNsPrefixTag (metaPackage);
70         if (name == null) {
71             name = getTagValue (metaPackage, XmiConstants.TAGID_XMI_NAMESPACE);
72         }
73          
74         if (name != null) {
75             iter = metaPackage.getQualifiedName ().iterator ();
76             String JavaDoc fqName = (String JavaDoc) iter.next ();
77             while (iter.hasNext ())
78                 fqName = fqName.concat (XmiConstants.DOT_SEPARATOR).concat ((String JavaDoc) iter.next ());
79             namespaces.put (fqName, name);
80             uri = getNsURITag (metaPackage);
81             if (uri == null) {
82                 uri = "unknown_uri"; // NOI18N
83
}
84             nsPrefixToURI.put (name, uri);
85         }
86
87         processedPackages.add (pkg);
88         iter = pkg.refAllPackages ().iterator ();
89         while (iter.hasNext ()) {
90             findNamespaces ((RefPackage) iter.next ());
91         }
92     }
93
94     protected void writeDocument(RefPackage pkg) {
95         try {
96             contentHandler.startDocument();
97         } catch (SAXException JavaDoc e) {
98         }
99         
100         startElement (XMI_NAMESPACE + XmiConstants.XMI_ROOT);
101         addAttribute (XMI_NAMESPACE + "version", XMI_VERSION);
102         writeNamespaces ();
103                 
104         if (!collectionWriting) {
105             processedPackages.clear();
106             writePackage (pkg);
107          
108             RefObject obj;
109             while (nonWrittenComponents.size () > 0) {
110                 Iterator iter = nonWrittenComponents.iterator ();
111                 do {
112                     obj = (RefObject) iter.next ();
113                 } while (nonWrittenComponents.contains (obj.refImmediateComposite ()));
114                 writeInstance (obj, true);
115                 while (lightOutermosts.size() > 0) {
116                     obj = (RefObject) lightOutermosts.remove(0);
117                     writeInstance (obj, true);
118                 } // while
119
} // while
120

121             processedPackages.clear();
122             writeStaticAttributes (pkg);
123         } else {
124             writeObjects ();
125         }
126         processedPackages.clear();
127         writeAssociations (pkg);
128                 
129         endElement (XMI_NAMESPACE + XmiConstants.XMI_ROOT);
130         try {
131             contentHandler.endDocument();
132         } catch (SAXException JavaDoc e) {
133         }
134     }
135
136     protected void writeNamespaces() {
137         String JavaDoc xmiNamespace = (XMI_NAMESPACE.length () == 0) ? "xmlns" : "xmlns:" + XMI_NAMESPACE.substring (XMI_NAMESPACE.length () - 1);
138         addAttribute (xmiNamespace, XmiConstants.XMI_NAMESPACE_URI);
139         HashMap temp = new HashMap ();
140         Iterator iter = namespaces.entrySet ().iterator ();
141         while (iter.hasNext ()) {
142             String JavaDoc name = (String JavaDoc) ((Map.Entry) iter.next ()).getValue ();
143             if (temp.get (name) == null) {
144                 temp.put (name, name);
145                 addAttribute ("xmlns:" + name, (String JavaDoc) nsPrefixToURI.get (name));
146             } // if
147
} // while
148
}
149
150     /**
151      * Serializes an instance.
152      *
153      * @param obj object to be serialized
154      * @param isTop true if the instance is serialized as a top-element (i.e. direct sub-element of <content>)
155      */

156     protected void writeInstance(RefObject obj, boolean isTop) {
157         RefClass proxy = obj.refClass ();
158         ModelElement element = (ModelElement) obj.refMetaObject ();
159         String JavaDoc name = qualifiedName (element);
160         XMIReferenceProvider.XMIReference xmiRef = provider.getReference (obj);
161         String JavaDoc xmiId = xmiRef.getXmiId ();
162         String JavaDoc systemId = xmiRef.getSystemId ();
163         if ((systemId != null) && (thisSystemId != null) && (thisSystemId.equals (systemId)))
164             systemId = null;
165         
166         markWritten (obj);
167         if (systemId != null) { // object from an external document
168
if (!isTop) { // serialize href
169
startElement (name);
170                 addAttribute (XMI_NAMESPACE + "href", systemId + HREF_DELIMITER + xmiId);
171                 endElement (name);
172             }
173             collectLightOutermosts (obj, proxy);
174             return;
175         }
176                 
177         startElement (name);
178         addAttribute (XMI_NAMESPACE + "id", xmiId);
179         Iterator attrs = instanceAttributes ((MofClass) proxy.refMetaObject ()).iterator ();
180         List attrsInContent = new LinkedList ();
181         while (attrs.hasNext ()) {
182             Attribute attr = (Attribute) attrs.next ();
183             
184             if (!isSerializeTag (attr)) {
185                 continue;
186             } else if (isElementTag (attr)) {
187                 attrsInContent.add (attr);
188                 continue;
189             }
190             
191             boolean isMultivalued = isMultivalued (attr);
192             Object JavaDoc value;
193             try {
194             value = obj.refGetValue (attr);
195             } catch (Exception JavaDoc e) {
196                 Logger.getDefault().annotate(e, ((ModelElement) obj.refMetaObject ()).getName () + " " + attr.getName ());
197                 Logger.getDefault().notify(e);
198                 value = Boolean.FALSE;
199             }
200             Object JavaDoc valueToWrite = value;
201             if (value == null) {
202                 continue; // optional attribute of no value
203
}
204             if (isMultivalued) {
205                 Collection col = (Collection) value;
206                 if (col.isEmpty ())
207                     continue;
208                 if (col.size () > 1) {
209                     // values have to be serialized in content
210
attrsInContent.add (attr);
211                     continue;
212                 } else
213                     valueToWrite = col.iterator ().next ();
214             } // if
215
Classifier type = getType (attr);
216             if (!(type instanceof PrimitiveType) && !(type instanceof EnumerationType)) {
217                 // values have to be serialized in content
218
attrsInContent.add (attr);
219             } else
220                 writeValueInAttr (attr, valueToWrite);
221         } // while
222
Iterator iter = attrsInContent.iterator ();
223         while (iter.hasNext ()) {
224             Attribute attr = (Attribute) iter.next ();
225             writeValueInContent (attr, obj.refGetValue (attr));
226         } // while
227
Iterator refs = references ((MofClass) proxy.refMetaObject ()).iterator ();
228         while (refs.hasNext ()) {
229             Reference ref = (Reference) refs.next ();
230             writeReference (obj, ref);
231         }
232         endElement (name);
233     }
234             
235     /**
236      * Writes reference to an instance (e.g. <Model:Class xmi.idref = 'a1'/>).
237      *
238      * @param obj an instance the reference points to
239      * @param externalOnly if true, the reference is written only if it points to an external document
240      * @param hrefForced if true, href reference is always used
241      */

242     protected void writeInstanceRef (RefObject obj, boolean externalOnly, boolean hrefForced) {
243         String JavaDoc name = qualifiedName ((ModelElement) obj.refMetaObject ());
244         XMIReferenceProvider.XMIReference xmiRef = provider.getReference (obj);
245         String JavaDoc xmiId = xmiRef.getXmiId ();
246         String JavaDoc systemId = xmiRef.getSystemId ();
247         
248         if (externalOnly && systemId == null)
249             return;
250         
251         if ((systemId != null) && (thisSystemId != null) && (thisSystemId.equals (systemId)) && !hrefForced) {
252             systemId = null;
253         } else if ((systemId == null) && hrefForced) {
254             systemId = thisSystemId;
255         }
256         
257         startElement (name);
258         if (systemId == null) {
259             addAttribute (XMI_NAMESPACE + "idref", xmiId);
260         } else {
261             addAttribute (XMI_NAMESPACE + "href", systemId + HREF_DELIMITER + xmiId);
262         }
263         endElement (name);
264     }
265
266     /**
267      * Serializes structure.
268      */

269     protected void writeStructure (StructureType type, RefStruct value) {
270         String JavaDoc name = qualifiedName (type);
271         startElement (name);
272         Iterator content = structureFields (type).iterator ();
273         List fields = new LinkedList ();
274         while (content.hasNext ()) {
275             StructureField field = (StructureField) content.next ();
276             
277             if (!isSerializeTag (field)) {
278                 continue;
279             } else if (isElementTag (field)) {
280                 fields.add (field); // serialize value of the field as a sub-element
281
continue;
282             }
283             
284             Classifier fieldType = getType ((StructureField) field);
285             if ((fieldType instanceof PrimitiveType) ||
286                 (fieldType instanceof EnumerationType)) {
287                 writeValueInAttr (
288                     (StructureField) field,
289                     value.refGetValue (((ModelElement) field).getName ())
290                 );
291             } else
292                 fields.add (field);
293         } // while
294
Iterator iter = fields.iterator ();
295         while (iter.hasNext ()) {
296             StructureField field = (StructureField) iter.next ();
297             Object JavaDoc fieldValue = value.refGetValue (((ModelElement) field).getName ());
298             writeValueInContent (field, fieldValue);
299         } // while
300
endElement (name);
301     }
302
303     /**
304      * Serializes Reference.
305      */

306     protected void writeReference(RefObject obj, Reference ref) {
307         AggregationKind kind = ref.getReferencedEnd ().getAggregation ();
308         if (AggregationKindEnum.COMPOSITE.equals (kind))
309             return; // do not serialize reference to immediate composite object
310
kind = ref.getExposedEnd ().getAggregation ();
311         boolean isComposite = AggregationKindEnum.COMPOSITE.equals (kind);
312         Object JavaDoc temp = obj.refGetValue (ref);
313         if (temp == null)
314             return;
315         Collection values;
316         if (isMultivalued (ref))
317             values = (Collection) temp;
318         else {
319             values = new LinkedList ();
320             values.add (temp);
321         }
322         Iterator iter;
323         
324         if (collectionWriting) {
325             // exclude all referenced instances that are not in the transitive closure generated by input collection
326
Collection cValues = new LinkedList ();
327             iter = values.iterator ();
328             while (iter.hasNext ()) {
329                 RefObject referencedObject = (RefObject) iter.next ();
330                 if (isInClosure (referencedObject)) {
331                     cValues.add (referencedObject);
332                 } // if
333
} // while
334
values = cValues;
335         } // if
336

337         if (values.isEmpty ())
338             return;
339
340         String JavaDoc name = qualifiedName (ref);
341         startElement (name);
342         iter = values.iterator ();
343         while (iter.hasNext ()) {
344             RefObject endValue = (RefObject) iter.next ();
345             if (isComposite)
346                 writeInstance (endValue, false);
347             else {
348                 writeInstanceRef (endValue, isRemoteOnlyTag (ref), isHrefTag (ref));
349             }
350         } // while
351
endElement (name);
352     }
353     
354     public String JavaDoc labelPrefix (EnumerationType type) {
355         return "";
356     }
357     
358     /**
359      * Returns fully qualified name of an model element.
360      */

361     protected String JavaDoc qualifiedName (ModelElement element) {
362         Iterator iter = element.getQualifiedName ().iterator ();
363         String JavaDoc name = (String JavaDoc) iter.next ();
364         while (iter.hasNext ())
365             name = name.concat (XmiConstants.DOT_SEPARATOR).concat ((String JavaDoc) iter.next ());
366
367         int index = name.lastIndexOf ('.');
368         String JavaDoc pName = name.substring (0, index);
369         String JavaDoc sName = name.substring (index + 1, name.length ());
370         if (!(element instanceof MofClass)) {
371             index = pName.lastIndexOf ('.');
372             if (index != -1) {
373                 pName = pName.substring (0, index);
374                 sName = name.substring (index + 1, name.length ());
375             }
376         }
377         String JavaDoc xmiName = getXmiNameTag (element);
378         if (xmiName != null)
379             sName = xmiName;
380         
381         String JavaDoc namespace = (String JavaDoc) namespaces.get (pName);
382
383         if (namespace != null)
384             return namespace + ":" + sName;
385         return pName + '.' + sName;
386     }
387     
388     protected String JavaDoc elementName (ModelElement elem) {
389         String JavaDoc name = getXmiNameTag (elem);
390         return name != null ? name : elem.getName ();
391     }
392     
393     // tag values getters .......................................................
394

395     public String JavaDoc getContentScopedTagValue (ModelElement elem, String JavaDoc tagId) {
396         String JavaDoc value = null;
397         while ((value == null) && (elem != null)) {
398             value = getTagValue (elem, tagId);
399             elem = elem.getContainer ();
400         }
401         if (value != null)
402             value = value.trim ();
403         return value;
404     }
405     
406     public boolean isElementTag (ModelElement elem) {
407         String JavaDoc value = getContentScopedTagValue (elem, XmiConstants.TAG_ELEMENT);
408         return (value != null) && value.equals ("true");
409     }
410
411     public boolean isHrefTag (ModelElement elem) {
412         String JavaDoc value = getContentScopedTagValue (elem, XmiConstants.TAG_HREF);
413         return (value != null) && value.equals ("true");
414     }
415     
416     public String JavaDoc getXmiNameTag (ModelElement elem) {
417         return getTagValue (elem, XmiConstants.TAG_XMI_NAME);
418     }
419     
420     public boolean isSerializeTag (ModelElement elem) {
421         String JavaDoc value = getTagValue (elem, XmiConstants.TAG_SERIALIZE);
422         return (value == null) || value.equals ("true");
423     }
424     
425     public boolean isRemoteOnlyTag (ModelElement elem) {
426         String JavaDoc value = getTagValue (elem, XmiConstants.TAG_REMOTE_ONLY);
427         return (value != null) && value.equals ("true");
428     }
429
430     public String JavaDoc getNsPrefixTag (ModelElement elem) {
431         return getContentScopedTagValue (elem, XmiConstants.TAG_NS_PREFIX);
432     }
433     
434     public String JavaDoc getNsURITag (ModelElement elem) {
435         return getContentScopedTagValue (elem, XmiConstants.TAG_NS_URI);
436     }
437     
438 }
439
Popular Tags