KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > j2ee > common > source > 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.common.source;
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.Map JavaDoc;
29 import java.util.Set JavaDoc;
30 import javax.lang.model.element.*;
31 import javax.lang.model.type.*;
32 import org.netbeans.api.java.source.JavaSource.Phase;
33 import org.netbeans.api.java.source.TreeMaker;
34 import org.netbeans.api.java.source.WorkingCopy;
35 import org.openide.filesystems.FileObject;
36 import org.openide.filesystems.FileSystem;
37 import org.openide.filesystems.Repository;
38 import org.openide.loaders.DataFolder;
39 import org.openide.loaders.DataObject;
40 import org.openide.util.Parameters;
41
42 /**
43  *
44  * @author Andrei Badea
45  */

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

54     // TODO use CharSequence instead of String where possible
55

56     /**
57      * The templates for regular Java class and interface.
58      */

59     static final String JavaDoc CLASS_TEMPLATE = "Templates/Classes/Class.java"; // NOI18N
60
static final String JavaDoc INTERFACE_TEMPLATE = "Templates/Classes/Interface.java"; // NOI18N
61

62     // <editor-fold desc="Constructors and factory methods">
63

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

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

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

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

98     // <editor-fold desc="Public static methods">
99

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

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

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

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

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

157         return classFO;
158     }
159
160     /**
161      * Creates a new Java class based on the provided template.
162      *
163      * @param targetFolder the folder the new class should be created in;
164      * cannot be null.
165      * @param targetName the name of the new interface (a valid Java identifier);
166      * cannot be null.
167      * @param parameters map of named objects that are going to be used when creating the new object
168      * @return the FileObject for the new Java class; never null.
169      */

170     public static FileObject createClass(String JavaDoc template, FileObject targetFolder, String JavaDoc className, final String JavaDoc javadoc,
171             Map JavaDoc<String JavaDoc,? extends Object JavaDoc> parameters) throws IOException JavaDoc {
172         Parameters.notNull("template", template); // NOI18N
173
Parameters.notNull("targetFolder", targetFolder); // NOI18N
174
Parameters.javaIdentifier("className", className); // NOI18N
175

176         FileObject classFO = createDataObjectFromTemplate(template, targetFolder, className, parameters).getPrimaryFile();
177         return classFO;
178     }
179
180     // </editor-fold>
181

182     // <editor-fold defaultstate="collapsed" desc="Non-public static methods">
183

184     /**
185      * Creates a data object from a given template path in the system
186      * file system.
187      *
188      * @return the <code>DataObject</code> of the newly created file.
189      * @throws IOException if an error occured while creating the file.
190      */

191     private static DataObject createDataObjectFromTemplate(String JavaDoc template, FileObject targetFolder, String JavaDoc targetName) throws IOException JavaDoc {
192         assert template != null;
193         assert targetFolder != null;
194         assert targetName != null && targetName.trim().length() > 0;
195
196         FileSystem defaultFS = Repository.getDefault().getDefaultFileSystem();
197         FileObject templateFO = defaultFS.findResource(template);
198         DataObject templateDO = DataObject.find(templateFO);
199         DataFolder dataFolder = DataFolder.findFolder(targetFolder);
200         return templateDO.createFromTemplate(dataFolder, targetName);
201     }
202
203     /**
204      * Creates a data object from a given template path in the system
205      * file system and using parameters defined in <code>parameters</code> map.
206      *
207      * @return the <code>DataObject</code> of the newly created file.
208      * @throws IOException if an error occured while creating the file.
209      */

210     private static DataObject createDataObjectFromTemplate(String JavaDoc template, FileObject targetFolder, String JavaDoc targetName,
211             Map JavaDoc<String JavaDoc,? extends Object JavaDoc> parameters) throws IOException JavaDoc {
212         assert template != null;
213         assert targetFolder != null;
214         assert targetName != null && targetName.trim().length() > 0;
215
216         FileSystem defaultFS = Repository.getDefault().getDefaultFileSystem();
217         FileObject templateFO = defaultFS.findResource(template);
218         DataObject templateDO = DataObject.find(templateFO);
219         DataFolder dataFolder = DataFolder.findFolder(targetFolder);
220         return templateDO.createFromTemplate(dataFolder, targetName, parameters);
221     }
222
223     // </editor-fold>
224

225     // <editor-fold desc="Public methods">
226

227     public Tree createType(String JavaDoc typeName) {
228         TreeMaker make = getTreeMaker();
229         TypeKind primitiveTypeKind = null;
230         if ("boolean".equals(typeName)) { // NOI18N
231
primitiveTypeKind = TypeKind.BOOLEAN;
232         } else if ("byte".equals(typeName)) { // NOI18N
233
primitiveTypeKind = TypeKind.BYTE;
234         } else if ("short".equals(typeName)) { // NOI18N
235
primitiveTypeKind = TypeKind.SHORT;
236         } else if ("int".equals(typeName)) { // NOI18N
237
primitiveTypeKind = TypeKind.INT;
238         } else if ("long".equals(typeName)) { // NOI18N
239
primitiveTypeKind = TypeKind.LONG;
240         } else if ("char".equals(typeName)) { // NOI18N
241
primitiveTypeKind = TypeKind.CHAR;
242         } else if ("float".equals(typeName)) { // NOI18N
243
primitiveTypeKind = TypeKind.FLOAT;
244         } else if ("double".equals(typeName)) { // NOI18N
245
primitiveTypeKind = TypeKind.DOUBLE;
246         }
247         if (primitiveTypeKind != null) {
248             return getTreeMaker().PrimitiveType(primitiveTypeKind);
249         }
250         return createQualIdent(typeName);
251     }
252
253     public ModifiersTree createModifiers(Modifier modifier) {
254         return getTreeMaker().Modifiers(EnumSet.of(modifier), Collections.<AnnotationTree>emptyList());
255     }
256
257     /**
258      * Creates a new annotation.
259      *
260      * @param annotationType the fully-qualified name of the annotation type;
261      * cannot be null.
262      * @return the new annotation; never null.
263      */

264     public AnnotationTree createAnnotation(String JavaDoc annotationType) {
265         Parameters.notNull("annotationType", annotationType); // NOI18N
266

267         return createAnnotation(annotationType, Collections.<ExpressionTree>emptyList());
268     }
269
270     /**
271      * Creates a new annotation.
272      *
273      * @param annotationType the fully-qualified name of the annotation type;
274      * cannot be null.
275      * <code>java.lang.SuppressWarnings</code>; cannot be null.
276      * @param arguments the arguments of the new annotation; cannot be null.
277      * @return the new annotation; never null.
278      */

279     public AnnotationTree createAnnotation(String JavaDoc annotationType, List JavaDoc<? extends ExpressionTree> arguments) {
280         Parameters.notNull("annotationType", annotationType); // NOI18N
281
Parameters.notNull("arguments", arguments); // NOI18N
282

283         ExpressionTree annotationTypeTree = createQualIdent(annotationType);
284         return getTreeMaker().Annotation(annotationTypeTree, arguments);
285     }
286
287     /**
288      * Creates a new annotation argument whose value is a literal.
289      *
290      * @param argumentName the argument name; cannot be null.
291      * @param argumentValue the argument value; cannot be null. The semantics
292      * of this parameter is the same as of the parameters of
293      * {@link TreeMaker#Literal(Object)}.
294      * @return the new annotation argument; never null.
295      */

296     public ExpressionTree createAnnotationArgument(String JavaDoc argumentName, Object JavaDoc argumentValue) {
297         Parameters.javaIdentifierOrNull("argumentName", argumentName); // NOI18N
298
Parameters.notNull("argumentValue", argumentValue); // NOI18N
299

300         TreeMaker make = getTreeMaker();
301         ExpressionTree argumentValueTree = make.Literal(argumentValue);
302         if (argumentName == null) {
303             return argumentValueTree;
304         } else {
305             return make.Assignment(make.Identifier(argumentName), argumentValueTree);
306         }
307     }
308
309     /**
310      * Creates a new annotation argument whose value is an array.
311      *
312      * @param argumentName the argument name; cannot be null.
313      * @param argumentValue the argument value; cannot be null.
314      * @return the new annotation argument; never null.
315      */

316     public ExpressionTree createAnnotationArgument(String JavaDoc argumentName, List JavaDoc<? extends ExpressionTree> argumentValues) {
317         Parameters.javaIdentifierOrNull("argumentName", argumentName); // NOI18N
318
Parameters.notNull("argumentValues", argumentValues); // NOI18N
319

320         TreeMaker make = getTreeMaker();
321         ExpressionTree argumentValuesTree = make.NewArray(null, Collections.<ExpressionTree>emptyList(), argumentValues);
322         if (argumentName == null) {
323             return argumentValuesTree;
324         } else {
325             return make.Assignment(make.Identifier(argumentName), argumentValuesTree);
326         }
327     }
328
329     /**
330      * Creates a new annotation argument whose value is a member of a type. For
331      * example it can be used to generate <code>@Target(ElementType.CONSTRUCTOR)</code>.
332      *
333      * @param argumentName the argument name; cannot be null.
334      * @param argumentType the fully-qualified name of the type whose member is to be invoked
335      * (e.g. <code>java.lang.annotations.ElementType</code> in the previous
336      * example); cannot be null.
337      * @param argumentTypeField a field of <code>argumentType</code>
338      * (e.g. <code>CONSTRUCTOR</code> in the previous example);
339      * cannot be null.
340      * @return the new annotation argument; never null.
341      */

342     public ExpressionTree createAnnotationArgument(String JavaDoc argumentName, String JavaDoc argumentType, String JavaDoc argumentTypeField) {
343         Parameters.javaIdentifierOrNull("argumentName", argumentName); // NOI18N
344
Parameters.notNull("argumentType", argumentType); // NOI18N
345
Parameters.javaIdentifier("argumentTypeField", argumentTypeField); // NOI18N
346

347         TreeMaker make = getTreeMaker();
348         MemberSelectTree argumentValueTree = make.MemberSelect(createQualIdent(argumentType), argumentTypeField);
349         if (argumentName == null) {
350             return argumentValueTree;
351         } else {
352             return make.Assignment(make.Identifier(argumentName), argumentValueTree);
353         }
354     }
355
356     /**
357      * Ensures the given class has a public no-arg constructor.
358      *
359      * @param classTree the class to ensure the constructor for; cannot be null.
360      * @return a modified class if a no-arg constructor was added, the original
361      * class otherwise; never null.
362      */

363     public ClassTree ensureNoArgConstructor(ClassTree classTree) throws IOException JavaDoc {
364         getWorkingCopy().toPhase(Phase.RESOLVED);
365
366         ExecutableElement constructor = getNoArgConstructor();
367         MethodTree constructorTree = constructor != null ? getWorkingCopy().getTrees().getTree(constructor) : null;
368         MethodTree newConstructorTree = null;
369         TreeMaker make = getTreeMaker();
370         if (constructor != null) {
371             if (!constructor.getModifiers().contains(Modifier.PUBLIC)) {
372                 ModifiersTree oldModifiersTree = constructorTree.getModifiers();
373                 Set JavaDoc<Modifier> newModifiers = EnumSet.of(Modifier.PUBLIC);
374                 for (Modifier modifier : oldModifiersTree.getFlags()) {
375                     if (!Modifier.PROTECTED.equals(modifier) && !Modifier.PRIVATE.equals(modifier)) {
376                         newModifiers.add(modifier);
377                     }
378                 }
379                 newConstructorTree = make.Constructor(
380                     make.Modifiers(newModifiers),
381                     constructorTree.getTypeParameters(),
382                     constructorTree.getParameters(),
383                     constructorTree.getThrows(),
384                     constructorTree.getBody());
385             }
386         } else {
387             newConstructorTree = make.Constructor(
388                     createModifiers(Modifier.PUBLIC),
389                     Collections.<TypeParameterTree>emptyList(),
390                     Collections.<VariableTree>emptyList(),
391                     Collections.<ExpressionTree>emptyList(),
392                     "{ }"); // NOI18N
393
}
394         ClassTree newClassTree = classTree;
395         if (newConstructorTree != null) {
396             if (constructorTree != null) {
397                 newClassTree = make.removeClassMember(newClassTree, constructorTree);
398             }
399             newClassTree = make.addClassMember(newClassTree, newConstructorTree);
400         }
401         return newClassTree;
402     }
403
404     /**
405      * Creates a constructor which assigns its parameters to fields with the
406      * same names. For example it can be used to generate:
407      *
408      * <pre>
409      * public void Constructor(String field1, Object field2) {
410      * this.field1 = field1;
411      * this.field2 = field2;
412      * }
413      * </pre>
414      *
415      * @param modifier the constructor modifier.
416      * @param constructorName the constructor name; cannot be null.
417      * @param parameters the constructor parameters; cannot be null.
418      * @return the new constructor; never null.
419      */

420     public MethodTree createAssignmentConstructor(ModifiersTree modifiersTree, String JavaDoc constructorName, List JavaDoc<VariableTree> parameters) {
421         Parameters.notNull("modifiersTree", modifiersTree);
422         Parameters.javaIdentifier("constructorName", constructorName); // NOI18N
423
Parameters.notNull("parameters", parameters); // NOI18N
424

425         StringBuilder JavaDoc body = new StringBuilder JavaDoc(parameters.size() * 30);
426         body.append("{"); // NOI18N
427
for (VariableTree parameter : parameters) {
428             String JavaDoc parameterName = parameter.getName().toString();
429             body.append("this." + parameterName + " = " + parameterName + ";"); // NOI18N
430
}
431         body.append("}"); // NOI18N
432

433         TreeMaker make = getTreeMaker();
434         return make.Constructor(
435                 modifiersTree,
436                 Collections.<TypeParameterTree>emptyList(),
437                 parameters,
438                 Collections.<ExpressionTree>emptyList(),
439                 body.toString());
440     }
441
442     /**
443      * Creates a new field.
444      *
445      * @param modifiersTree the field modifiers; cannot be null.
446      * @param fieldType the fully-qualified name of the field type; cannot be null.
447      * @param fieldName the field name; cannot be null.
448      * @return the new field; never null.
449      */

450     public VariableTree createField(ModifiersTree modifiersTree, String JavaDoc fieldName, String JavaDoc fieldType) {
451         Parameters.notNull("modifiersTree", modifiersTree); // NOI18N
452
Parameters.javaIdentifier("fieldName", fieldName); // NOI18N
453
Parameters.notNull("fieldType", fieldType); // NOI18N
454

455         return getTreeMaker().Variable(
456                 modifiersTree,
457                 fieldName,
458                 createType(fieldType),
459                 null);
460     }
461
462     // MISSING createField(ModifiersTree, String, String, ExpressionTree)
463

464     /**
465      * Creates a new variable (a <code>VariableTree</code> with no
466      * modifiers nor initializer).
467      *
468      * @param variableType the fully-qualified name of the variable type; cannot be null.
469      * @param variableName the variable name; cannot be null.
470      * @return the new variable; never null.
471      */

472     public VariableTree createVariable(String JavaDoc variableName, String JavaDoc variableType) {
473         Parameters.javaIdentifier("variableName", variableName); // NOI18N
474
Parameters.notNull("variableType", variableType); // NOI18N
475

476         return createField(
477                 createEmptyModifiers(),
478                 variableName,
479                 variableType);
480     }
481
482     /**
483      * Creates a new variable (a <code>VariableTree</code> with no
484      * modifiers nor initializer).
485      *
486      * @param variableType the variable type; cannot be null.
487      * @param variableName the variable name; cannot be null.
488      * @return the new variable; never null.
489      */

490     public VariableTree createVariable(String JavaDoc variableName, Tree variableType) {
491         Parameters.javaIdentifier("variableName", variableName); // NOI18N
492
Parameters.notNull("variableType", variableType); // NOI18N
493

494         return getTreeMaker().Variable(
495                 createEmptyModifiers(),
496                 variableName,
497                 variableType,
498                 null);
499     }
500
501     /**
502      * Removes any modifiers from the given <code>VariableTree</code>. This can be e.g.
503      * used to create a variable suitable for use as a method parameter.
504      *
505      * @param variableTree the <code>VariableTree</code> to remove the modifiers from.
506      * @return a <code>VariableTree</code> with the same properties but no modifiers.
507      */

508     public VariableTree removeModifiers(VariableTree variableTree) {
509         Parameters.notNull("variableTree", variableTree);
510
511         TreeMaker make = getTreeMaker();
512         return make.Variable(
513                 createEmptyModifiers(),
514                 variableTree.getName(),
515                 variableTree.getType(),
516                 variableTree.getInitializer());
517     }
518
519     /**
520      * Creates a new public property getter method.
521      *
522      * @param modifiersTree the method modifiers; cannot be null.
523      * @param propertyType the fully-qualified name of the property type; cannot be null.
524      * @param propertyName the property name; cannot be null.
525      * @return the new method; never null.
526      */

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

544     public MethodTree createPropertyGetterMethod(ModifiersTree modifiersTree, String JavaDoc propertyName, Tree propertyType) throws IOException JavaDoc {
545         Parameters.notNull("modifiersTree", modifiersTree); // NOI18N
546
Parameters.javaIdentifier("propertyName", propertyName); // NOI18N
547
Parameters.notNull("propertyType", propertyType); // NOI18N
548
getWorkingCopy().toPhase(Phase.RESOLVED);
549
550         return getTreeMaker().Method(
551                 modifiersTree,
552                 createPropertyAccessorName(propertyName, true),
553                 propertyType,
554                 Collections.<TypeParameterTree>emptyList(),
555                 Collections.<VariableTree>emptyList(),
556                 Collections.<ExpressionTree>emptyList(),
557                 "{ return " + propertyName + "; }", // NOI18N
558
null);
559     }
560
561     /**
562      * Creates a new public property setter method.
563      *
564      * @param propertyType the fully-qualified name of the property type; cannot be null.
565      * @param propertyName the property name; cannot be null.
566      * @return the new method; never null.
567      */

568     public MethodTree createPropertySetterMethod(ModifiersTree modifiersTree, String JavaDoc propertyName, String JavaDoc propertyType) throws IOException JavaDoc {
569         Parameters.notNull("modifiersTree", modifiersTree); // NOI18N
570
Parameters.javaIdentifier("propertyName", propertyName); // NOI18N
571
Parameters.notNull("propertyType", propertyType); // NOI18N
572
getWorkingCopy().toPhase(Phase.RESOLVED);
573
574         return createPropertySetterMethod(modifiersTree, propertyName, createType(propertyType));
575     }
576
577     /**
578      * Creates a new public property setter method.
579      *
580      * @param propertyType the property type; cannot be null.
581      * @param propertyName the property name; cannot be null.
582      * @return the new method; never null.
583      */

584     public MethodTree createPropertySetterMethod(ModifiersTree modifiersTree, String JavaDoc propertyName, Tree propertyType) throws IOException JavaDoc {
585         Parameters.notNull("modifiersTree", modifiersTree); // NOI18N
586
Parameters.javaIdentifier("propertyName", propertyName); // NOI18N
587
Parameters.notNull("propertyType", propertyType); // NOI18N
588
getWorkingCopy().toPhase(Phase.RESOLVED);
589
590         TreeMaker make = getTreeMaker();
591         return make.Method(
592                 modifiersTree,
593                 createPropertyAccessorName(propertyName, false),
594                 make.PrimitiveType(TypeKind.VOID),
595                 Collections.<TypeParameterTree>emptyList(),
596                 Collections.singletonList(createVariable(propertyName, propertyType)),
597                 Collections.<ExpressionTree>emptyList(),
598                 "{ this." + propertyName + " = " + propertyName + "; }", // NOI18N
599
null);
600     }
601
602     /**
603      * Adds an annotation to a class. This is equivalent to {@link TreeMaker#addModifiersAnnotation},
604      * but it creates and returns a new <code>ClassTree, not a new <code>ModifiersTree</code>.
605      *
606      * @param classTree the class to add the annotation to; cannot be null.
607      * @param annotationTree the annotation to add; cannot be null.
608      * @return a new class annotated with the new annotation; never null.
609      */

610     @SuppressWarnings JavaDoc("unchecked") // NOI18N
611
public ClassTree addAnnotation(ClassTree classTree, AnnotationTree annotationTree) {
612         Parameters.notNull("classTree", classTree); // NOI18N
613
Parameters.notNull("annotationTree", annotationTree); // NOI18N
614

615         TreeMaker make = getTreeMaker();
616         return make.Class(
617                 make.addModifiersAnnotation(classTree.getModifiers(), annotationTree),
618                 classTree.getSimpleName(),
619                 classTree.getTypeParameters(),
620                 classTree.getExtendsClause(),
621                 (List JavaDoc<ExpressionTree>)classTree.getImplementsClause(),
622                 classTree.getMembers());
623     }
624
625     /**
626      * Adds an annotation to a method. This is equivalent to {@link TreeMaker#addModifiersAnnotation},
627      * but it creates and returns a new <code>MethodTree, not a new <code>ModifiersTree</code>.
628      *
629      * @param methodTree the method to add the annotation to; cannot be null.
630      * @param annotationTree the annotation to add; cannot be null.
631      * @return a new method annotated with the new annotation; never null.
632      */

633     public MethodTree addAnnotation(MethodTree methodTree, AnnotationTree annotationTree) {
634         Parameters.notNull("methodTree", methodTree); // NOI18N
635
Parameters.notNull("annotationTree", annotationTree); // NOI18N
636

637         TreeMaker make = getTreeMaker();
638         return make.Method(
639                 make.addModifiersAnnotation(methodTree.getModifiers(), annotationTree),
640                 methodTree.getName(),
641                 methodTree.getReturnType(),
642                 methodTree.getTypeParameters(),
643                 methodTree.getParameters(),
644                 methodTree.getThrows(),
645                 methodTree.getBody(),
646                 (ExpressionTree)methodTree.getDefaultValue());
647     }
648
649     /**
650      * Adds an annotation to a variable. This is equivalent to {@link TreeMaker#addModifiersAnnotation},
651      * but it creates and returns a new <code>VariableTree, not a new <code>ModifiersTree</code>.
652      *
653      * @param variableTree the variable to add the annotation to; cannot be null.
654      * @param annotationTree the annotation to add; cannot be null.
655      * @return a new variable annotated with the new annotation; never null.
656      */

657     public VariableTree addAnnotation(VariableTree variableTree, AnnotationTree annotationTree) {
658         Parameters.notNull("variableTree", variableTree); // NOI18N
659
Parameters.notNull("annotationTree", annotationTree); // NOI18N
660

661         TreeMaker make = getTreeMaker();
662         return make.Variable(
663                 make.addModifiersAnnotation(variableTree.getModifiers(), annotationTree),
664                 variableTree.getName(),
665                 variableTree.getType(),
666                 variableTree.getInitializer());
667     }
668
669     /**
670      * Inserts the given fields in the given class after any fields already existing
671      * in the class (if any, otherwise the fields are inserted at the beginning
672      * of the class).
673      *
674      * @param classTree the class to add fields to; cannot be null.
675      * @param fieldTrees the fields to be added; cannot be null.
676      * @return the class containing the new fields; never null.
677      */

678     public ClassTree addClassFields(ClassTree classTree, List JavaDoc<? extends VariableTree> fieldTrees) {
679         Parameters.notNull("classTree", classTree); // NOI18N
680
Parameters.notNull("fieldTrees", fieldTrees); // NOI18N
681

682         int firstNonFieldIndex = 0;
683         Iterator JavaDoc<? extends Tree> memberTrees = classTree.getMembers().iterator();
684         while (memberTrees.hasNext() && memberTrees.next().getKind() == Tree.Kind.VARIABLE) {
685             firstNonFieldIndex++;
686         }
687         TreeMaker make = getTreeMaker();
688         ClassTree newClassTree = getClassTree();
689         for (VariableTree fieldTree : fieldTrees) {
690             newClassTree = make.insertClassMember(newClassTree, firstNonFieldIndex, fieldTree);
691             firstNonFieldIndex++;
692         }
693         return newClassTree;
694     }
695
696     // MISSING addClassConstructors(), addClassMethods()
697

698     /**
699      * Adds the specified interface to the implements clause of
700      * {@link #getClassTree()}.
701      *
702      * @param interfaceType the fully-qualified name of the interface; cannot be null.
703      */

704     public ClassTree addImplementsClause(ClassTree classTree, String JavaDoc interfaceType) {
705         if (getTypeElement().getKind() != ElementKind.CLASS) {
706             throw new IllegalStateException JavaDoc("Cannot add an implements clause to the non-class type " + getTypeElement().getQualifiedName()); // NOI18N
707
}
708
709         ExpressionTree interfaceTree = createQualIdent(interfaceType);
710         return getTreeMaker().addClassImplementsClause(classTree, interfaceTree);
711     }
712
713     // </editor-fold>
714

715     // <editor-fold defaultstate="collapsed" desc="Non-public methods">
716

717     /**
718      * Returns the working copy this instance works with.
719      *
720      * @return the working copy this instance works with; never null.
721      */

722     private WorkingCopy getWorkingCopy() {
723         return (WorkingCopy)getCompilationController();
724     }
725
726     private TreeMaker getTreeMaker() {
727         return getWorkingCopy().getTreeMaker();
728     }
729
730     private ModifiersTree createEmptyModifiers() {
731         return getTreeMaker().Modifiers(Collections.<Modifier>emptySet(), Collections.<AnnotationTree>emptyList());
732     }
733
734     private ExpressionTree createQualIdent(String JavaDoc typeName) {
735         TypeElement typeElement = getWorkingCopy().getElements().getTypeElement(typeName);
736         if (typeElement == null) {
737             throw new IllegalArgumentException JavaDoc("Type " + typeName + " cannot be found"); // NOI18N
738
}
739         return getTreeMaker().QualIdent(typeElement);
740     }
741
742     private String JavaDoc createPropertyAccessorName(String JavaDoc propertyName, boolean getter) {
743         assert propertyName.length() > 0;
744         StringBuffer JavaDoc pascalCaseName = new StringBuffer JavaDoc(propertyName);
745         pascalCaseName.setCharAt(0, Character.toUpperCase(pascalCaseName.charAt(0)));
746         return (getter ? "get" : "set") + pascalCaseName; // NOI18N
747
}
748
749     // </editor-fold>
750
}
751
Popular Tags