KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > lib > jmi > mapping > JavaMapper


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
20 package org.netbeans.lib.jmi.mapping;
21
22 import org.netbeans.api.mdr.JMIStreamFactory;
23 import org.netbeans.lib.jmi.util.ContainsIterator;
24 import org.netbeans.lib.jmi.util.Logger;
25 import javax.jmi.model.*;
26 import java.io.BufferedReader JavaDoc;
27 import java.io.IOException JavaDoc;
28 import java.io.PrintStream JavaDoc;
29 import java.io.StringReader JavaDoc;
30 import java.text.MessageFormat JavaDoc;
31 import java.util.*;
32
33 /**
34  * Generates java interfaces for specified meta objects or whole meta model.
35  *
36  * @author Martin Matula, Dusan Balek
37  */

38 public class JavaMapper extends GenericMapper {
39
40     // Java doc constants .......................................................
41

42     // attribute template
43
// getter (single-value)
44
private static final String JavaDoc DOC_ATTR_GETTER = "Returns the value of attribute {0}."; //NOI18N
45
private static final String JavaDoc DOC_ATTR_GETTER_RETURN = "Value of attribute {0}."; //NOI18N
46
// setter
47
private static final String JavaDoc DOC_ATTR_SETTER = "Sets the value of {0} attribute. See '{'@link #{1}'}' for description on the attribute."; //NOI18N
48
private static final String JavaDoc DOC_ATTR_SETTER_PARAM = "New value to be set."; //NOI18N
49
// getter (multi-value)
50
private static final String JavaDoc DOC_ATTR_GETTER_RETURN_ORDERED = "Value of {0} attribute. Element type: '{'@link {1}'}'"; //NOI18N
51
private static final String JavaDoc DOC_ATTR_GETTER_RETURN_MULTI = "Value of {0} attribute. Element type: '{'@link {1}'}'"; //NOI18N
52

53     // association template
54
private static final String JavaDoc DOC_ASSOC_PROXY = "{0} association proxy interface."; //NOI18N
55
// exists method
56
private static final String JavaDoc DOC_ASSOC_EXISTS = "Queries whether a link currently exists between a given pair of instance objects in the association's link set."; //NOI18N
57
private static final String JavaDoc DOC_ASSOC_EXISTS_PARAM1 = "Value of the first association end."; //NOI18N
58
private static final String JavaDoc DOC_ASSOC_EXISTS_PARAM2 = "Value of the second association end."; //NOI18N
59
private static final String JavaDoc DOC_ASSOC_EXISTS_RETURN = "Returns true if the queried link exists."; //NOI18N
60
// add method
61
private static final String JavaDoc DOC_ASSOC_ADD = "Creates a link between the pair of instance objects in the association's link set."; //NOI18N
62
// remove method
63
private static final String JavaDoc DOC_ASSOC_REMOVE = "Removes a link between a pair of instance objects in the current association's link set."; //NOI18N
64
// get end_1 method
65
private static final String JavaDoc DOC_ASSOC_GET_END1_SINGLE = "Queries the instance object that is related to a particular instance object by a link in the current association's link set."; //NOI18N
66
private static final String JavaDoc DOC_ASSOC_GET_END1_MULTI = "Queries the instance objects that are related to a particular instance object by a link in the current association's link set."; //NOI18N
67
private static final String JavaDoc DOC_ASSOC_GET_END1_ORDERED = "Queries the instance objects that are related to a particular instance object by a link in the current association's link set."; //NOI18N
68
private static final String JavaDoc DOC_ASSOC_GET_END1_PARAM = "Required value of the first association end."; //NOI18N
69
private static final String JavaDoc DOC_ASSOC_GET_END1_RETURN_SINGLE = "Related object or <code>null</code> if none exists."; //NOI18N
70
private static final String JavaDoc DOC_ASSOC_GET_END1_RETURN_MULTI = "Collection of related objects."; //NOI18N
71
private static final String JavaDoc DOC_ASSOC_GET_END1_RETURN_ORDERED = "List of related objects."; //NOI18N
72
// get end_2 method
73
private static final String JavaDoc DOC_ASSOC_GET_END2_PARAM = "Required value of the second association end."; //NOI18N
74

75     // class instance template
76
private static final String JavaDoc DOC_INSTANCE = "{0} object instance interface."; //NOI18N
77

78     // reference template
79
// getter (single-value)
80
private static final String JavaDoc DOC_REFERENCE_GETTER = "Returns the value of reference {0}."; //NOI18N
81
private static final String JavaDoc DOC_REFERENCE_GETTER_RETURN = "Value of reference {0}."; //NOI18N
82
// setter
83
private static final String JavaDoc DOC_REFERENCE_SETTER = "Sets the value of reference {0}. See '{'@link #{1}'}' for description on the reference."; //NOI18N
84
private static final String JavaDoc DOC_REFERENCE_SETTER_PARAM = "New value to be set."; //NOI18N
85
// getter (multi-value)
86
private static final String JavaDoc DOC_REFERENCE_GETTER_RETURN_ORDERED = "Value of reference {0}. Element type: '{'@link {1}'}'"; //NOI18N
87
private static final String JavaDoc DOC_REFERENCE_GETTER_RETURN_MULTI = "Value of reference {0}. Element type: '{'@link {1}'}'"; //NOI18N
88

89     // class proxy template
90
private static final String JavaDoc DOC_CLASS_PROXY = "{0} class proxy interface."; //NOI18N
91
// create method (with no args)
92
private static final String JavaDoc DOC_CLASS_PROXY_CREATE = "The default factory operation used to create an instance object."; //NOI18N
93
private static final String JavaDoc DOC_CLASS_PROXY_CREATE_RETURN = "The created instance object."; //NOI18N
94
// create method (with args)
95
private static final String JavaDoc DOC_CLASS_PROXY_CREATE2 = "Creates an instance object having attributes initialized by the passed values."; //NOI18N
96

97     // package template
98
private static final String JavaDoc DOC_PACKAGE = "{0} package interface."; //NOI18N
99
// get<ImportName>
100
private static final String JavaDoc DOC_PACKAGE_GET_IMPORT = "Returns clustered package {1}."; //NOI18N
101
private static final String JavaDoc DOC_PACKAGE_GET_IMPORT_RETURN = "Proxy object related to clustered package {1}."; //NOI18N
102
// get<NestedPackageName>
103
private static final String JavaDoc DOC_PACKAGE_GET_NESTED = "Returns nested package {1}."; //NOI18N
104
private static final String JavaDoc DOC_PACKAGE_GET_NESTED_RETURN = "Proxy object related to nested package {1}."; //NOI18N
105
// get<ClassName>
106
private static final String JavaDoc DOC_PACKAGE_GET_CLASS = "Returns {1} class proxy object."; //NOI18N
107
private static final String JavaDoc DOC_PACKAGE_GET_CLASS_RETURN = "{1} class proxy object."; //NOI18N
108
// get<AssociationName>
109
private static final String JavaDoc DOC_PACKAGE_GET_ASSOC = "Returns {1} association proxy object."; //NOI18N
110
private static final String JavaDoc DOC_PACKAGE_GET_ASSOC_RETURN = "{1} association proxy object."; //NOI18N
111

112     // exception template
113
private static final String JavaDoc DOC_EXCEPTION = "{0} exception implementation class."; //NOI18N
114
// constructor
115
private static final String JavaDoc DOC_EXCEPTION_CONSTRUCTOR = "The public constructor."; //NOI18N
116
// getter
117
private static final String JavaDoc DOC_EXCEPTION_GETTER = "Returns value of parameter {1}."; //NOI18N
118
private static final String JavaDoc DOC_EXCEPTION_GETTER_RETURN = "Value of parameter {1}."; //NOI18N
119

120     // enumeration interface
121
private static final String JavaDoc DOC_ENUM_INTERFACE = "{0} enumeration interface."; //NOI18N
122

123     // enumeration class
124
private static final String JavaDoc DOC_ENUM_CLASS = "{0} enumeration class implementation."; //NOI18N
125
// literal field
126
private static final String JavaDoc DOC_ENUM_LITERAL = "Enumeration constant corresponding to literal {1}."; //NOI18N
127
// refTypeName
128
private static final String JavaDoc DOC_ENUM_REFTYPENAME = "Returns fully qualified name of the enumeration type."; //NOI18N
129
private static final String JavaDoc DOC_ENUM_REFTYPENAME_RETURN = "List containing all parts of the fully qualified name."; //NOI18N
130
// toString
131
private static final String JavaDoc DOC_ENUM_TOSTRING = "Returns a string representation of the enumeration value."; //NOI18N
132
private static final String JavaDoc DOC_ENUM_TOSTRING_RETURN = "A string representation of the enumeration value."; //NOI18N
133
// hashCode
134
private static final String JavaDoc DOC_ENUM_HASHCODE = "Returns a hash code for this the enumeration value."; //NOI18N
135
private static final String JavaDoc DOC_ENUM_HASHCODE_RETURN = "A hash code for this enumeration value."; //NOI18N
136
// equals
137
private static final String JavaDoc DOC_ENUM_EQUALS = "Indicates whether some other object is equal to this enumeration value."; //NOI18N
138
private static final String JavaDoc DOC_ENUM_EQUALS_RETURN = "true if the other object is the enumeration of the same type and of the same value."; //NOI18N
139
private static final String JavaDoc DOC_ENUM_EQUALS_PARAM = "The reference object with which to compare."; //NOI18N
140
// forName
141
private static final String JavaDoc DOC_ENUM_FORNAME = "Translates literal name to correspondent enumeration value."; //NOI18N
142
private static final String JavaDoc DOC_ENUM_FORNAME_RETURN = "Enumeration value corresponding to the passed literal."; //NOI18N
143
private static final String JavaDoc DOC_ENUM_FORNAME_PARAM = "Enumeration literal."; //NOI18N
144
// readResolve
145
private static final String JavaDoc DOC_ENUM_READRESOLVE = "Resolves serialized instance of enumeration value."; //NOI18N
146
private static final String JavaDoc DOC_ENUM_READRESOLVE_RETURN = "Resolved enumeration value."; //NOI18N
147

148     // structure template
149
private static final String JavaDoc DOC_STRUCT = "{0} structure interface."; //NOI18N
150
// create<StructureTypeName>
151
private static final String JavaDoc DOC_STRUCT_CREATE = "Creates an instance of {0} structure type."; //NOI18N
152
private static final String JavaDoc DOC_STRUCT_CREATE_RETURN = "Value of {0}."; //NOI18N
153
// getter
154
private static final String JavaDoc DOC_STRUCT_GETTER = "Returns value of {1} field."; //NOI18N
155
private static final String JavaDoc DOC_STRUCT_GETTER_RETURN = "Value of {1} field."; //NOI18N
156

157     // warning - for every file
158
private static final String JavaDoc DOC_WARNING = "<p><em><strong>Note:</strong> This type should not be subclassed or implemented by clients. It is generated from a MOF metamodel and automatically implemented by MDR (see <a HREF=\"http://mdr.netbeans.org/\">mdr.netbeans.org</a>).</em></p>"; // NOI18N
159

160     // ..........................................................................
161

162     // indentation level of generated text
163
private int indentation = 0;
164
165     // generator class used to generate source code
166
private final JMIStreamFactory generator;
167
168     // tab
169
private static final String JavaDoc TAB = " "; //NOI18N
170
// stream
171
private PrintStream JavaDoc stream = null;
172     // header
173
private String JavaDoc header = null;
174
175     // method used to write a line of text
176
private void generate(String JavaDoc text) throws IOException JavaDoc {
177         // indent the line
178
generateTabs();
179         // write the text
180
stream.println(text);
181         checkStreamForErrors(stream);
182     }
183
184     private void generateTabs() throws IOException JavaDoc {
185         // indent the line
186
for (int i = 0; i < indentation; i++) {
187             stream.print(TAB);
188         }
189         checkStreamForErrors(stream);
190     }
191
192     // method used to write a new line
193
private void newLine() throws IOException JavaDoc {
194         stream.println();
195         checkStreamForErrors(stream);
196     }
197
198     // method for indenting generated text
199
private void indent() {
200         indentation++;
201     }
202
203     // method for indenting generated text the specified number of tabs (absolutely)
204
private void indent(int count) {
205         indentation = count;
206     }
207
208     // method for unindenting generated text
209
private void unindent() {
210         indentation--;
211     }
212     
213     protected boolean createStream(List pkg, String JavaDoc name) throws IOException JavaDoc {
214         if (stream != null) {
215             closeStream();
216             throw new IllegalStateException JavaDoc("Attempting to create stream before previous stream was closed.");
217         }
218         java.io.OutputStream JavaDoc os = generator.createStream(pkg, name);
219         if (os != null) {
220             stream = new PrintStream JavaDoc(os);
221         }
222         return stream != null;
223     }
224
225     protected void closeStream() throws IOException JavaDoc {
226         if (stream == null)
227             throw new IllegalStateException JavaDoc("Attempting to close the stream without opening it first.");
228         PrintStream JavaDoc ps = stream;
229         stream = null;
230         ps.close();
231         checkStreamForErrors(ps);
232     }
233     
234     private static void checkStreamForErrors(PrintStream JavaDoc ps) throws IOException JavaDoc {
235         if (ps.checkError())
236             throw new IOException JavaDoc("Error writing to print stream during JMI Source generator.");
237     }
238     
239     /**
240      * Method used to generate interface header.
241      * @param pkg Name of package for the interface.
242      * @param name Name for the interface.
243      * @param ancestors Array of interface ancestors' names.
244      */

245     private void interfaceHeader(String JavaDoc pkg, String JavaDoc name, Object JavaDoc[] ancestors, ModelElement elem, String JavaDoc comment) throws IOException JavaDoc {
246         classHeader(pkg, name, ancestors, null, true, elem, comment);
247     }
248
249     /**
250      * Method used to generate class or interface header.
251      * @param pkg Name of package for the class.
252      * @param name Name for the class.
253      * @param ancestors Array of classes ancestors' names.
254      * @param interfaces Array of implemented interfaces.
255      * @param isInterface If true, method will generate an interface header. In this case the implements argument is ignored.
256      */

257     private void classHeader(String JavaDoc pkg, String JavaDoc name, Object JavaDoc[] ancestors, Object JavaDoc[] interfaces, boolean isInterface, ModelElement elem, String JavaDoc comment) throws IOException JavaDoc {
258         classHeader(pkg, name, ancestors, interfaces, isInterface, false, elem, comment);
259     }
260     
261     /**
262      * Method used to generate class or interface header.
263      * @param pkg Name of package for the class.
264      * @param name Name for the class.
265      * @param ancestors Array of classes ancestors' names.
266      * @param interfaces Array of implemented interfaces.
267      * @param isInterface If true, method will generate an interface header. In this case the implements argument is ignored.
268      */

269     private void classHeader(String JavaDoc pkg, String JavaDoc name, Object JavaDoc[] ancestors, Object JavaDoc[] interfaces, boolean isInterface, boolean isFinal, ModelElement elem, String JavaDoc comment) throws IOException JavaDoc {
270         // reset the indentation
271
indent(0);
272
273         StringBuffer JavaDoc sbAnc = new StringBuffer JavaDoc();
274         StringBuffer JavaDoc sbIfc = new StringBuffer JavaDoc();
275         String JavaDoc type;
276         
277         // --- here starts the generation of header
278
// generate header comment
279
if (header != null) {
280             generate(header);
281             newLine();
282         }
283         // generate package information
284
generate("package " + pkg + ";"); //NOI18N
285
newLine();
286
287         // generate class Java doc
288
classJavaDoc (elem, comment);
289         // generate class definition header
290
if (ancestors != null) {
291             for (int i = 0; i < ancestors.length; sbAnc.append((String JavaDoc) ancestors[i++])) {
292                 if (sbAnc.length() > 0) sbAnc.append(", "); //NOI18N
293
else sbAnc.append(" extends "); //NOI18N
294
}
295         }
296         if (isInterface) {
297             type = "interface"; //NOI18N
298
} else {
299             if (isFinal) type = "final class"; //NOI18N
300
else type = "class"; //NOI18N
301
if (interfaces != null) {
302                 for (int i = 0; i < interfaces.length; sbIfc.append((String JavaDoc) interfaces[i++])) {
303                     if (sbIfc.length() > 0) sbIfc.append(", "); //NOI18N
304
else sbIfc.append(" implements "); //NOI18N
305
}
306             }
307         }
308         generate("public " + type + " " + name + sbAnc.toString() + sbIfc.toString() + " {"); //NOI18N
309

310         // indent the following text
311
indent();
312     }
313     
314     // method used to generate interface footer
315
private void interfaceFooter(String JavaDoc name) throws IOException JavaDoc {
316         classFooter(name, true);
317     }
318
319     private void classFooter(String JavaDoc name, boolean isInterface) throws IOException JavaDoc {
320         // unindent the following text
321
unindent();
322
323         // generate class ending
324
generate("}"); //NOI18N
325
}
326
327     // generates a method of a given interface
328
private void interfaceMethod(String JavaDoc returnType, String JavaDoc name, Object JavaDoc[] parameters, Object JavaDoc[] exceptions) throws IOException JavaDoc {
329         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
330         StringBuffer JavaDoc sb2 = new StringBuffer JavaDoc();
331
332         if (parameters != null)
333             for (int i = 0; i < parameters.length; sb.append((String JavaDoc) parameters[i++] + " " + (String JavaDoc) parameters[i++])) { //NOI18N
334
if (sb.length() > 0) sb.append(", "); //NOI18N
335
}
336
337         if (exceptions != null)
338             for (int i = 0; i < exceptions.length; sb2.append((String JavaDoc) exceptions[i++])) {
339                 if (sb2.length() > 0) sb2.append(", "); //NOI18N
340
else sb2.append(" throws "); //NOI18N
341
}
342
343         generate("public " + returnType + " " + name + "(" + sb + ")" + sb2 + ";"); //NOI18N
344
}
345
346     // generates an interface field
347
private void interfaceField(String JavaDoc fieldType, String JavaDoc name, String JavaDoc value) throws IOException JavaDoc {
348         generate("public final " + fieldType + " " + name + " = " + value + ";"); //NOI18N
349
}
350
351     // generates an interface constant
352
// generates interface methods for a given attribute
353
private void attributeTemplate(Object JavaDoc objAttribute) throws IOException JavaDoc {
354         Attribute attr = (Attribute) objAttribute;
355         String JavaDoc attrName = firstUpper(tagProvider.getSubstName(attr));
356         Classifier attrType = getAttrType(attr);
357         String JavaDoc attrTypeName = getTypeName(attr, GENERIC_STYLE_FAKE);
358         
359         if (attr.getMultiplicity().getUpper() == 1) {
360             // getter
361
String JavaDoc name;
362             String JavaDoc setterName;
363             if (attrType instanceof PrimitiveType && attrType.getName().equals("Boolean")) { //NOI18N
364
if (attrName.substring(0, 2).equals("Is")) name = firstLower(attrName); //NOI18N
365
else name = "is" + attrName; //NOI18N
366
setterName = "set" + name.substring(2); //NOI18N
367
} else {
368                 name = "get" + attrName; //NOI18N
369
setterName = "set" + attrName; //NOI18N
370
}
371
372             // if multiplicity = [1..1] map to primitive type
373
String JavaDoc getterType = attrTypeName;
374             if (attr.getMultiplicity().getLower() == 1) {
375                 getterType = getPrimitiveName(getterType);
376             }
377             
378             methodJavaDoc(attr, true, DOC_ATTR_GETTER, DOC_ATTR_GETTER_RETURN, null, null, null);
379             interfaceMethod(getterType, name, null, null);
380             
381             // setter
382
if (attr.isChangeable()) {
383                 methodJavaDoc(
384                     attr, false, DOC_ATTR_SETTER, null, new String JavaDoc [] {"newValue"}, //NOI18N
385
new Object JavaDoc [] {DOC_ATTR_SETTER_PARAM}, new String JavaDoc [] {name}
386                 );
387                 interfaceMethod("void", setterName, new String JavaDoc[] {getterType, "newValue"}, null); //NOI18N
388
}
389         } else if (attr.getMultiplicity().getUpper() != 0) {
390             // getter
391
boolean ordered = attr.getMultiplicity().isOrdered();
392             methodJavaDoc(attr, true, DOC_ATTR_GETTER,
393                 (ordered ? DOC_ATTR_GETTER_RETURN_ORDERED : DOC_ATTR_GETTER_RETURN_MULTI), null, null,
394                 new String JavaDoc[] {getTypeName(attrType)}
395             );
396             interfaceMethod(attrTypeName, "get" + attrName, null, null); //NOI18N
397
}
398     }
399
400     // generates interface methods for a given operation
401
private void operationTemplate(Object JavaDoc objOperation) throws IOException JavaDoc {
402         Operation oper = (Operation) objOperation;
403         Collection exceptions = new ArrayList();
404         Collection parameters = new ArrayList();
405         ArrayList parametersList = new ArrayList();
406         ArrayList parametersNames = new ArrayList();
407         
408         String JavaDoc operType = "void"; //NOI18N
409
Parameter param, returnParam = null;
410         ModelElement element;
411         
412         for (Iterator it = oper.getContents().iterator(); it.hasNext();) {
413             element = (ModelElement) it.next();
414             if (element instanceof Parameter) {
415                 param = (Parameter) element;
416                 if (param.getDirection().equals(DirectionKindEnum.RETURN_DIR)) {
417                     operType = getTypeName(param, GENERIC_STYLE_FAKE);
418                     returnParam = param;
419                 } else {
420                     parameters.add(getTypeName(param, GENERIC_STYLE_FAKE));
421                     String JavaDoc name = tagProvider.getSubstName(param) + (param.getDirection().equals(DirectionKindEnum.IN_DIR) ? "" : "[]"); //NOI18N
422
parameters.add(name);
423                     
424                     parametersList.add (param);
425                     parametersNames.add (name);
426                 }
427             }
428         }
429
430         for (Iterator it = oper.getExceptions().iterator(); it.hasNext();) {
431             element = (ModelElement) it.next();
432             exceptions.add(tagProvider.getTypeFullName(element));
433         }
434
435         int size = parametersList.size ();
436         Object JavaDoc [] paramsArray = new Object JavaDoc [size];
437         paramsArray = parametersList.toArray (paramsArray);
438         String JavaDoc [] namesArray = new String JavaDoc [size];
439         namesArray = (String JavaDoc[]) parametersNames.toArray (namesArray);
440         
441         methodJavaDoc(oper, true, null, returnParam, namesArray, paramsArray, null);
442         interfaceMethod(operType, tagProvider.getSubstName(oper), parameters.toArray(), exceptions.toArray());
443     }
444     
445     // generates interface methods for a given constant
446
private void constantTemplate(Object JavaDoc objConstant) throws IOException JavaDoc {
447         Constant constant = (Constant) objConstant;
448         DataType type = (DataType) getAttrType(constant);
449         String JavaDoc value = constant.getValue();
450         
451         if (type.getName ().equals ("String")) { //NOI18N
452
value = "\"" + value.replace('\n', ' ') + "\""; //NOI18N
453
}
454     
455         fieldJavaDoc (constant);
456         interfaceField(getTypeName2(constant), tagProvider.getSubstName(constant), value);
457     }
458
459     // generates interface methods for a given reference
460
private void referenceTemplate(Object JavaDoc objReference) throws IOException JavaDoc {
461         Reference ref = (Reference) objReference;
462         String JavaDoc refName = firstUpper(tagProvider.getSubstName(ref));
463         String JavaDoc refType = getTypeName(getAttrType(ref));
464
465         if (ref.getMultiplicity().getUpper() == 1) {
466             // getter
467
methodJavaDoc (
468                 ref, true, DOC_REFERENCE_GETTER, DOC_REFERENCE_GETTER_RETURN,
469                 null, null, null
470             );
471             interfaceMethod(refType, "get" + refName, null, null); //NOI18N
472

473             // setter
474
if (ref.isChangeable()) {
475                 methodJavaDoc (
476                     ref, false, DOC_REFERENCE_SETTER, null, new String JavaDoc [] {"newValue"}, //NOI18N
477
new Object JavaDoc [] {DOC_REFERENCE_SETTER_PARAM}, new String JavaDoc [] {"get" + refName} //NOI18N
478
);
479                 interfaceMethod("void", "set" + refName, new String JavaDoc[] {refType, "newValue"}, null); //NOI18N
480
}
481         } else if (ref.getMultiplicity().getUpper() != 0) {
482             // getter
483
boolean isOrdered = ref.getMultiplicity().isOrdered();
484             methodJavaDoc (
485                 ref, true, DOC_REFERENCE_GETTER,
486                 isOrdered ? DOC_REFERENCE_GETTER_RETURN_ORDERED : DOC_REFERENCE_GETTER_RETURN_MULTI,
487                 null, null, new String JavaDoc[] {refType}
488             );
489             interfaceMethod(getTypeName(ref, GENERIC_STYLE_FAKE), "get" + refName, null, null); //NOI18N
490
}
491     }
492
493     // generates interfaces for a given class (class interface and class proxy interface)
494
protected void classProxyTemplate(javax.jmi.model.MofClass objClass) throws IOException JavaDoc {
495         final ClassContents contents = getClassContents(objClass);
496         interfaceHeader(tagProvider.getTypePrefix(objClass), tagProvider.getSubstName(objClass) + CLASS_POSTFIX, new String JavaDoc[] {"javax.jmi.reflect.RefClass"}, objClass, DOC_CLASS_PROXY); //NOI18N
497

498         if (!objClass.isAbstract()) {
499             // create (default)
500
methodJavaDoc (
501                 objClass, false, DOC_CLASS_PROXY_CREATE,
502                 DOC_CLASS_PROXY_CREATE_RETURN, null, null, null
503             );
504             interfaceMethod(tagProvider.getSubstName(objClass), "create" + tagProvider.getSubstName(objClass), null, null); //NOI18N
505

506             // create
507
if (contents.allAttributes.size() > 0) {
508                 Object JavaDoc [] params = contents.allAttributes.toArray();
509                 Object JavaDoc [] paramsObjects = contents.allAttributesObjects.toArray();
510                 String JavaDoc [] paramsNames = new String JavaDoc [paramsObjects.length];
511                 for (int x = 0; x < paramsNames.length; x++) {
512                     paramsNames [x] = ((ModelElement) paramsObjects [x]).getName ();
513                 }
514                 String JavaDoc name = tagProvider.getSubstName(objClass);
515                 methodJavaDoc (
516                     objClass, false, DOC_CLASS_PROXY_CREATE2, DOC_CLASS_PROXY_CREATE_RETURN,
517                     paramsNames, paramsObjects, null
518                 );
519                 // XXX note element type in @param for Javadoc of create* methods: e.g. in javamodel, see TypeParameterClass.createTypeParameter
520
interfaceMethod(tagProvider.getSubstName(objClass), "create" + name, params, null); //NOI18N
521
}
522         }
523
524         // generate operations
525
for (Iterator it = contents.clsOperations.iterator(); it.hasNext();)
526             operationTemplate(it.next());
527
528         // generate attributes
529
for (Iterator it = contents.clsAttributes.iterator(); it.hasNext();)
530             attributeTemplate(it.next());
531
532         // generate structure factory methods
533
for (Iterator it = contents.structures.iterator(); it.hasNext();) {
534             structTemplate(it.next());
535         }
536
537         interfaceFooter(tagProvider.getSubstName(objClass) + CLASS_POSTFIX);
538     }
539     
540     protected void classInstanceTemplate(MofClass objClass) throws IOException JavaDoc {
541         final ClassContents contents = getClassContents(objClass);
542
543         // *** Instance interface generation ***************************************************************************************
544
final Collection ancestors = new ArrayList();
545         final Collection supertypes = objClass.getSupertypes();
546
547         for (Iterator it = supertypes.iterator(); it.hasNext();) {
548             ancestors.add(tagProvider.getTypeFullName((ModelElement) it.next()));
549         }
550         if (ancestors.size() == 0) ancestors.add("javax.jmi.reflect.RefObject"); //NOI18N
551

552         interfaceHeader(tagProvider.getTypePrefix(objClass), tagProvider.getSubstName(objClass), ancestors.toArray(), objClass, DOC_INSTANCE);
553
554         // generate constants
555
for (Iterator it = contents.constants.iterator(); it.hasNext();)
556             constantTemplate(it.next());
557
558         // generate operations
559
for (Iterator it = contents.instOperations.iterator(); it.hasNext();)
560             operationTemplate(it.next());
561
562         // generate attributes
563
for (Iterator it = contents.instAttributes.iterator(); it.hasNext();)
564             attributeTemplate(it.next());
565
566         // generate references
567
for (Iterator it = contents.instReferences.iterator(); it.hasNext();)
568             referenceTemplate(it.next());
569
570         interfaceFooter(tagProvider.getSubstName(objClass));
571     }
572
573     // GenericMapper will nicely generate the class proxy interface right
574
// before/after the class instance interface, so we "remember" the last
575
// class accessed as an optimization. But, even if GenericMapper didn't
576
// do call classInstanceTemplate() and classProxyTemplate() successively,
577
// this will still do the right thing.
578
private ClassContents getClassContents(MofClass cls) {
579         if (cachedClassContents == null || cachedClassContents.objClass != cls)
580             cachedClassContents = new ClassContents(cls);
581         return cachedClassContents;
582     }
583     private ClassContents cachedClassContents;
584         
585     private final class ClassContents {
586         final Collection instAttributes = new ArrayList();
587         final Collection instOperations = new ArrayList();
588         final Collection instReferences = new ArrayList();
589         final Collection clsAttributes = new ArrayList();
590         final Collection clsOperations = new ArrayList();
591         final Collection allAttributes = new ArrayList();
592         final Collection allAttributesObjects = new ArrayList ();
593         final Collection constants = new ArrayList();
594         final Collection enumerations = new ArrayList();
595         final Collection structures = new ArrayList();
596         final MofClass objClass;
597
598         private ClassContents(MofClass objClass) {
599             this.objClass = objClass;
600             final Collection elements = objClass.getContents();
601
602             ModelElement element;
603             Feature feature;
604
605             for (Iterator it = elements.iterator(); it.hasNext();) {
606                 element = (ModelElement) it.next();
607
608                 if (element instanceof Constant) {
609                     constants.add(element);
610                 } else if (element instanceof Feature) {
611                     feature = (Feature) element;
612                     if (feature.getVisibility().equals(VisibilityKindEnum.PUBLIC_VIS)) {
613                         if (feature instanceof Attribute) {
614                             if (feature.getScope().equals(ScopeKindEnum.INSTANCE_LEVEL))
615                                 instAttributes.add(feature);
616                         } else if (feature instanceof Operation) {
617                             if (feature.getScope().equals(ScopeKindEnum.INSTANCE_LEVEL))
618                                 instOperations.add(feature);
619                         } else if (feature instanceof Reference) {
620                             instReferences.add(feature);
621                         }
622                     }
623                 } else if (element instanceof EnumerationType) {
624                     enumerations.add(element);
625                 } else if (element instanceof StructureType) {
626                     structures.add(element);
627                 }
628             }
629
630             for (Iterator it = new ContainsIterator(objClass); it.hasNext();) {
631                 if ((element = (ModelElement) it.next()) instanceof Attribute) {
632                     feature = (Attribute) element;
633                     if (feature.getScope().equals(ScopeKindEnum.CLASSIFIER_LEVEL)) {
634                         clsAttributes.add(feature);
635                     } else {
636                         if (!((Attribute) feature).isDerived()) {
637                             allAttributes.add(getTypeName((Attribute) feature, GENERIC_STYLE_FAKE));
638                             allAttributes.add(tagProvider.getSubstName(feature));
639                             allAttributesObjects.add(feature);
640                         }
641                     }
642                 } else if (element instanceof Operation) {
643                     feature = (Operation) element;
644                     if (feature.getScope().equals(ScopeKindEnum.CLASSIFIER_LEVEL)) {
645                         clsOperations.add(feature);
646                     }
647                 }
648             }
649         }
650     }
651     
652     // generates interface for a given association
653
protected void associationTemplate(Association objAssociation) throws IOException JavaDoc {
654         Collection contents = objAssociation.getContents();
655         AssociationEnd[] ends = new AssociationEnd[2];
656         Object JavaDoc element;
657         int i = 0;
658         boolean single, ordered;
659
660         for (Iterator it = contents.iterator(); it.hasNext() && i < 2;) {
661             element = it.next();
662             if (element instanceof AssociationEnd)
663                 ends[i++] = (AssociationEnd) element;
664         }
665
666         String JavaDoc end1Name = tagProvider.getSubstName(ends[0]);
667         String JavaDoc end1Class = getTypeName(getAttrType(ends[0]));
668         String JavaDoc end2Name = tagProvider.getSubstName(ends[1]);
669         String JavaDoc end2Class = getTypeName(getAttrType(ends[1]));
670         
671         interfaceHeader(tagProvider.getTypePrefix(objAssociation), tagProvider.getSubstName(objAssociation), new String JavaDoc[] {"javax.jmi.reflect.RefAssociation"}, objAssociation, DOC_ASSOC_PROXY); //NOI18N
672

673         // exists(<associationEnd1>, <associationEnd2>)
674
methodJavaDoc (
675             objAssociation, false, DOC_ASSOC_EXISTS, DOC_ASSOC_EXISTS_RETURN,
676             new String JavaDoc [] {end1Name, end2Name}, new Object JavaDoc [] {DOC_ASSOC_EXISTS_PARAM1, DOC_ASSOC_EXISTS_PARAM2}, null
677         );
678         interfaceMethod("boolean", "exists", new String JavaDoc[] {end1Class, end1Name, end2Class, end2Name}, null); //NOI18N
679

680         // <associationEnd1>(<associationEnd2>)
681
if (ends[0].isNavigable()) {
682             single = ends[0].getMultiplicity().getUpper() == 1;
683             ordered = ends[0].getMultiplicity().isOrdered();
684             methodJavaDoc (
685                 objAssociation, false,
686                 single ? DOC_ASSOC_GET_END1_SINGLE : (ordered ? DOC_ASSOC_GET_END1_ORDERED : DOC_ASSOC_GET_END1_MULTI),
687                 single ? DOC_ASSOC_GET_END1_RETURN_SINGLE : (ordered ? DOC_ASSOC_GET_END1_RETURN_ORDERED : DOC_ASSOC_GET_END1_RETURN_MULTI),
688                 new String JavaDoc [] {end2Name}, new Object JavaDoc [] {DOC_ASSOC_GET_END2_PARAM}, null
689             );
690             // XXX genericize:
691
interfaceMethod(single ? end1Class : (ordered ? DT_ORDERED : DT_MULTIVALUED),
692                 "get" + firstUpper(end1Name), new String JavaDoc[] {end2Class, end2Name}, null); //NOI18N
693
}
694
695         // <associationEnd2>(<associationEnd1>)
696
if (ends[1].isNavigable()) {
697             single = ends[1].getMultiplicity().getUpper() == 1;
698             ordered = ends[1].getMultiplicity().isOrdered();
699             methodJavaDoc (
700                 objAssociation, false,
701                 single ? DOC_ASSOC_GET_END1_SINGLE : (ordered ? DOC_ASSOC_GET_END1_ORDERED : DOC_ASSOC_GET_END1_MULTI),
702                 single ? DOC_ASSOC_GET_END1_RETURN_SINGLE : (ordered ? DOC_ASSOC_GET_END1_RETURN_ORDERED : DOC_ASSOC_GET_END1_RETURN_MULTI),
703                 new String JavaDoc [] {end1Name}, new Object JavaDoc [] {DOC_ASSOC_GET_END1_PARAM}, null
704             );
705             // XXX genericize:
706
interfaceMethod(single ? end2Class : (ordered ? DT_ORDERED : DT_MULTIVALUED),
707                 "get" + firstUpper(end2Name), new String JavaDoc[] {end1Class, end1Name}, null); //NOI18N
708
}
709
710         if (ends[0].isChangeable() && ends[1].isChangeable()) {
711             String JavaDoc [] names = new String JavaDoc [] {end1Name, end2Name};
712             Object JavaDoc [] params = new Object JavaDoc [] {DOC_ASSOC_EXISTS_PARAM1, DOC_ASSOC_EXISTS_PARAM2};
713
714             // add(<associationEnd1>, <associationEnd2>)
715
methodJavaDoc (
716                 objAssociation, false, DOC_ASSOC_ADD, null,
717                 names, params, null
718             );
719             interfaceMethod("boolean", "add", new String JavaDoc[] {end1Class, end1Name, end2Class, end2Name}, null); //NOI18N
720

721             // remove(<associationEnd1>, <associationEnd2>)
722
methodJavaDoc (
723                 objAssociation, false, DOC_ASSOC_REMOVE, null,
724                 names, params, null
725             );
726             interfaceMethod("boolean", "remove", new String JavaDoc[] {end1Class, end1Name, end2Class, end2Name}, null); //NOI18N
727
}
728
729         interfaceFooter(tagProvider.getSubstName(objAssociation));
730     }
731
732     // generates interface for a given package
733
protected void packageTemplate(MofPackage objPackage) throws IOException JavaDoc {
734         Collection elements;
735         ModelElement element;
736         Collection ancestors = new ArrayList();
737         Collection supertypes = objPackage.getSupertypes();
738         for (Iterator it = supertypes.iterator(); it.hasNext();) {
739             ancestors.add(tagProvider.getTypeFullName((ModelElement) it.next()) + PACKAGE_POSTFIX);
740         }
741         if (ancestors.size() == 0) ancestors.add("javax.jmi.reflect.RefPackage"); //NOI18N
742
interfaceHeader(tagProvider.getTypePrefix(objPackage), tagProvider.getSubstName(objPackage) + PACKAGE_POSTFIX, ancestors.toArray(), objPackage, DOC_PACKAGE);
743
744         ArrayList nestedPackages = new ArrayList();
745         ArrayList classes = new ArrayList();
746         ArrayList associations = new ArrayList();
747         ArrayList structureTypes = new ArrayList();
748         
749         elements = objPackage.getContents();
750         for (Iterator it = elements.iterator(); it.hasNext();) {
751             element = (ModelElement) it.next();
752             if (element instanceof Association) {
753                 associations.add(element);
754             } else if (element instanceof javax.jmi.model.MofClass) {
755                 classes.add(element);
756             } else if (element instanceof MofPackage) {
757                 nestedPackages.add(element);
758             } else if (element instanceof StructureType) {
759                 structureTypes.add(element);
760             } else if (element instanceof Import) {
761                 // addProxyGetter cannot handle Imports, and Imports come first
762
// in the mapping, so go ahead and just generate the necessary
763
// method now.
764
Import imp = (Import) element;
765                 if (imp.isClustered() && VisibilityKindEnum.PUBLIC_VIS.equals(imp.getVisibility())) {
766                     Namespace ns = imp.getImportedNamespace();
767                     if (ns instanceof MofPackage &&
768                             VisibilityKindEnum.PUBLIC_VIS.equals(((MofPackage) ns).getVisibility())) {
769                         String JavaDoc typeName = tagProvider.getTypeFullName(ns) + PACKAGE_POSTFIX;
770                         String JavaDoc elementName = tagProvider.getSubstName(element);
771                         interfaceMethod(typeName, "get" + elementName, null, null); //NOI18N
772
}
773                 } else {
774                     Logger.getDefault().log("import: " + imp.getName() + " mofid: " + imp.refMofId() + " clustered: " + imp.isClustered() + " visibility: " + imp.getVisibility()); //NOI18N
775
}
776             }
777         }
778
779         addProxyGetter(objPackage, nestedPackages, PACKAGE_POSTFIX);
780         addProxyGetter(objPackage, classes, CLASS_POSTFIX);
781         addProxyGetter(objPackage, associations, ""); //NOI18N
782

783         for (Iterator i = structureTypes.iterator(); i.hasNext(); ) {
784             structTemplate(i.next());
785         }
786         
787         interfaceFooter(tagProvider.getSubstName(objPackage) + PACKAGE_POSTFIX);
788     }
789
790     void addProxyGetter(MofPackage objPackage, ArrayList list, String JavaDoc suffix) throws IOException JavaDoc {
791         for (Iterator i = list.iterator(); i.hasNext(); ) {
792             GeneralizableElement element = (GeneralizableElement) i.next();
793             if (VisibilityKindEnum.PUBLIC_VIS.equals(element.getVisibility())) {
794                 String JavaDoc methodComment = null, returnComment = null;
795                 if (element instanceof Import) {
796                     methodComment = DOC_PACKAGE_GET_IMPORT;
797                     returnComment = DOC_PACKAGE_GET_IMPORT_RETURN;
798                 } else if (element instanceof MofPackage) {
799                     methodComment = DOC_PACKAGE_GET_NESTED;
800                     returnComment = DOC_PACKAGE_GET_NESTED_RETURN;
801                 } else if (element instanceof MofClass) {
802                     methodComment = DOC_PACKAGE_GET_CLASS;
803                     returnComment = DOC_PACKAGE_GET_CLASS_RETURN;
804                 } else if (element instanceof Association) {
805                     methodComment = DOC_PACKAGE_GET_ASSOC;
806                     returnComment = DOC_PACKAGE_GET_ASSOC_RETURN;
807                 }
808                 String JavaDoc typeName = tagProvider.getTypeFullName(element);
809                 String JavaDoc elementName = tagProvider.getSubstName(element);
810                 if (methodComment != null)
811                     methodJavaDoc(objPackage, false, methodComment, returnComment, null, null, new String JavaDoc [] {elementName});
812                 interfaceMethod(typeName + suffix, "get" + elementName, null, null); //NOI18N
813
}
814         }
815     }
816     
817
818     // generates class for an exception
819
protected void exceptionTemplate(MofException objException) throws IOException JavaDoc {
820         Collection contents = objException.getContents();
821         ArrayList params = new ArrayList();
822         ArrayList paramsObjects = new ArrayList();
823         ArrayList paramsNames = new ArrayList();
824         ArrayList codeConstr = new ArrayList();
825         StringBuffer JavaDoc paramsConstr = new StringBuffer JavaDoc(100);
826         StringBuffer JavaDoc codeMsg = new StringBuffer JavaDoc(100);
827         
828         Object JavaDoc element;
829         Parameter param;
830         String JavaDoc typeName;
831         String JavaDoc paramName;
832         String JavaDoc getterName;
833
834         for (Iterator it = contents.iterator(); it.hasNext();) {
835             element = it.next();
836             if (element instanceof Parameter) {
837                 param = (Parameter) element;
838                 paramsObjects.add (param);
839                 params.add(getTypeName(param, GENERIC_STYLE_FAKE));
840                 paramName = firstLower(tagProvider.getSubstName(param));
841                 paramsNames.add (paramName);
842                 params.add(removeUnderscores(paramName));
843                 getterName = paramName;
844                 if (param.getType() instanceof PrimitiveType && param.getType().getName().equals("Boolean")) { //NOI18N
845
if (getterName.indexOf("is") != 0) { //NOI18N
846
getterName = "is_" + getterName; //NOI18N
847
}
848                 } else {
849                     getterName = "get_" + getterName; //NOI18N
850
}
851                 params.add(removeUnderscores(getterName));
852             }
853         }
854
855         String JavaDoc exceptionName = tagProvider.getSubstName(objException);
856         
857         classHeader(tagProvider.getTypePrefix(objException), exceptionName, new Object JavaDoc[] {DT_EXCEPTION}, null, false, objException, DOC_EXCEPTION);
858
859         for (Iterator it = params.iterator(); it.hasNext(); it.next()) {
860             typeName = (String JavaDoc) it.next();
861             paramName = (String JavaDoc) it.next();
862             generate("private final " + typeName + " " + paramName + ";"); //NOI18N
863
codeConstr.add("this." + paramName + " = " + paramName + ";"); //NOI18N
864
paramsConstr.append(", " + typeName + " " + paramName); //NOI18N
865
getterName = paramName + ": \" + " + paramName; //NOI18N
866
if (codeMsg.length() == 0) {
867                 codeMsg.append("\"" + getterName); //NOI18N
868
} else {
869                 codeMsg.append(" + \", " + getterName); //NOI18N
870
}
871         }
872         
873         // constructor
874
methodJavaDoc (
875             objException, false, DOC_EXCEPTION_CONSTRUCTOR, null,
876             (String JavaDoc []) paramsNames.toArray (new String JavaDoc [] {}), paramsObjects.toArray (), null
877         );
878         generate("public " + exceptionName + "(" + (paramsConstr.length() == 0 ? "" : paramsConstr.toString().substring(2)) + ") {"); //NOI18N
879
indent();
880         generate("super(" + codeMsg.toString() + ");"); //NOI18N
881
for (Iterator it = codeConstr.iterator(); it.hasNext();) {
882             generate((String JavaDoc) it.next());
883         }
884         unindent();
885         generate("}"); //NOI18N
886

887         // getters for exception parameters
888
for (Iterator it = params.iterator(); it.hasNext();) {
889             typeName = (String JavaDoc) it.next();
890             paramName = (String JavaDoc) it.next();
891             getterName = (String JavaDoc) it.next();
892             methodJavaDoc (
893                 objException, false, DOC_EXCEPTION_GETTER, DOC_EXCEPTION_GETTER_RETURN,
894                 null, null, new String JavaDoc [] {paramName}
895             );
896             generate("public " + typeName + " " + getterName + "() {"); //NOI18N
897
indent();
898             generate("return " + paramName + ";"); //NOI18N
899
unindent();
900             generate("}"); //NOI18N
901
}
902
903         classFooter(exceptionName, false);
904     }
905     
906     protected void enumerationInterfaceTemplate(EnumerationType objEnumeration) throws IOException JavaDoc {
907         // generate interface for EnumerationType
908
String JavaDoc packageName = tagProvider.getTypePrefix(objEnumeration);
909         String JavaDoc ifcName = tagProvider.getSubstName(objEnumeration);
910         
911         interfaceHeader(packageName, ifcName, new Object JavaDoc[] {"javax.jmi.reflect.RefEnum"}, objEnumeration, DOC_ENUM_INTERFACE); //NOI18N
912
interfaceFooter(tagProvider.getSubstName(objEnumeration));
913     }
914     
915     protected void enumerationClassTemplate(EnumerationType objEnumeration) throws IOException JavaDoc {
916         String JavaDoc packageName = tagProvider.getTypePrefix(objEnumeration);
917         String JavaDoc ifcName = tagProvider.getSubstName(objEnumeration);
918         String JavaDoc clsName = ifcName + ENUM_POSTFIX;
919
920         List literals = objEnumeration.getLabels();
921         String JavaDoc literal;
922             
923         classHeader(packageName, clsName, new Object JavaDoc[0], new Object JavaDoc[] {ifcName}, false, true, objEnumeration, DOC_ENUM_CLASS);
924             
925         // public fields (literals)
926
for (Iterator it = literals.iterator(); it.hasNext();) {
927             literal = (String JavaDoc) it.next();
928             methodJavaDoc (objEnumeration, false, DOC_ENUM_LITERAL, null, null, null, new String JavaDoc [] {literal});
929             generate("public static final " + clsName + " " + tagProvider.mapEnumLiteral(literal) + " = new " + clsName + "(\"" + literal + "\");"); //NOI18N
930
}
931         newLine();
932             
933         // private fields
934
generate("private static final java.util.List typeName;"); //NOI18N
935
generate("private final java.lang.String literalName;"); //NOI18N
936
newLine();
937            
938         // static initializer
939
generate("static {"); //NOI18N
940
indent();
941         generate("java.util.ArrayList temp = new java.util.ArrayList();"); //NOI18N
942

943         String JavaDoc enumFQN = ""; //NOI18N
944
for (Iterator it = objEnumeration.getQualifiedName().iterator(); it.hasNext();) {
945             String JavaDoc fqnElement = (String JavaDoc) it.next();
946             generate("temp.add(\"" + fqnElement + "\");"); //NOI18N
947
enumFQN += fqnElement + (it.hasNext() ? "." : ""); //NOI18N
948
}
949         
950         generate("typeName = java.util.Collections.unmodifiableList(temp);"); //NOI18N
951
unindent();
952         generate("}"); //NOI18N
953
newLine();
954             
955         // constructor
956
generate("private " + clsName + "(java.lang.String literalName) {"); //NOI18N
957
indent();
958         generate("this.literalName = literalName;"); //NOI18N
959
unindent();
960         generate("}"); //NOI18N
961
newLine();
962           
963         // refTypeName
964
methodJavaDoc (
965             objEnumeration, false, DOC_ENUM_REFTYPENAME, DOC_ENUM_REFTYPENAME_RETURN,
966             null, null, null
967         );
968         // XXX genericize
969
generate("public java.util.List refTypeName() {"); //NOI18N
970
indent();
971         generate("return typeName;"); //NOI18N
972
unindent();
973         generate("}"); //NOI18N
974
newLine();
975             
976         // toString
977
methodJavaDoc (
978             objEnumeration, false, DOC_ENUM_TOSTRING, DOC_ENUM_TOSTRING_RETURN,
979             null, null, null
980         );
981         generate("public java.lang.String toString() {"); //NOI18N
982
indent();
983         generate("return literalName;"); //NOI18N
984
unindent();
985         generate("}"); //NOI18N
986
newLine();
987             
988         // hashCode
989
methodJavaDoc (
990             objEnumeration, false, DOC_ENUM_HASHCODE, DOC_ENUM_HASHCODE_RETURN,
991             null, null, null
992         );
993         generate("public int hashCode() {"); //NOI18N
994
indent();
995         generate("return literalName.hashCode();"); //NOI18N
996
unindent();
997         generate("}"); //NOI18N
998
newLine();
999             
1000        // equals
1001
methodJavaDoc (
1002            objEnumeration, false, DOC_ENUM_EQUALS, DOC_ENUM_EQUALS_RETURN,
1003            new String JavaDoc [] {"o"}, new Object JavaDoc [] {DOC_ENUM_EQUALS_PARAM}, null //NOI18N
1004
);
1005        generate("public boolean equals(java.lang.Object o) {"); //NOI18N
1006
indent();
1007        generate("if (o instanceof " + clsName + ") return (o == this);"); //NOI18N
1008
generate("else if (o instanceof " + ifcName + ") return (o.toString().equals(literalName));"); //NOI18N
1009
generate("else return ((o instanceof javax.jmi.reflect.RefEnum) && ((javax.jmi.reflect.RefEnum) o).refTypeName().equals(typeName) && o.toString().equals(literalName));"); //NOI18N
1010
unindent();
1011        generate("}"); //NOI18N
1012
newLine();
1013        
1014        // forName
1015
methodJavaDoc (
1016            objEnumeration, false, DOC_ENUM_FORNAME, DOC_ENUM_FORNAME_RETURN,
1017            new String JavaDoc [] {"name"}, new Object JavaDoc [] {DOC_ENUM_FORNAME_PARAM}, null //NOI18N
1018
);
1019        generate("public static " + ifcName + " forName(java.lang.String name) {"); //NOI18N
1020
indent();
1021        for (Iterator it = literals.iterator(); it.hasNext();) {
1022            literal = (String JavaDoc) it.next();
1023                    generate("if (name.equals(\"" + literal + "\")) return " + tagProvider.mapEnumLiteral(literal) + ";"); //NOI18N
1024
}
1025        generate("throw new java.lang.IllegalArgumentException(\"Unknown literal name '\" + name + \"' for enumeration '" + enumFQN + "'\");"); //NOI18N
1026
unindent();
1027        generate("}"); //NOI18N
1028

1029        // readResolve
1030
methodJavaDoc (
1031            objEnumeration, false, DOC_ENUM_READRESOLVE, DOC_ENUM_READRESOLVE_RETURN,
1032            null, null, null
1033        );
1034        generate("protected java.lang.Object readResolve() throws java.io.ObjectStreamException {"); //NOI18N
1035
indent();
1036            generate("try {"); //NOI18N
1037
indent();
1038                generate("return forName(literalName);"); //NOI18N
1039
unindent();
1040            generate("} catch (java.lang.IllegalArgumentException e) {"); //NOI18N
1041
indent();
1042                generate("throw new java.io.InvalidObjectException(e.getMessage());"); //NOI18N
1043
unindent();
1044            generate("}"); //NOI18N
1045
unindent();
1046        generate("}"); //NOI18N
1047

1048        classFooter(ifcName, false);
1049    }
1050    
1051    protected void structureTemplate(StructureType objStructure) throws IOException JavaDoc {
1052        String JavaDoc memberName, fieldName;
1053
1054        // generate interface for StructuredType
1055
interfaceHeader(tagProvider.getTypePrefix(objStructure), tagProvider.getSubstName(objStructure), new Object JavaDoc[] {"javax.jmi.reflect.RefStruct"}, objStructure, DOC_STRUCT); //NOI18N
1056

1057        List fields = objStructure.getContents();
1058        ModelElement field;
1059        Classifier fieldType;
1060            
1061        // generate getters for structure fields
1062
for (Iterator it = fields.iterator(); it.hasNext();) {
1063            field = (ModelElement) it.next();
1064            if (field instanceof StructureField) {
1065                fieldType = ((StructureField) field).getType();
1066                memberName = firstUpper (tagProvider.getSubstName(field));
1067                fieldName = memberName;
1068                if (fieldType instanceof PrimitiveType && fieldType.getName().equals("Boolean")) { //NOI18N
1069
if (memberName.indexOf("Is") != 0) { //NOI18N
1070
memberName = "is" + memberName; //NOI18N
1071
} else {
1072                        memberName = firstLower(memberName);
1073                    }
1074                } else {
1075                    memberName = "get" + memberName; //NOI18N
1076
}
1077                methodJavaDoc (
1078                    objStructure, false, DOC_STRUCT_GETTER, DOC_STRUCT_GETTER_RETURN,
1079                    null, null, new String JavaDoc [] {fieldName}
1080                );
1081                interfaceMethod(getPrimitiveName(getTypeName(fieldType)), memberName, null, null);
1082            }
1083        }
1084        interfaceFooter(tagProvider.getSubstName(objStructure));
1085    }
1086
1087    // generates factory methods for structured datatype
1088
void structTemplate(Object JavaDoc objStructure) throws IOException JavaDoc {
1089        DataType dataType = (DataType) objStructure;
1090        ArrayList parameters = new ArrayList();
1091        ArrayList structureFields = new ArrayList ();
1092        ArrayList paramNames = new ArrayList ();
1093        List fields = dataType.getContents();
1094        ModelElement field;
1095
1096        // generate getters for structure fields
1097
for (Iterator it = fields.iterator(); it.hasNext();) {
1098            field = (ModelElement) it.next();
1099            if (field instanceof StructureField) {
1100                parameters.add(getTypeName2((StructureField) field));
1101                String JavaDoc name = tagProvider.getSubstName(field);
1102                parameters.add(name);
1103                paramNames.add(name);
1104                structureFields.add(field);
1105            }
1106        }
1107
1108        String JavaDoc params[] = new String JavaDoc [parameters.size ()];
1109        params = (String JavaDoc []) parameters.toArray(params);
1110        
1111        int size = structureFields.size();
1112        Object JavaDoc [] structFields = new Object JavaDoc[size];
1113        String JavaDoc [] parNames = new String JavaDoc[size];
1114        structFields = structureFields.toArray(structFields);
1115        parNames = (String JavaDoc []) paramNames.toArray(parNames);
1116
1117        // generate factory method
1118
methodJavaDoc(
1119            dataType, false, DOC_STRUCT_CREATE, DOC_STRUCT_CREATE_RETURN,
1120            parNames, structFields, null
1121        );
1122        interfaceMethod(tagProvider.getTypeFullName(dataType), "create" + firstUpper(tagProvider.getSubstName(dataType)), params, null); //NOI18N
1123
}
1124
1125    // Java doc generation ------------------------------------------------------
1126

1127    private void classJavaDoc (ModelElement elem, String JavaDoc genericComment) throws IOException JavaDoc {
1128        generate ("/**"); //NOI18N
1129
if (genericComment != null) {
1130            javaDoc (MessageFormat.format (genericComment, new String JavaDoc [] {elem.getName ()}));
1131        }
1132        javaDoc (elem.getAnnotation ());
1133        javaDoc (" "); //NOI18N
1134
javaDoc (DOC_WARNING);
1135        generate (" */"); //NOI18N
1136
}
1137    
1138    private void fieldJavaDoc (ModelElement elem) throws IOException JavaDoc {
1139        generate ("/**"); //NOI18N
1140
javaDoc (elem.getAnnotation ());
1141        generate (" */"); //NOI18N
1142
}
1143        
1144    private void methodJavaDoc (ModelElement elem, boolean annotate, String JavaDoc genericComment,
1145        Object JavaDoc retValDescriptor, String JavaDoc [] args, Object JavaDoc [] argDescriptors, String JavaDoc [] variables)
1146        throws IOException JavaDoc {
1147
1148        String JavaDoc text;
1149        String JavaDoc [] vars = (variables == null) ? new String JavaDoc [1] : new String JavaDoc [variables.length + 1];
1150        vars [0] = elem.getName ();
1151        if (variables != null) {
1152            for (int x = 0; x < variables.length; x++)
1153                vars [x + 1] = variables [x];
1154        }
1155        
1156        generate ("/**"); //NOI18N
1157

1158        // generic comment
1159
if (genericComment != null) {
1160            javaDoc (MessageFormat.format (genericComment, vars));
1161        }
1162        
1163        // annotation based comment
1164
if (annotate) {
1165            javaDoc (elem.getAnnotation ());
1166        }
1167        
1168        // javadoc for arguments
1169
if (args != null) {
1170            for (int x = 0; x < args.length; x++) {
1171                if (argDescriptors [x] instanceof ModelElement) {
1172                    text = ((ModelElement) argDescriptors [x]).getAnnotation ();
1173                } else {
1174                    text = (String JavaDoc) argDescriptors [x];
1175                    if (text != null) {
1176                        text = MessageFormat.format (text, vars);
1177                    }
1178                }
1179                if (text != null) {
1180                    javaDoc ("@param " + args [x] + " " + text); //NOI18N
1181
}
1182            } // for
1183
} // if
1184

1185        // javadoc for return value
1186
if (retValDescriptor instanceof ModelElement) {
1187            text = elem.getAnnotation ();
1188        } else {
1189            text = (String JavaDoc) retValDescriptor;
1190            if (text != null)
1191                text = MessageFormat.format (text, vars);
1192        }
1193        if (text != null) {
1194            javaDoc ("@return " + text); //NOI18N
1195
}
1196        
1197        // javadoc for exceptions
1198

1199        generate (" */"); //NOI18N
1200
}
1201    
1202    private void javaDoc (String JavaDoc text) throws IOException JavaDoc {
1203        if (text == null)
1204            return;
1205        final int MAX_LINE_LENGTH = 70;
1206        
1207        BufferedReader JavaDoc reader = new BufferedReader JavaDoc (new StringReader JavaDoc (text));
1208        String JavaDoc line = reader.readLine ();
1209        while (line != null) {
1210            int length = line.length ();
1211            int pos = 0, pos2;
1212            String JavaDoc s;
1213            while (pos < length) {
1214                if (length - pos <= MAX_LINE_LENGTH) {
1215                    s = line.substring (pos);
1216                    pos = length;
1217                } else {
1218                    pos2 = pos + MAX_LINE_LENGTH;
1219                    // find end of a word
1220
while ((pos2 < length) && (!Character.isWhitespace (text.charAt (pos2)))) {
1221                        pos2++;
1222                    } // while
1223
// find start of next word
1224
while ((pos2 < length) && (Character.isWhitespace (text.charAt (pos2)))) {
1225                        pos2++;
1226                    } // while
1227
s = line.substring (pos, pos2);
1228                    pos = pos2;
1229                }
1230                generate (" * " + s); //NOI18N
1231
} // while
1232
line = reader.readLine ();
1233        } // while
1234
}
1235    
1236    // public ---------------------------------------------------------------------------------------------------------------
1237

1238    /** <P>
1239     * Creates new JavaMapper. Each created mapping interface will be written into
1240     * separate file to the specified Filesystem into the specified path.
1241     * </P>
1242     * @param sf StreamFactory used to generate files/streams.
1243     */

1244    public JavaMapper(JMIStreamFactory sf, String JavaDoc header) {
1245        super();
1246        generator = sf;
1247        if ((header != null) && (header.trim().length() > 0)) {
1248            this.header = "/*\n"; //NOI18N
1249
StringTokenizer tokenizer = new StringTokenizer (header, "\n"); //NOI18N
1250
while (tokenizer.hasMoreTokens ())
1251                this.header += " * " + tokenizer.nextToken () + "\n"; //NOI18N
1252
this.header += " */"; //NOI18N
1253
}
1254    }
1255}
1256
Popular Tags