KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > test > java > Common


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 /*
21  * Common.java
22  *
23  * Created on May 19, 2000, 1:56 PM
24  */

25
26 package org.netbeans.test.java;
27
28 import com.sun.source.tree.AnnotationTree;
29 import com.sun.source.tree.BlockTree;
30 import com.sun.source.tree.ClassTree;
31 import com.sun.source.tree.CompilationUnitTree;
32 import com.sun.source.tree.ExpressionTree;
33 import com.sun.source.tree.ImportTree;
34 import com.sun.source.tree.MethodTree;
35 import com.sun.source.tree.ModifiersTree;
36 import com.sun.source.tree.Tree;
37 import com.sun.source.tree.Tree.Kind;
38 import com.sun.source.tree.TypeParameterTree;
39 import com.sun.source.tree.VariableTree;
40 import java.io.IOException JavaDoc;
41 import java.util.ArrayList JavaDoc;
42 import java.util.Collections JavaDoc;
43 import java.util.EnumSet JavaDoc;
44 import java.util.HashMap JavaDoc;
45 import java.util.LinkedList JavaDoc;
46 import java.util.List JavaDoc;
47 import java.util.Map JavaDoc;
48 import java.util.Set JavaDoc;
49 import javax.lang.model.element.Modifier;
50 import javax.lang.model.element.TypeElement;
51 import javax.lang.model.type.TypeKind;
52 import org.netbeans.api.java.classpath.ClassPath;
53 import org.netbeans.api.java.source.CancellableTask;
54 import org.netbeans.api.java.source.Comment;
55 import org.netbeans.api.java.source.JavaSource;
56 import org.netbeans.api.java.source.JavaSource.Phase;
57 import org.netbeans.api.java.source.TreeMaker;
58 import org.netbeans.api.java.source.WorkingCopy;
59 import org.openide.filesystems.*;
60 import org.openide.loaders.DataObject;
61 import org.openide.filesystems.Repository;
62 //import org.openide.src.MethodParameter;
63
//import org.openide.src.Type;
64

65
66 /** Common static methods. Useful for creating new JavaElements
67  * @author Jan Becicka
68  * @version 1.1
69  */

70
71 public class Common extends Object JavaDoc {
72     
73     private static final String JavaDoc cr=System.getProperty("line.separator");
74     private static final String JavaDoc METHODS = "newMethod";
75     private static final String JavaDoc FIELDS = "newField";
76     //private static final int DEFAULTMODIFIERS = Modifier.PUBLIC;
77
private static final String JavaDoc DEFAULTBODY = "for (int i=0;i<100;i++){\n\tSystem.out.println(new Integer(i).toString());\n}\nreturn 0;\n";
78     public static final String JavaDoc DEFAULTINITIALIZERBODY = "\n/*somebody*/\n";
79     
80     /** int parameter1
81      */

82     public static Map JavaDoc<String JavaDoc,String JavaDoc> PARS1;
83     /** int parameter1, int parameter2
84      */

85     public static Map JavaDoc<String JavaDoc,String JavaDoc> PARS2;
86     /** float parameter1, float parameter2, float parameter 3
87      */

88     public static Map JavaDoc<String JavaDoc,String JavaDoc> PARS3;
89     
90     
91     /** int parameter1
92      */

93     //public static Type[] TPARS1={Type.INT};
94
/** int parameter1, int parameter2smnJm kjhklkj .k
95      */

96     //public static Type[] TPARS2={Type.INT,Type.INT};
97
/** float parameter1, float parameter2, float parameter 3
98      */

99     //public static Type[] TPARS3={Type.FLOAT,Type.FLOAT, Type.INT};
100

101     static {
102         PARS1 = new HashMap JavaDoc<String JavaDoc, String JavaDoc>();
103         PARS1.put("param1","int");
104         PARS2 = new HashMap JavaDoc<String JavaDoc, String JavaDoc>();
105         PARS2.put("param1","int");
106         PARS2.put("param2","int");
107         PARS3 = new HashMap JavaDoc<String JavaDoc, String JavaDoc>();
108         PARS3.put("param1","float");
109         PARS3.put("param2","int");
110         PARS3.put("param3","String");
111         
112     }
113     
114     private static java.io.PrintWriter JavaDoc pw = null;
115     
116     public static void setPrintWriter(java.io.PrintWriter JavaDoc pr){
117         pw=pr;
118     }
119     
120     // private static Type getType(int i) throws Exception {
121
// switch (i){
122
// case 0x0001: return Type.BOOLEAN;
123
// case 0x0002: return Type.INT ;
124
// case 0x0003: return Type.CHAR;
125
// case 0x0004: return Type.BYTE;
126
// case 0x0005: return Type.SHORT ;
127
// case 0x0006: return Type.LONG;
128
// case 0x0007: return Type.FLOAT;
129
// case 0x0008: return Type.DOUBLE;
130
// case 0x0009: return Type.VOID;
131
// }
132
// throw new Exception("unknown type");
133
// }
134

135     
136     public Common() {
137     }
138     
139     /** returns string from in and int
140      * @param s
141      * @param i
142      * @return Makes String from String and int
143      */

144     public static String JavaDoc concat(String JavaDoc s, int i){
145         return s+new Integer JavaDoc(i).toString();
146     }
147     
148     /**
149      * @param i
150      * @return for i=1 "newMethod1"
151      */

152     static public String JavaDoc getMethodName(int i){
153         return concat(METHODS,i);
154     }
155     
156     /** Concats String and int
157      * @param name
158      * @param i
159      * @return
160      */

161     public static String JavaDoc getFieldName(String JavaDoc name,int i){
162         return concat(name,i);
163     }
164     
165     /**
166      * @param i
167      * @return for i=1 "newField1"
168      */

169     public static String JavaDoc getFieldName(int i){
170         return concat(FIELDS,i);
171     }
172     
173     /**
174      * @param name Name of method
175      * @param modifiers Modifiers
176      * @param returntype Return Type
177      * @param pars Parameters
178      * @return
179      */

180     // public static MethodElement createMethod(String name, int modifiers, Type returntype, MethodParameter[] pars) throws Exception {
181
// MethodElement me = new MethodElement();
182
// me.setName(Identifier.create(name));
183
// me.setParameters(pars);
184
// me.setReturn(returntype);
185
// me.setExceptions(new Identifier[] { Identifier.create("java.io.IOException") });
186
// me.setModifiers(modifiers);
187
// me.setBody("\n/*This is body of mehod"+name+"*/\n"+DEFAULTBODY);
188
// return me;
189
// }
190

191     /** Creates method with empty body, return type is int.
192      * @param name Name of method
193      * @throws Exception
194      * @return
195      */

196     // public static MethodElement createEmptyMethod(String name) throws Exception {
197
// MethodElement me = createMethod(name);
198
// me.setBody(null);
199
// return me;
200
// }
201

202     /** Creates method. Retrun type is int.
203      * @param name Name of new method
204      * @throws Exception
205      * @return
206      */

207     // public static MethodElement createMethod(String name) throws Exception{
208
// return createMethod(name,DEFAULTMODIFIERS,Type.INT);
209
// }
210

211     /**
212      * @param name Name of new method
213      * @param modifiers Modifiers
214      * @param returntype Return Type
215      * @throws Exception
216      * @return
217      */

218     // public static MethodElement createMethod(String name,int modifiers,int returntype) throws Exception {
219
// return createMethod(name, modifiers, getType(returntype));
220
// }
221

222     /**
223      * @param name Name of new method
224      * @param modifiers Modifiers
225      * @param returntype Return Type
226      * @throws Exception
227      * @return
228      */

229     // public static MethodElement createMethod(String name,int modifiers,Type returntype) throws Exception {
230
// return createMethod(name, modifiers, returntype, new MethodParameter[] { });
231
// }
232

233     
234     // /** Creates public float name;
235
// * @param name
236
// * @throws Exception
237
// * @return
238
// */
239
// public static FieldElement createField(String name) throws Exception {
240
// return createField(name, DEFAULTMODIFIERS, Type.FLOAT);
241
// }
242
//
243
// /** creates new field
244
// */
245
// public static FieldElement createField(String name, int modifiers, int type) throws Exception {
246
// return createField(name, modifiers, getType(type));
247
// }
248
//
249
// /** creates new field
250
// * @param name
251
// * @param modifiers
252
// * @param type
253
// * @throws Exception
254
// * @return
255
// */
256
// public static FieldElement createField(String name, int modifiers, Type type) throws Exception {
257
// FieldElement fe = new FieldElement();
258
// fe.setName(Identifier.create(name));
259
// fe.setModifiers(modifiers);
260
// fe.setType(type);
261
// return fe;
262
// }
263
//
264

265     private static Tree getTreeForType(String JavaDoc paramType, TreeMaker make) {
266         Tree param = null;
267         try {
268             param = make.PrimitiveType(TypeKind.valueOf(paramType.toUpperCase()));
269         } catch (IllegalArgumentException JavaDoc iae) {
270             param = make.Identifier(paramType);
271         }
272         return param;
273     }
274     
275     public static MethodTree createMethod(TreeMaker make,String JavaDoc name, Map JavaDoc<String JavaDoc,String JavaDoc> params) {
276         ModifiersTree methodModifiers = make.Modifiers(
277                 Collections.<Modifier>singleton(Modifier.PUBLIC),
278                 Collections.<AnnotationTree>emptyList()
279                 );
280         List JavaDoc<VariableTree> paramList = new LinkedList JavaDoc<VariableTree>();
281         for(String JavaDoc paramName: params.keySet()) {
282             Tree paramType = getTreeForType(params.get(paramName), make);
283             VariableTree parameter = make.Variable(
284                     make.Modifiers(
285                     Collections.<Modifier>emptySet(),
286                     Collections.<AnnotationTree>emptyList()
287                     ),
288                     paramName, // name
289
paramType, // parameter type
290
null // initializer - does not make sense in parameters.
291
);
292             paramList.add(parameter);
293         }
294         MethodTree newMethod = make.Method(
295                 methodModifiers, // public
296
name, // name
297
make.PrimitiveType(TypeKind.VOID), // return type "void"
298
Collections.<TypeParameterTree>emptyList(), // type parameters - none
299
paramList, // final ObjectOutput arg0
300
Collections.<ExpressionTree>emptyList(), // throws
301
"{ throw new UnsupportedOperationException(\"Not supported yet.\") }", // body text
302
null // default value - not applicable here, used by annotations
303
);
304         return newMethod;
305     }
306     
307     public static void addMethod(JavaSource js,
308             final String JavaDoc name,
309             final Map JavaDoc<String JavaDoc,String JavaDoc> params,
310             final String JavaDoc returnType,
311             final Set JavaDoc<Modifier> modifiers) throws IOException JavaDoc {
312         CancellableTask task = new CancellableTask<WorkingCopy>() {
313             public void cancel() {
314                 throw new UnsupportedOperationException JavaDoc("Not supported yet.");
315             }
316             
317             public void run(WorkingCopy workingCopy) throws Exception JavaDoc {
318                 workingCopy.toPhase(Phase.RESOLVED);
319                 CompilationUnitTree cut = workingCopy.getCompilationUnit();
320                 TreeMaker make = workingCopy.getTreeMaker();
321                 ClassTree clazz = null;
322                 for (Tree typeDecl : cut.getTypeDecls()) {
323                     if (Tree.Kind.CLASS == typeDecl.getKind()) {
324                         clazz = (ClassTree) typeDecl;
325                     }
326                 } // end for
327
MethodTree newMethod = createMethod(make, name, params);
328                 newMethod = make.Method(make.Modifiers(modifiers),
329                         newMethod.getName(),
330                         getTreeForType(returnType, make),
331                         newMethod.getTypeParameters(),
332                         newMethod.getParameters(),
333                         newMethod.getThrows(),
334                         newMethod.getBody(),
335                         (ExpressionTree)newMethod.getDefaultValue());
336                 ClassTree modifiedClazz = make.addClassMember(clazz, newMethod);
337                 workingCopy.rewrite(clazz, modifiedClazz);
338             }
339         };
340         js.runModificationTask(task).commit();
341     }
342     
343     public static void addConstructor(JavaSource js, final Map JavaDoc<String JavaDoc,String JavaDoc> params) throws IOException JavaDoc {
344         CancellableTask task = new CancellableTask<WorkingCopy>() {
345             public void cancel() {
346                 throw new UnsupportedOperationException JavaDoc("Not supported yet.");
347             }
348             
349             public void run(WorkingCopy workingCopy) throws Exception JavaDoc {
350                 workingCopy.toPhase(Phase.RESOLVED);
351                 CompilationUnitTree cut = workingCopy.getCompilationUnit();
352                 TreeMaker make = workingCopy.getTreeMaker();
353                 ClassTree clazz = null;
354                 for (Tree typeDecl : cut.getTypeDecls()) {
355                     if (Tree.Kind.CLASS == typeDecl.getKind()) {
356                         clazz = (ClassTree) typeDecl;
357                     }
358                 } // end for
359
MethodTree newMethod = createMethod(make, "<init>", params);
360                 ClassTree modifiedClazz = make.addClassMember(clazz, newMethod);
361                 workingCopy.rewrite(clazz, modifiedClazz);
362             }
363         };
364         js.runModificationTask(task).commit();
365     }
366     
367     public static void removeConstructors(JavaSource js) throws IOException JavaDoc {
368         CancellableTask task = new CancellableTask<WorkingCopy>() {
369             public void cancel() {
370                 throw new UnsupportedOperationException JavaDoc("Not supported yet.");
371             }
372             
373             ClassTree orig;
374             
375             public void run(WorkingCopy workingCopy) throws Exception JavaDoc {
376                 workingCopy.toPhase(Phase.RESOLVED);
377                 CompilationUnitTree cut = workingCopy.getCompilationUnit();
378                 TreeMaker make = workingCopy.getTreeMaker();
379                 ClassTree clazz = null;
380                 for (Tree typeDecl : cut.getTypeDecls()) {
381                     if (Tree.Kind.CLASS == typeDecl.getKind()) {
382                         clazz = (ClassTree) typeDecl;
383                     }
384                 } // end for
385
orig = clazz;
386                 for(Tree el : clazz.getMembers()) {
387                     if(el.getKind().equals(Kind.METHOD)) {
388                         MethodTree method = (MethodTree) el;
389                         if(method.getName().toString().equals("<init>")) {
390                             clazz = make.removeClassMember(clazz, method);
391                         }
392                         
393                     }
394                 }
395                 workingCopy.rewrite(orig, clazz);
396             }
397         };
398         js.runModificationTask(task).commit();
399     }
400     
401     public static void addInitializer(JavaSource js, final boolean isStatic) throws IOException JavaDoc {
402         CancellableTask task = new CancellableTask<WorkingCopy>() {
403             public void cancel() {
404                 throw new UnsupportedOperationException JavaDoc("Not supported yet.");
405             }
406             
407             public void run(WorkingCopy workingCopy) throws Exception JavaDoc {
408                 workingCopy.toPhase(Phase.RESOLVED);
409                 CompilationUnitTree cut = workingCopy.getCompilationUnit();
410                 TreeMaker make = workingCopy.getTreeMaker();
411                 ClassTree clazz = null;
412                 for (Tree typeDecl : cut.getTypeDecls()) {
413                     if (Tree.Kind.CLASS == typeDecl.getKind()) {
414                         clazz = (ClassTree) typeDecl;
415                     }
416                 } // end for
417

418                 BlockTree bt = make.Block(Collections.EMPTY_LIST, isStatic);
419                 ClassTree modifiedClazz = make.addClassMember(clazz, bt);
420                 workingCopy.rewrite(clazz,modifiedClazz);
421             }
422         };
423         js.runModificationTask(task).commit();
424     }
425     
426     
427     public static void addExtendImplementClause(JavaSource js,final String JavaDoc superClass,final List JavaDoc<String JavaDoc> ifaces) throws IOException JavaDoc {
428         CancellableTask task = new CancellableTask<WorkingCopy>() {
429             public void cancel() {
430                 throw new UnsupportedOperationException JavaDoc("Not supported yet.");
431             }
432             
433             public void run(WorkingCopy workingCopy) throws Exception JavaDoc {
434                 workingCopy.toPhase(Phase.RESOLVED);
435                 CompilationUnitTree cut = workingCopy.getCompilationUnit();
436                 TreeMaker make = workingCopy.getTreeMaker();
437                 ClassTree clazz = null;
438                 for (Tree typeDecl : cut.getTypeDecls()) {
439                     if (Tree.Kind.CLASS == typeDecl.getKind()) {
440                         clazz = (ClassTree) typeDecl;
441                     }
442                 } // end for
443
ClassTree origClazz = clazz;
444                 for(String JavaDoc iface :ifaces) {
445                     TypeElement element = workingCopy.getElements().getTypeElement(iface);
446                     ExpressionTree implementsClause = implementsClause = make.QualIdent(element);
447                     clazz = make.addClassImplementsClause(clazz, implementsClause);
448                 }
449                 Tree extendsTree = make.QualIdent(workingCopy.getElements().getTypeElement(superClass));
450                 clazz = make.Class(clazz.getModifiers(),
451                         clazz.getSimpleName(),
452                         clazz.getTypeParameters(),
453                         extendsTree,
454                         (List JavaDoc<ExpressionTree>) clazz.getImplementsClause(),
455                         clazz.getMembers());
456                 workingCopy.rewrite(origClazz,clazz);
457             }
458         };
459         js.runModificationTask(task).commit();
460         
461     }
462     
463     /** Creates new Class from package
464      * @param packageName destination
465      * @param className name
466      * @throws Exception
467      * @return
468      */

469     
470     
471     public static void addImport(JavaSource js,final String JavaDoc importText,final boolean isStatic) throws IOException JavaDoc {
472         CancellableTask task = new CancellableTask<WorkingCopy>() {
473             public void cancel() {
474                 throw new UnsupportedOperationException JavaDoc("Not supported yet.");
475             }
476             
477             public void run(WorkingCopy workingCopy) throws Exception JavaDoc {
478                 workingCopy.toPhase(Phase.RESOLVED);
479                 CompilationUnitTree cut = workingCopy.getCompilationUnit();
480                 TreeMaker make = workingCopy.getTreeMaker();
481                 CompilationUnitTree copy = make.addCompUnitImport(cut,make.Import(make.Identifier(importText), isStatic));
482                 workingCopy.rewrite(cut, copy);
483             }
484         };
485         js.runModificationTask(task).commit();
486     }
487     
488     
489     public static void setPackage(JavaSource js, final String JavaDoc pack) throws IOException JavaDoc {
490         CancellableTask task = new CancellableTask<WorkingCopy>() {
491             public void cancel() {
492                 throw new UnsupportedOperationException JavaDoc("Not supported yet.");
493             }
494             
495             public void run(WorkingCopy workingCopy) throws Exception JavaDoc {
496                 workingCopy.toPhase(Phase.RESOLVED);
497                 CompilationUnitTree cut = workingCopy.getCompilationUnit();
498                 TreeMaker make = workingCopy.getTreeMaker();
499                 CompilationUnitTree copy = make.CompilationUnit(make.Identifier(pack),cut.getImports(), cut.getTypeDecls(), cut.getSourceFile());
500                 workingCopy.rewrite(cut, copy);
501             }
502         };
503         js.runModificationTask(task).commit();
504     }
505     
506     public static FileObject createClass(FileObject target, String JavaDoc packageName, String JavaDoc className) throws Exception JavaDoc {
507         DataObject dob = getSystemDO("Templates/Classes", "Class", "java");
508         DataObject mdob = dob.createFromTemplate(org.openide.loaders.DataFolder.findFolder(getFO(target,packageName,null,null)), className);
509         return mdob.getPrimaryFile();
510     }
511     
512     /** Creates new interface from package
513      * @param packageName destination
514      * @param interfaceName name of interface
515      * @throws Exception
516      * @return
517      */

518    /* public static ClassElement createInterface(String packageName, String interfaceName) throws Exception {
519         DataObject dob = getDO("Templates.Classes", "Interface", "java");
520         DataObject mdob = dob.createFromTemplate(org.openide.loaders.DataFolder.findFolder(getFO(packageName,null,null)),interfaceName);
521         SourceCookie cookie = (SourceCookie) mdob.getCookie(SourceCookie.class);
522         ClassElement iface = cookie.getSource().getClasses()[0];
523         return iface;
524     }*/

525     
526     
527     /** Get a file object by name. */
528     public static FileObject getFO(FileObject file, String JavaDoc pkg, String JavaDoc name, String JavaDoc ext) throws Exception JavaDoc {
529         ClassPath cp=ClassPath.getClassPath(file, ClassPath.SOURCE);
530         String JavaDoc nam=(pkg != null && pkg.length() > 0)?pkg:"";
531         nam+=(name != null && name.length() > 0)?".":"";
532         nam=nam.replace('.', '/');
533         nam+=(name != null && name.length() > 0)?name:"";
534         nam+=(ext != null && ext.length() > 0)?"."+ext:"";
535         //check
536
FileObject[] root=cp.getRoots();
537         FileObject ret=cp.findResource(nam);
538         return ret;
539     }
540     
541     /** Get a data object by name. */
542     public static DataObject getSystemDO(String JavaDoc pkg, String JavaDoc name, String JavaDoc ext) throws Exception JavaDoc {
543         return DataObject.find(Repository.getDefault().getDefaultFileSystem().findResource(pkg+"/"+name+"."+ext));
544     }
545     
546     /** Generates SimpleJavaTestSourceEtalon
547      * @param clazz where to generate
548      * @throws Exception
549      */

550     // public static void simpleJavaSourceEtalonGenerator(ClassElement clazz) throws Exception {
551
//
552
// clazz.removeConstructors(clazz.getConstructors());
553
// clazz.addMethod(Common.createMethod("method1", Modifier.PUBLIC | Modifier.STATIC, Type.INT, PARS1));
554
// clazz.addField(Common.createField("field1",Modifier.PUBLIC | Modifier.STATIC, Type.FLOAT));
555
// clazz.addInitializer(Common.createInitializer());
556
// clazz.addMethod(Common.createMethod("method1", Modifier.PUBLIC | Modifier.STATIC, Type.INT, PARS2));
557
// clazz.addField(Common.createField("field2",Modifier.PUBLIC | Modifier.STATIC, Type.INT));
558
// clazz.addConstructor(Common.createConstructor(clazz.getName()));
559
// clazz.addConstructor(Common.createConstructor(clazz.getName(),PARS1));
560
//
561
// clazz.addMethod(Common.createMethod("method1", Modifier.PUBLIC | Modifier.STATIC, Type.INT, PARS3));
562
// clazz.addInitializer(Common.createInitializer());
563
// clazz.addMethod(Common.createMethod("method2", Modifier.PUBLIC | Modifier.STATIC, Type.INT, PARS1));
564
// clazz.addField(Common.createField("field3",Modifier.PUBLIC | Modifier.STATIC, Type.SHORT));
565
// clazz.addConstructor(Common.createConstructor(clazz.getName(),PARS2));
566
// clazz.addMethod(Common.createMethod("method2", Modifier.PUBLIC | Modifier.STATIC, Type.SHORT, PARS2));
567
// clazz.addInitializer(Common.createInitializer());
568
// clazz.addMethod(Common.createMethod("method2", Modifier.PUBLIC | Modifier.STATIC, Type.LONG, PARS3));
569
//
570
// ClassElement innerClass = new ClassElement();
571
//
572
// innerClass.addMethod(Common.createMethod("method2", Modifier.PUBLIC , Type.VOID, PARS3));
573
//
574
// //BUGY
575
// innerClass.setName(Identifier.create("InnerClass","InnerClass"));
576
// innerClass.addField(Common.createField("field2",Modifier.PUBLIC | Modifier.VOLATILE, Type.INT));
577
//
578
//
579
// ClassElement innerIface = new ClassElement();
580
// innerIface.setClassOrInterface(false);
581
//
582
// //BUGY
583
// innerIface.setName(Identifier.create("InnerInterface", "InnerInterface"));
584
// innerIface.addMethod(Common.createEmptyMethod("interfaceMethod"));
585
//
586
// clazz.addClass(innerClass);
587
// clazz.addClass(innerIface);
588
//
589
//
590
// }
591

592     /** Compares two Arrays
593      * @param l
594      * @param r
595      * @return
596      */

597     public static boolean arrayEquals(Object JavaDoc[] l,Object JavaDoc[] r) {
598         if (l.length!=r.length) return false;
599         for (int i=0; i < l.length; i++){
600             if (!l[i].equals(r[i])) return false;
601         }
602         return true;
603     }
604     
605     /** Removes time and author's name
606      * @param result
607      * @return
608      */

609     public static String JavaDoc unify(String JavaDoc result) {
610         int left=result.indexOf("* Created on");
611         int right=result.indexOf('\n',left);
612         if (left > -1)
613             result=result.substring(0,left+"* Created on".length())+result.substring(right);
614         
615         left=result.indexOf("@author");
616         right=result.indexOf('\n',left);
617         if (left > -1)
618             result=result.substring(0,left+"@author".length())+result.substring(right);
619         return result;
620     }
621     
622     /**
623      * @param str
624      * @return
625      */

626     public static String JavaDoc firstCharToUpper(String JavaDoc str) {
627         String JavaDoc first, rest;
628         
629         if( str==null || str.equals("") )
630             return str;
631         
632         first = str.substring(0, 1).toUpperCase();
633         rest = str.substring( 1 );
634         return first+rest;
635     }
636     
637     /**
638      * @param str
639      * @return
640      */

641     public static String JavaDoc firstCharToLower(String JavaDoc str) {
642         String JavaDoc first, rest;
643         
644         if( str==null || str.equals("") )
645             return( str );
646         
647         first = str.substring(0, 1).toLowerCase();
648         rest = str.substring( 1 );
649         
650         return first+rest;
651     }
652     
653     /**
654      * @param declaringClass
655      * @return
656      */

657     // public static MethodElement createEqualsMethod(ClassElement declaringClass) throws Exception {
658
// MethodParameter parameter=new MethodParameter("obj", Type.createFromClass(java.lang.Object.class), false),
659
// parameters[]=new MethodParameter[1];
660
// FieldElement[] fields=declaringClass.getFields();
661
// String className=declaringClass.getName().getName(),
662
// methodName="equals",
663
// body=cr+" if( obj==null ||"+
664
// cr+" !this.getClass().equals(obj.getClass()) ) return( false );" + cr;
665
// Type returnType=Type.BOOLEAN;
666
//
667
// //set body
668
// if( fields.length>0 )
669
// body += " " + className + " o=(" + className + ") obj;" + cr;
670
// for( int i=0; i<fields.length; i++ ){
671
// Type fieldType=fields[i].getType();
672
// String fieldName=fields[i].getName().getName(),
673
// typeName=fieldType.getSourceString();
674
//
675
// if( fieldType.isPrimitive() )
676
// body += " if( this." + fieldName + "!=o." + fieldName + " ) return( false );" + cr;
677
// else
678
// body += " if( !this." + fieldName + ".equals(o." + fieldName + ") ) return( false );" + cr;
679
// }
680
// body += " return( true );" + cr;
681
//
682
// parameters[0] = parameter;
683
// return( createMethod(declaringClass, methodName, parameters, null, body, returnType) );
684
// }
685
//
686
// /**
687
// * @param className
688
// * @param classModifiers
689
// * @return
690
// */
691
// public static ClassElement createClassElement(String className,int classModifiers) throws Exception {
692
// ClassElement clazz=ClassElement.forName(className);
693
//
694
// if( clazz==null ){
695
// int index=className.lastIndexOf('.');
696
// String sourceName=index==-1?className:className.substring(index+1);
697
//
698
// clazz = new ClassElement();
699
//
700
// //calls of member element
701
// clazz.setName( Identifier.create(className, sourceName) );
702
// clazz.setModifiers( classModifiers );
703
//
704
// //calls of class element
705
// clazz.addConstructor( createConstructor(className) );
706
// //clazz.addClass( null );
707
// //clazz.addInitializer( null );
708
// //clazz.addInterface( null );
709
// clazz.setClassOrInterface( true );
710
// clazz.setSuperclass( null );
711
// pw.println( "created ClassElement "+clazz.getName().getFullName() );
712
// }
713
// else
714
// clazz = (ClassElement) clazz.clone();
715
//
716
// return( clazz );
717
// }
718
//
719

720     public static VariableTree createField(TreeMaker make,String JavaDoc name,Set JavaDoc<Modifier> modifiers, String JavaDoc type) {
721         Tree fieldType = getTreeForType(type, make);
722         VariableTree vt = make.Variable(
723                 make.Modifiers(modifiers),
724                 name,
725                 fieldType,
726                 null);
727         return vt;
728     }
729     
730     
731     public static void addField(JavaSource js, final String JavaDoc name, final Set JavaDoc<Modifier> modifiers, final String JavaDoc type) throws IOException JavaDoc {
732         CancellableTask task = new CancellableTask<WorkingCopy>() {
733             public void cancel() {
734                 throw new UnsupportedOperationException JavaDoc("Not supported yet.");
735             }
736             
737             public void run(WorkingCopy workingCopy) throws Exception JavaDoc {
738                 workingCopy.toPhase(Phase.RESOLVED);
739                 CompilationUnitTree cut = workingCopy.getCompilationUnit();
740                 TreeMaker make = workingCopy.getTreeMaker();
741                 ClassTree clazz = null;
742                 for (Tree typeDecl : cut.getTypeDecls()) {
743                     if (Tree.Kind.CLASS == typeDecl.getKind()) {
744                         clazz = (ClassTree) typeDecl;
745                     }
746                 } // end for
747
VariableTree vt = createField(make, name, modifiers, type);
748                 ClassTree modifiedClazz = make.addClassMember(clazz, vt);
749                 workingCopy.rewrite(clazz, modifiedClazz);
750             }
751         };
752         js.runModificationTask(task).commit();
753     }
754     
755     
756     public static ClassTree getClassTree(
757             TreeMaker make,
758             WorkingCopy workingCopy,
759             String JavaDoc name,
760             String JavaDoc superClass,
761             List JavaDoc<ExpressionTree> implementsList,
762             Set JavaDoc<Modifier> modifiers) {
763             
764         Tree extendsTree = make.QualIdent(workingCopy.getElements().getTypeElement(superClass));
765         Map JavaDoc<String JavaDoc,String JavaDoc> params = new HashMap JavaDoc<String JavaDoc, String JavaDoc>();
766         params.put("param1", "String");
767         MethodTree mt = Common.createMethod(make, "method", params);
768         VariableTree vt = Common.createField(make, "variable", EnumSet.of(Modifier.PROTECTED), "double");
769         List JavaDoc<Tree> members = new ArrayList JavaDoc<Tree>();
770         members.add(mt);
771         members.add(vt);
772         members.add(make.Block(Collections.EMPTY_LIST, false));
773         ClassTree innerClass = make.Class(
774                 make.Modifiers(modifiers),
775                 name,
776                 Collections.EMPTY_LIST,
777                 extendsTree,
778                 implementsList,
779                 members);
780         return innerClass;
781     }
782     
783     public static void addTopLevelClass(JavaSource js) throws IOException JavaDoc {
784         CancellableTask task = new CancellableTask<WorkingCopy>() {
785             public void cancel() {
786                 throw new UnsupportedOperationException JavaDoc("Not supported yet.");
787             }
788             
789             public void run(WorkingCopy workingCopy) throws Exception JavaDoc {
790                 workingCopy.toPhase(Phase.RESOLVED);
791                 CompilationUnitTree cut = workingCopy.getCompilationUnit();
792                 TreeMaker make = workingCopy.getTreeMaker();
793                 ClassTree clazz = getClassTree(make, workingCopy, "TopLevel", "java.util.List", Collections.<ExpressionTree>emptyList(), EnumSet.noneOf(Modifier.class));
794                 CompilationUnitTree copy = make.addCompUnitTypeDecl(cut, clazz);
795
796                 workingCopy.rewrite(cut, copy);
797             }
798         };
799         js.runModificationTask(task).commit();
800     }
801     
802     
803     
804     public static void addClassComment(JavaSource js, final String JavaDoc text) throws IOException JavaDoc {
805         CancellableTask task = new CancellableTask<WorkingCopy>() {
806             public void cancel() {
807                 throw new UnsupportedOperationException JavaDoc("Not supported yet.");
808             }
809             
810             public void run(WorkingCopy workingCopy) throws Exception JavaDoc {
811                 workingCopy.toPhase(Phase.RESOLVED);
812                 CompilationUnitTree cut = workingCopy.getCompilationUnit();
813                 TreeMaker make = workingCopy.getTreeMaker();
814                 ClassTree clazz = null;
815                 for (Tree typeDecl : cut.getTypeDecls()) {
816                     if (Tree.Kind.CLASS == typeDecl.getKind()) {
817                         clazz = (ClassTree) typeDecl;
818                     }
819                 } // end for
820

821             }
822         };
823         js.runModificationTask(task).commit();
824     }
825     
826     
827     // /**
828
// * @param className
829
// * @return
830
// */
831
// public static ClassElement createClassElement(String className) throws Exception {
832
// String fullOidClassName=className+".Oid";
833
// ClassElement clazz=createClassElement(className, Modifier.PUBLIC),
834
// oidClass;
835
//
836
// if( clazz.getClass(Identifier.create(fullOidClassName))==null ){
837
// oidClass = createClassElement( fullOidClassName, Modifier.PUBLIC | Modifier.STATIC );
838
// clazz.addClass( oidClass );
839
// }
840
//
841
// return ( clazz );
842
// }
843
//
844
// /**
845
// * @return
846
// */
847
// public static ClassElement createDepartment(String packageName) throws Exception {
848
// ClassElement clazz=createClassElement(createQualifiedClassName(packageName,"Department"));
849
//
850
// if( clazz!=null ){
851
// createField( clazz, "deptid", Type.parse("int"), true );
852
// createField( clazz, "name", Type.parse("String"), false );
853
// }
854
//
855
// return clazz;
856
// }
857
//
858
// /**
859
// * @return
860
// */
861
// public static ClassElement createEmployee(String packageName) throws Exception {
862
// ClassElement clazz=createClassElement(createQualifiedClassName(packageName,"Employee"));
863
//
864
// if( clazz!=null ){
865
// createField( clazz, "empid", Type.parse("int"), true );
866
// createField( clazz, "lastName", Type.parse("String"), false );
867
// createField( clazz, "firstName", Type.parse("String"), false );
868
// createField( clazz, "hireDate", Type.parse("java.util.Date"), false );
869
// createField( clazz, "birthDate", Type.parse("java.util.Date"), false );
870
// createField( clazz, "salary", Type.parse("double"), false );
871
// }
872
//
873
// return clazz;
874
// }
875
//
876
// /**
877
// * @param declaringClass
878
// * @param field
879
// * @return
880
// */
881
// public static MethodElement createGetterMethod(ClassElement declaringClass,FieldElement field) throws Exception {
882
// String fieldName=field.getName().getName(),
883
// methodName="get"+firstCharToUpper(fieldName),
884
// body=cr+" return "+fieldName+";"+cr;
885
//
886
// return( createMethod(declaringClass, methodName, null, null, body, field.getType()) );
887
// }
888
//
889
// /**
890
// * @param declaringClass
891
// * @return
892
// */
893
// public static MethodElement createHashCodeMethod(ClassElement declaringClass) throws Exception {
894
// FieldElement[] fields=declaringClass.getFields();
895
// String className=declaringClass.getName().getName(),
896
// methodName="hashCode",
897
// body=cr+" int hashCode=0;" + cr;
898
// Type returnType=Type.INT;
899
//
900
// //set body
901
// for( int i=0; i<fields.length; i++ ){
902
// FieldElement field=fields[i];
903
// Type fieldType=fields[i].getType();
904
// String fieldName=fields[i].getName().getName(),
905
// typeName=fieldType.getSourceString();
906
//
907
// if( fieldType.isPrimitive() ){
908
// if( typeName.equals("boolean") )
909
// body += " hashCode += new Boolean(" + fieldName + ").hashCode();" + cr;
910
// else if( typeName.equals("char") )
911
// body += " hashCode += new Character(" + fieldName + ").hashCode();" + cr;
912
// else
913
// body += " hashCode += " + fieldName + ";" + cr;
914
// }
915
// else
916
// body += " hashCode += " + fieldName + ".hashCode();" + cr;
917
// }
918
// body += " return( hashCode );" + cr;
919
//
920
// return( createMethod(declaringClass, methodName, null, null, body, returnType) );
921
// }
922
//
923
// /**
924
// * @param declaringClass
925
// * @param fieldName
926
// * @param fieldType
927
// * @param isOidField
928
// * @return
929
// */
930
// public static FieldElement createField(ClassElement declaringClass,String fieldName,Type fieldType,boolean isOidField) throws Exception {
931
//
932
// FieldElement field=createField(declaringClass, fieldName, fieldType, Modifier.PRIVATE);
933
//
934
// //getter/setter methods
935
// createGetterMethod( declaringClass, field );
936
// createSetterMethod( declaringClass, field );
937
//
938
// if( isOidField ) {
939
// Identifier identifier=Identifier.create(declaringClass.getName().getFullName()+".Oid");
940
// ClassElement oidClass=declaringClass.getClass(identifier);
941
//
942
// createField( oidClass, fieldName, fieldType, Modifier.PUBLIC );
943
// createEqualsMethod( oidClass );
944
// createHashCodeMethod( oidClass );
945
// }
946
//
947
// return( field );
948
// }
949

950     /**
951      * @param declaringClass
952      * @param methodName
953      * @param parameters
954      * @param exceptions
955      * @param body
956      * @param returnType
957      * @return
958      */

959     // public static MethodElement createMethod(ClassElement declaringClass,String methodName,MethodParameter[] parameters,Identifier[] exceptions,String body,Type returnType) throws Exception {
960
// Identifier id=Identifier.create(methodName);
961
// MethodElement method;
962
// Type[] types=parameters==null?null:new Type[parameters.length];
963
// int methodModifiers=Modifier.PUBLIC;
964
//
965
// if( parameters!=null )
966
// for( int i=0; i<parameters.length; i++ )
967
// types[i] = parameters[i].getType();
968
//
969
// method = declaringClass.getMethod( id, types );
970
// if( method!=null )
971
// declaringClass.removeMethod( method );
972
//
973
// //create new method
974
// method = new MethodElement();
975
//
976
// //calls of member element
977
// method.setName( id );
978
// method.setModifiers( methodModifiers );
979
//
980
// //calls of constructor element
981
// if( parameters!=null )
982
// method.setParameters( parameters );
983
// if( exceptions!=null )
984
// method.setExceptions( exceptions );
985
// method.setBody( body );
986
//
987
// //calls of method element
988
// method.setReturn( returnType );
989
//
990
// //set context
991
// //method.setDeclaringClass( declaringClass );
992
// declaringClass.addMethod( method );
993
//
994
// return( method );
995
// }
996
//
997
// /**
998
// * @return
999
// */
1000
// public static java.util.Vector createObjects(String packageName) throws Exception {
1001
// java.util.Vector objects = new java.util.Vector();
1002
// ClassElement clazz;
1003
//
1004
// clazz = createDepartment(packageName);
1005
// if( clazz!=null ){
1006
// objects.addElement( clazz );
1007
// }
1008
//
1009
// clazz = createEmployee(packageName);
1010
//
1011
// if( clazz!=null ){
1012
// objects.addElement( clazz );
1013
// }
1014
//
1015
// return objects;
1016
// }
1017
//
1018
// /**
1019
// * @param className
1020
// * @return
1021
// */
1022
//
1023
// public static String createQualifiedClassName(String packageName, String className) {
1024
// String qualifiedClassName;
1025
// int index=className.lastIndexOf('.');
1026
//
1027
// if( index!=-1 ||
1028
// packageName==null ||
1029
// packageName.equals("") )
1030
// return className;
1031
//
1032
// return packageName+"."+className;
1033
// }
1034

1035    
1036    /**
1037     * @param declaringClass
1038     * @param field
1039     * @return
1040     */

1041    // public static MethodElement createSetterMethod(ClassElement declaringClass,FieldElement field) throws Exception {
1042
// String fieldName=field.getName().getName(),
1043
// methodName="set"+firstCharToUpper(fieldName),
1044
// body=cr+" this. "+fieldName+" = "+fieldName+";" + cr;
1045
// Type returnType=Type.VOID;
1046
// MethodParameter parameter=new MethodParameter(fieldName, field.getType(), false),
1047
// parameters[]= new MethodParameter[1];
1048
//
1049
// parameters[0] = parameter;
1050
// return( createMethod(declaringClass, methodName, parameters, null, body, returnType) );
1051
// }
1052

1053    /*public static org.openide.src.SourceElement createSource(String packageName, String className) throws Exception {
1054        return createClass(packageName, className).getSource();
1055    }*/

1056    
1057}
1058
Popular Tags