KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > j2ee > persistence > util > GenerationUtils


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.modules.j2ee.persistence.util;
21
22 import com.sun.source.tree.*;
23 import java.io.IOException JavaDoc;
24 import java.util.Collections JavaDoc;
25 import java.util.EnumSet JavaDoc;
26 import java.util.Iterator JavaDoc;
27 import java.util.List JavaDoc;
28 import java.util.Set JavaDoc;
29 import javax.lang.model.element.*;
30 import javax.lang.model.type.*;
31 import org.netbeans.api.java.source.JavaSource.Phase;
32 import org.netbeans.api.java.source.TreeMaker;
33 import org.netbeans.api.java.source.WorkingCopy;
34 import org.openide.filesystems.FileObject;
35 import org.openide.filesystems.FileSystem;
36 import org.openide.filesystems.Repository;
37 import org.openide.loaders.DataFolder;
38 import org.openide.loaders.DataObject;
39 import org.openide.util.Parameters;
40
41 /**
42  * <b><i>This class is a temporary copy of the
43  * <code>org.netbeans.modules.j2ee.common.source.GenerationUtils</code>, will be
44  * removed when the equivalent functionality is provided by java/source, which
45  * should happen during M8</i></b>.
46  *
47  * @author Andrei Badea
48  */

49 public final class GenerationUtils extends SourceUtils {
50
51     // XXX this class both provides some state (getClassTree()) and
52
// method which could be static if they didn't need TreeMaker.
53
// GenerationUtils should only contain these "static" method and should not
54
// inherit from SourceUtils. Instead it should have just a newInstance(WorkingCopy)
55
// method and there should also be a SourceUtils.getGenerationUtils() method.
56

57     // TODO use CharSequence instead of String where possible
58

59     /**
60      * The templates for regular Java class and interface.
61      */

62     static final String JavaDoc CLASS_TEMPLATE = "Templates/Classes/Class.java"; // NOI18N
63
static final String JavaDoc INTERFACE_TEMPLATE = "Templates/Classes/Interface.java"; // NOI18N
64

65     // <editor-fold desc="Constructors and factory methods">
66

67     private GenerationUtils(WorkingCopy copy, TypeElement typeElement) {
68         super(copy, typeElement);
69     }
70
71     private GenerationUtils(WorkingCopy copy, ClassTree classTree) {
72         super(copy, classTree);
73     }
74
75     public static GenerationUtils newInstance(WorkingCopy copy, TypeElement typeElement) {
76         Parameters.notNull("copy", copy); // NOI18N
77
Parameters.notNull("typeElement", typeElement); // NOI18N
78

79         return new GenerationUtils(copy, typeElement);
80     }
81
82     public static GenerationUtils newInstance(WorkingCopy copy, ClassTree classTree) {
83         Parameters.notNull("copy", copy); // NOI18N
84
Parameters.notNull("classTree", classTree); // NOI18N
85

86         return new GenerationUtils(copy, classTree);
87     }
88
89     public static GenerationUtils newInstance(WorkingCopy copy) throws IOException JavaDoc {
90         Parameters.notNull("copy", copy); // NOI18N
91

92         ClassTree classTree = findPublicTopLevelClass(copy);
93         if (classTree != null) {
94             return newInstance(copy, classTree);
95         }
96         return null;
97     }
98
99     // </editor-fold>
100

101     // <editor-fold desc="Public static methods">
102

103     /**
104      * Creates a new Java class based on the default template for classes.
105      *
106      * @param targetFolder the folder the new class should be created in;
107      * cannot be null.
108      * @param targetName the name of the new class (a valid Java identifier);
109      * cannot be null.
110      * @param javadoc the new class's Javadoc; can be null.
111      * @return the FileObject for the new Java class; never null.
112      */

113     public static FileObject createClass(FileObject targetFolder, String JavaDoc className, final String JavaDoc javadoc) throws IOException JavaDoc{
114         return createClass(CLASS_TEMPLATE, targetFolder, className, javadoc);
115     }
116
117     /**
118      * Creates a new Java class based on the default template for interfaces.
119      *
120      * @param targetFolder the folder the new interface should be created in;
121      * cannot be null.
122      * @param interfaceName the name of the new interface (a valid Java identifier);
123      * cannot be null.
124      * @param javadoc the new interface's Javadoc; can be null.
125      * @return the FileObject for the new Java interface; never null.
126      */

127     public static FileObject createInterface(FileObject targetFolder, String JavaDoc interfaceName, final String JavaDoc javadoc) throws IOException JavaDoc{
128         return createClass(INTERFACE_TEMPLATE, targetFolder, interfaceName, javadoc);
129     }
130
131     /**
132      * Creates a new Java class based on the provided template.
133      *
134      * @param targetFolder the folder the new class should be created in;
135      * cannot be null.
136      * @param targetName the name of the new interface (a valid Java identifier);
137      * cannot be null.
138      * @return the FileObject for the new Java class; never null.
139      */

140     public static FileObject createClass(String JavaDoc template, FileObject targetFolder, String JavaDoc className, final String JavaDoc javadoc) throws IOException JavaDoc {
141         Parameters.notNull("template", template); // NOI18N
142
Parameters.notNull("targetFolder", targetFolder); // NOI18N
143
Parameters.javaIdentifier("className", className); // NOI18N
144

145         FileObject classFO = createDataObjectFromTemplate(template, targetFolder, className).getPrimaryFile();
146         // JavaSource javaSource = JavaSource.forFileObject(classFO);
147
// final boolean[] commit = { false };
148
// ModificationResult modification = javaSource.runModificationTask(new AbstractTask<WorkingCopy>() {
149
// public void run(WorkingCopy copy) throws IOException {
150
// GenerationUtils genUtils = GenerationUtils.newInstance(copy);
151
// if (javadoc != null) {
152
// genUtils.setJavadoc(copy, mainType, javadoc);
153
// }
154
// }
155
// });
156
// if (commit[0]) {
157
// modification.commit();
158
// }
159

160         return classFO;
161     }
162
163     // </editor-fold>
164

165     // <editor-fold defaultstate="collapsed" desc="Non-public static methods">
166

167     /**
168      * Creates a data object from a given template path in the system
169      * file system.
170      *
171      * @return the <code>DataObject</code> of the newly created file.
172      * @throws IOException if an error occured while creating the file.
173      */

174     private static DataObject createDataObjectFromTemplate(String JavaDoc template, FileObject targetFolder, String JavaDoc targetName) throws IOException JavaDoc {
175         assert template != null;
176         assert targetFolder != null;
177         assert targetName != null && targetName.trim().length() > 0;
178
179         FileSystem defaultFS = Repository.getDefault().getDefaultFileSystem();
180         FileObject templateFO = defaultFS.findResource(template);
181         DataObject templateDO = DataObject.find(templateFO);
182         DataFolder dataFolder = DataFolder.findFolder(targetFolder);
183         return templateDO.createFromTemplate(dataFolder, targetName);
184     }
185
186     // </editor-fold>
187

188     // <editor-fold desc="Public methods">
189

190     public Tree createType(String JavaDoc typeName) {
191         TreeMaker make = getTreeMaker();
192         TypeKind primitiveTypeKind = null;
193         if ("boolean".equals(typeName)) { // NOI18N
194
primitiveTypeKind = TypeKind.BOOLEAN;
195         } else if ("byte".equals(typeName)) { // NOI18N
196
primitiveTypeKind = TypeKind.BYTE;
197         } else if ("short".equals(typeName)) { // NOI18N
198
primitiveTypeKind = TypeKind.SHORT;
199         } else if ("int".equals(typeName)) { // NOI18N
200
primitiveTypeKind = TypeKind.INT;
201         } else if ("long".equals(typeName)) { // NOI18N
202
primitiveTypeKind = TypeKind.LONG;
203         } else if ("char".equals(typeName)) { // NOI18N
204
primitiveTypeKind = TypeKind.CHAR;
205         } else if ("float".equals(typeName)) { // NOI18N
206
primitiveTypeKind = TypeKind.FLOAT;
207         } else if ("double".equals(typeName)) { // NOI18N
208
primitiveTypeKind = TypeKind.DOUBLE;
209         }
210         if (primitiveTypeKind != null) {
211             return getTreeMaker().PrimitiveType(primitiveTypeKind);
212         }
213         return createQualIdent(typeName);
214     }
215
216     public ModifiersTree createModifiers(Modifier modifier) {
217         return getTreeMaker().Modifiers(EnumSet.of(modifier), Collections.<AnnotationTree>emptyList());
218     }
219
220     /**
221      * Creates a new annotation.
222      *
223      * @param annotationType the fully-qualified name of the annotation type;
224      * cannot be null.
225      * @return the new annotation; never null.
226      */

227     public AnnotationTree createAnnotation(String JavaDoc annotationType) {
228         Parameters.notNull("annotationType", annotationType); // NOI18N
229

230         return createAnnotation(annotationType, Collections.<ExpressionTree>emptyList());
231     }
232
233     /**
234      * Creates a new annotation.
235      *
236      * @param annotationType the fully-qualified name of the annotation type;
237      * cannot be null.
238      * <code>java.lang.SuppressWarnings</code>; cannot be null.
239      * @param arguments the arguments of the new annotation; cannot be null.
240      * @return the new annotation; never null.
241      */

242     public AnnotationTree createAnnotation(String JavaDoc annotationType, List JavaDoc<? extends ExpressionTree> arguments) {
243         Parameters.notNull("annotationType", annotationType); // NOI18N
244
Parameters.notNull("arguments", arguments); // NOI18N
245

246         ExpressionTree annotationTypeTree = createQualIdent(annotationType);
247         return getTreeMaker().Annotation(annotationTypeTree, arguments);
248     }
249
250     /**
251      * Creates a new annotation argument whose value is a literal.
252      *
253      * @param argumentName the argument name; cannot be null.
254      * @param argumentValue the argument value; cannot be null. The semantics
255      * of this parameter is the same as of the parameters of
256      * {@link TreeMaker#Literal(Object)}.
257      * @return the new annotation argument; never null.
258      */

259     public ExpressionTree createAnnotationArgument(String JavaDoc argumentName, Object JavaDoc argumentValue) {
260         Parameters.javaIdentifierOrNull("argumentName", argumentName); // NOI18N
261
Parameters.notNull("argumentValue", argumentValue); // NOI18N
262

263         TreeMaker make = getTreeMaker();
264         ExpressionTree argumentValueTree = make.Literal(argumentValue);
265         if (argumentName == null) {
266             return argumentValueTree;
267         } else {
268             return make.Assignment(make.Identifier(argumentName), argumentValueTree);
269         }
270     }
271
272     /**
273      * Creates a new annotation argument whose value is an array.
274      *
275      * @param argumentName the argument name; cannot be null.
276      * @param argumentValue the argument value; cannot be null.
277      * @return the new annotation argument; never null.
278      */

279     public ExpressionTree createAnnotationArgument(String JavaDoc argumentName, List JavaDoc<? extends ExpressionTree> argumentValues) {
280         Parameters.javaIdentifierOrNull("argumentName", argumentName); // NOI18N
281
Parameters.notNull("argumentValues", argumentValues); // NOI18N
282

283         TreeMaker make = getTreeMaker();
284         ExpressionTree argumentValuesTree = make.NewArray(null, Collections.<ExpressionTree>emptyList(), argumentValues);
285         if (argumentName == null) {
286             return argumentValuesTree;
287         } else {
288             return make.Assignment(make.Identifier(argumentName), argumentValuesTree);
289         }
290     }
291
292     /**
293      * Creates a new annotation argument whose value is a member of a type. For
294      * example it can be used to generate <code>@Target(ElementType.CONSTRUCTOR)</code>.
295      *
296      * @param argumentName the argument name; cannot be null.
297      * @param argumentType the fully-qualified name of the type whose member is to be invoked
298      * (e.g. <code>java.lang.annotations.ElementType</code> in the previous
299      * example); cannot be null.
300      * @param argumentTypeField a field of <code>argumentType</code>
301      * (e.g. <code>CONSTRUCTOR</code> in the previous example);
302      * cannot be null.
303      * @return the new annotation argument; never null.
304      */

305     public ExpressionTree createAnnotationArgument(String JavaDoc argumentName, String JavaDoc argumentType, String JavaDoc argumentTypeField) {
306         Parameters.javaIdentifierOrNull("argumentName", argumentName); // NOI18N
307
Parameters.notNull("argumentType", argumentType); // NOI18N
308
Parameters.javaIdentifier("argumentTypeField", argumentTypeField); // NOI18N
309

310         TreeMaker make = getTreeMaker();
311         MemberSelectTree argumentValueTree = make.MemberSelect(createQualIdent(argumentType), argumentTypeField);
312         if (argumentName == null) {
313             return argumentValueTree;
314         } else {
315             return make.Assignment(make.Identifier(argumentName), argumentValueTree);
316         }
317     }
318
319     /**
320      * Ensures the given class has a public no-arg constructor.
321      *
322      * @param classTree the class to ensure the constructor for; cannot be null.
323      * @return a modified class if a no-arg constructor was added, the original
324      * class otherwise; never null.
325      */

326     public ClassTree ensureNoArgConstructor(ClassTree classTree) throws IOException JavaDoc {
327         getWorkingCopy().toPhase(Phase.RESOLVED);
328
329         ExecutableElement constructor = getNoArgConstructor();
330         MethodTree constructorTree = constructor != null ? getWorkingCopy().getTrees().getTree(constructor) : null;
331         MethodTree newConstructorTree = null;
332         TreeMaker make = getTreeMaker();
333         if (constructor != null) {
334             if (!constructor.getModifiers().contains(Modifier.PUBLIC)) {
335                 ModifiersTree oldModifiersTree = constructorTree.getModifiers();
336                 Set JavaDoc<Modifier> newModifiers = EnumSet.of(Modifier.PUBLIC);
337                 for (Modifier modifier : oldModifiersTree.getFlags()) {
338                     if (!Modifier.PROTECTED.equals(modifier) && !Modifier.PRIVATE.equals(modifier)) {
339                         newModifiers.add(modifier);
340                     }
341                 }
342                 newConstructorTree = make.Constructor(
343                     make.Modifiers(newModifiers),
344                     constructorTree.getTypeParameters(),
345                     constructorTree.getParameters(),
346                     constructorTree.getThrows(),
347                     constructorTree.getBody());
348             }
349         } else {
350             newConstructorTree = make.Constructor(
351                     createModifiers(Modifier.PUBLIC),
352                     Collections.<TypeParameterTree>emptyList(),
353                     Collections.<VariableTree>emptyList(),
354                     Collections.<ExpressionTree>emptyList(),
355                     "{ }"); // NOI18N
356
}
357         ClassTree newClassTree = classTree;
358         if (newConstructorTree != null) {
359             if (constructorTree != null) {
360                 newClassTree = make.removeClassMember(newClassTree, constructorTree);
361             }
362             newClassTree = make.addClassMember(newClassTree, newConstructorTree);
363         }
364         return newClassTree;
365     }
366
367     /**
368      * Creates a constructor which assigns its parameters to fields with the
369      * same names. For example it can be used to generate:
370      *
371      * <pre>
372      * public void Constructor(String field1, Object field2) {
373      * this.field1 = field1;
374      * this.field2 = field2;
375      * }
376      * </pre>
377      *
378      * @param modifier the constructor modifier.
379      * @param constructorName the constructor name; cannot be null.
380      * @param parameters the constructor parameters; cannot be null.
381      * @return the new constructor; never null.
382      */

383     public MethodTree createAssignmentConstructor(ModifiersTree modifiersTree, String JavaDoc constructorName, List JavaDoc<VariableTree> parameters) {
384         Parameters.notNull("modifiersTree", modifiersTree);
385         Parameters.javaIdentifier("constructorName", constructorName); // NOI18N
386
Parameters.notNull("parameters", parameters); // NOI18N
387

388         StringBuilder JavaDoc body = new StringBuilder JavaDoc(parameters.size() * 30);
389         body.append("{"); // NOI18N
390
for (VariableTree parameter : parameters) {
391             String JavaDoc parameterName = parameter.getName().toString();
392             body.append("this." + parameterName + " = " + parameterName + ";"); // NOI18N
393
}
394         body.append("}"); // NOI18N
395

396         TreeMaker make = getTreeMaker();
397         return make.Constructor(
398                 modifiersTree,
399                 Collections.<TypeParameterTree>emptyList(),
400                 parameters,
401                 Collections.<ExpressionTree>emptyList(),
402                 body.toString());
403     }
404
405     /**
406      * Creates a new field.
407      *
408      * @param modifiersTree the field modifiers; cannot be null.
409      * @param fieldType the fully-qualified name of the field type; cannot be null.
410      * @param fieldName the field name; cannot be null.
411      * @return the new field; never null.
412      */

413     public VariableTree createField(ModifiersTree modifiersTree, String JavaDoc fieldName, String JavaDoc fieldType) {
414         Parameters.notNull("modifiersTree", modifiersTree); // NOI18N
415
Parameters.javaIdentifier("fieldName", fieldName); // NOI18N
416
Parameters.notNull("fieldType", fieldType); // NOI18N
417

418         return getTreeMaker().Variable(
419                 modifiersTree,
420                 fieldName,
421                 createType(fieldType),
422                 null);
423     }
424
425     // MISSING createField(ModifiersTree, String, String, ExpressionTree)
426

427     /**
428      * Creates a new variable (a <code>VariableTree</code> with no
429      * modifiers nor initializer).
430      *
431      * @param variableType the fully-qualified name of the variable type; cannot be null.
432      * @param variableName the variable name; cannot be null.
433      * @return the new variable; never null.
434      */

435     public VariableTree createVariable(String JavaDoc variableName, String JavaDoc variableType) {
436         Parameters.javaIdentifier("variableName", variableName); // NOI18N
437
Parameters.notNull("variableType", variableType); // NOI18N
438

439         return createField(
440                 createEmptyModifiers(),
441                 variableName,
442                 variableType);
443     }
444
445     /**
446      * Creates a new variable (a <code>VariableTree</code> with no
447      * modifiers nor initializer).
448      *
449      * @param variableType the variable type; cannot be null.
450      * @param variableName the variable name; cannot be null.
451      * @return the new variable; never null.
452      */

453     public VariableTree createVariable(String JavaDoc variableName, Tree variableType) {
454         Parameters.javaIdentifier("variableName", variableName); // NOI18N
455
Parameters.notNull("variableType", variableType); // NOI18N
456

457         return getTreeMaker().Variable(
458                 createEmptyModifiers(),
459                 variableName,
460                 variableType,
461                 null);
462     }
463
464     /**
465      * Removes any modifiers from the given <code>VariableTree</code>. This can be e.g.
466      * used to create a variable suitable for use as a method parameter.
467      *
468      * @param variableTree the <code>VariableTree</code> to remove the modifiers from.
469      * @return a <code>VariableTree</code> with the same properties but no modifiers.
470      */

471     public VariableTree removeModifiers(VariableTree variableTree) {
472         Parameters.notNull("variableTree", variableTree);
473
474         TreeMaker make = getTreeMaker();
475         return make.Variable(
476                 createEmptyModifiers(),
477                 variableTree.getName(),
478                 variableTree.getType(),
479                 variableTree.getInitializer());
480     }
481
482     /**
483      * Creates a new public property getter method.
484      *
485      * @param modifiersTree the method modifiers; cannot be null.
486      * @param propertyType the fully-qualified name of the property type; cannot be null.
487      * @param propertyName the property name; cannot be null.
488      * @return the new method; never null.
489      */

490     public MethodTree createPropertyGetterMethod(ModifiersTree modifiersTree, String JavaDoc propertyName, String JavaDoc propertyType) throws IOException JavaDoc {
491         Parameters.notNull("modifiersTree", modifiersTree); // NOI18N
492
Parameters.javaIdentifier("propertyName", propertyName); // NOI18N
493
Parameters.notNull("propertyType", propertyType); // NOI18N
494
getWorkingCopy().toPhase(Phase.RESOLVED);
495
496         return createPropertyGetterMethod(modifiersTree, propertyName, createType(propertyType));
497     }
498
499     /**
500      * Creates a new public property getter method.
501      *
502      * @param modifiersTree the method modifiers; cannot be null.
503      * @param propertyType the property type; cannot be null.
504      * @param propertyName the property name; cannot be null.
505      * @return the new method; never null.
506      */

507     public MethodTree createPropertyGetterMethod(ModifiersTree modifiersTree, String JavaDoc propertyName, Tree propertyType) throws IOException JavaDoc {
508         Parameters.notNull("modifiersTree", modifiersTree); // NOI18N
509
Parameters.javaIdentifier("propertyName", propertyName); // NOI18N
510
Parameters.notNull("propertyType", propertyType); // NOI18N
511
getWorkingCopy().toPhase(Phase.RESOLVED);
512
513         return getTreeMaker().Method(
514                 modifiersTree,
515                 createPropertyAccessorName(propertyName, true),
516                 propertyType,
517                 Collections.<TypeParameterTree>emptyList(),
518                 Collections.<VariableTree>emptyList(),
519                 Collections.<ExpressionTree>emptyList(),
520                 "{ return " + propertyName + "; }", // NOI18N
521
null);
522     }
523
524     /**
525      * Creates a new public property setter method.
526      *
527      * @param propertyType the fully-qualified name of the property type; cannot be null.
528      * @param propertyName the property name; cannot be null.
529      * @return the new method; never null.
530      */

531     public MethodTree createPropertySetterMethod(ModifiersTree modifiersTree, String JavaDoc propertyName, String JavaDoc propertyType) throws IOException JavaDoc {
532         Parameters.notNull("modifiersTree", modifiersTree); // NOI18N
533
Parameters.javaIdentifier("propertyName", propertyName); // NOI18N
534
Parameters.notNull("propertyType", propertyType); // NOI18N
535
getWorkingCopy().toPhase(Phase.RESOLVED);
536
537         return createPropertySetterMethod(modifiersTree, propertyName, createType(propertyType));
538     }
539
540     /**
541      * Creates a new public property setter method.
542      *
543      * @param propertyType the property type; cannot be null.
544      * @param propertyName the property name; cannot be null.
545      * @return the new method; never null.
546      */

547     public MethodTree createPropertySetterMethod(ModifiersTree modifiersTree, String JavaDoc propertyName, Tree propertyType) throws IOException JavaDoc {
548         Parameters.notNull("modifiersTree", modifiersTree); // NOI18N
549
Parameters.javaIdentifier("propertyName", propertyName); // NOI18N
550
Parameters.notNull("propertyType", propertyType); // NOI18N
551
getWorkingCopy().toPhase(Phase.RESOLVED);
552
553         TreeMaker make = getTreeMaker();
554         return make.Method(
555                 modifiersTree,
556                 createPropertyAccessorName(propertyName, false),
557                 make.PrimitiveType(TypeKind.VOID),
558                 Collections.<TypeParameterTree>emptyList(),
559                 Collections.singletonList(createVariable(propertyName, propertyType)),
560                 Collections.<ExpressionTree>emptyList(),
561                 "{ this." + propertyName + " = " + propertyName + "; }", // NOI18N
562
null);
563     }
564
565     /**
566      * Adds an annotation to a class. This is equivalent to {@link TreeMaker#addModifiersAnnotation},
567      * but it creates and returns a new <code>ClassTree, not a new <code>ModifiersTree</code>.
568      *
569      * @param classTree the class to add the annotation to; cannot be null.
570      * @param annotationTree the annotation to add; cannot be null.
571      * @return a new class annotated with the new annotation; never null.
572      */

573     @SuppressWarnings JavaDoc("unchecked") // NOI18N
574
public ClassTree addAnnotation(ClassTree classTree, AnnotationTree annotationTree) {
575         Parameters.notNull("classTree", classTree); // NOI18N
576
Parameters.notNull("annotationTree", annotationTree); // NOI18N
577

578         TreeMaker make = getTreeMaker();
579         return make.Class(
580                 make.addModifiersAnnotation(classTree.getModifiers(), annotationTree),
581                 classTree.getSimpleName(),
582                 classTree.getTypeParameters(),
583                 classTree.getExtendsClause(),
584                 (List JavaDoc<ExpressionTree>)classTree.getImplementsClause(),
585                 classTree.getMembers());
586     }
587
588     /**
589      * Adds an annotation to a method. This is equivalent to {@link TreeMaker#addModifiersAnnotation},
590      * but it creates and returns a new <code>MethodTree, not a new <code>ModifiersTree</code>.
591      *
592      * @param methodTree the method to add the annotation to; cannot be null.
593      * @param annotationTree the annotation to add; cannot be null.
594      * @return a new method annotated with the new annotation; never null.
595      */

596     public MethodTree addAnnotation(MethodTree methodTree, AnnotationTree annotationTree) {
597         Parameters.notNull("methodTree", methodTree); // NOI18N
598
Parameters.notNull("annotationTree", annotationTree); // NOI18N
599

600         TreeMaker make = getTreeMaker();
601         return make.Method(
602                 make.addModifiersAnnotation(methodTree.getModifiers(), annotationTree),
603                 methodTree.getName(),
604                 methodTree.getReturnType(),
605                 methodTree.getTypeParameters(),
606                 methodTree.getParameters(),
607                 methodTree.getThrows(),
608                 methodTree.getBody(),
609                 (ExpressionTree)methodTree.getDefaultValue());
610     }
611
612     /**
613      * Adds an annotation to a variable. This is equivalent to {@link TreeMaker#addModifiersAnnotation},
614      * but it creates and returns a new <code>VariableTree, not a new <code>ModifiersTree</code>.
615      *
616      * @param variableTree the variable to add the annotation to; cannot be null.
617      * @param annotationTree the annotation to add; cannot be null.
618      * @return a new variable annotated with the new annotation; never null.
619      */

620     public VariableTree addAnnotation(VariableTree variableTree, AnnotationTree annotationTree) {
621         Parameters.notNull("variableTree", variableTree); // NOI18N
622
Parameters.notNull("annotationTree", annotationTree); // NOI18N
623

624         TreeMaker make = getTreeMaker();
625         return make.Variable(
626                 make.addModifiersAnnotation(variableTree.getModifiers(), annotationTree),
627                 variableTree.getName(),
628                 variableTree.getType(),
629                 variableTree.getInitializer());
630     }
631
632     /**
633      * Inserts the given fields in the given class after any fields already existing
634      * in the class (if any, otherwise the fields are inserted at the beginning
635      * of the class).
636      *
637      * @param classTree the class to add fields to; cannot be null.
638      * @param fieldTrees the fields to be added; cannot be null.
639      * @return the class containing the new fields; never null.
640      */

641     public ClassTree addClassFields(ClassTree classTree, List JavaDoc<? extends VariableTree> fieldTrees) {
642         Parameters.notNull("classTree", classTree); // NOI18N
643
Parameters.notNull("fieldTrees", fieldTrees); // NOI18N
644

645         int firstNonFieldIndex = 0;
646         Iterator JavaDoc<? extends Tree> memberTrees = classTree.getMembers().iterator();
647         while (memberTrees.hasNext() && memberTrees.next().getKind() == Tree.Kind.VARIABLE) {
648             firstNonFieldIndex++;
649         }
650         TreeMaker make = getTreeMaker();
651         ClassTree newClassTree = getClassTree();
652         for (VariableTree fieldTree : fieldTrees) {
653             newClassTree = make.insertClassMember(newClassTree, firstNonFieldIndex, fieldTree);
654             firstNonFieldIndex++;
655         }
656         return newClassTree;
657     }
658
659     // MISSING addClassConstructors(), addClassMethods()
660

661     /**
662      * Adds the specified interface to the implements clause of
663      * {@link #getClassTree()}.
664      *
665      * @param interfaceType the fully-qualified name of the interface; cannot be null.
666      */

667     public ClassTree addImplementsClause(ClassTree classTree, String JavaDoc interfaceType) {
668         if (getTypeElement().getKind() != ElementKind.CLASS) {
669             throw new IllegalStateException JavaDoc("Cannot add an implements clause to the non-class type " + getTypeElement().getQualifiedName()); // NOI18N
670
}
671
672         ExpressionTree interfaceTree = createQualIdent(interfaceType);
673         return getTreeMaker().addClassImplementsClause(classTree, interfaceTree);
674     }
675
676     // </editor-fold>
677

678     // <editor-fold defaultstate="collapsed" desc="Non-public methods">
679

680     /**
681      * Returns the working copy this instance works with.
682      *
683      * @return the working copy this instance works with; never null.
684      */

685     private WorkingCopy getWorkingCopy() {
686         return (WorkingCopy)getCompilationController();
687     }
688
689     private TreeMaker getTreeMaker() {
690         return getWorkingCopy().getTreeMaker();
691     }
692
693     private ModifiersTree createEmptyModifiers() {
694         return getTreeMaker().Modifiers(Collections.<Modifier>emptySet(), Collections.<AnnotationTree>emptyList());
695     }
696
697     private ExpressionTree createQualIdent(String JavaDoc typeName) {
698         TypeElement typeElement = getWorkingCopy().getElements().getTypeElement(typeName);
699         if (typeElement == null) {
700             throw new IllegalArgumentException JavaDoc("Type " + typeName + " cannot be found"); // NOI18N
701
}
702         return getTreeMaker().QualIdent(typeElement);
703     }
704
705     private String JavaDoc createPropertyAccessorName(String JavaDoc propertyName, boolean getter) {
706         assert propertyName.length() > 0;
707         StringBuffer JavaDoc pascalCaseName = new StringBuffer JavaDoc(propertyName);
708         pascalCaseName.setCharAt(0, Character.toUpperCase(pascalCaseName.charAt(0)));
709         return (getter ? "get" : "set") + pascalCaseName; // NOI18N
710
}
711
712     // </editor-fold>
713
}
714
Popular Tags