KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > form > layoutdesign > LayoutTestUtils


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.form.layoutdesign;
21
22 import com.sun.source.tree.ClassTree;
23 import com.sun.source.tree.ExpressionTree;
24 import com.sun.source.tree.MethodTree;
25 import com.sun.source.tree.TypeParameterTree;
26 import com.sun.source.tree.VariableTree;
27 import java.awt.Rectangle JavaDoc;
28 import java.io.FileWriter JavaDoc;
29 import java.io.IOException JavaDoc;
30 import java.io.InputStream JavaDoc;
31 import java.io.InputStreamReader JavaDoc;
32 import java.io.LineNumberReader JavaDoc;
33 import java.util.Collection JavaDoc;
34 import java.util.Collections JavaDoc;
35 import java.util.EnumSet JavaDoc;
36 import java.util.Iterator JavaDoc;
37 import java.util.List JavaDoc;
38 import java.util.Map JavaDoc;
39 import javax.lang.model.element.Modifier;
40 import javax.lang.model.element.TypeElement;
41 import javax.lang.model.type.TypeKind;
42 import org.netbeans.api.java.classpath.ClassPath;
43 import org.netbeans.api.java.source.CancellableTask;
44 import org.netbeans.api.java.source.CompilationController;
45 import org.netbeans.api.java.source.JavaSource;
46 import org.netbeans.api.java.source.TreeMaker;
47 import org.netbeans.api.java.source.WorkingCopy;
48 import org.netbeans.modules.form.FormDataObject;
49 import org.netbeans.modules.form.FormDesigner;
50 import org.openide.awt.StatusDisplayer;
51 import org.openide.filesystems.FileObject;
52 import org.openide.filesystems.FileUtil;
53 import org.openide.loaders.DataObject;
54 import org.openide.util.Utilities;
55
56 /**
57  * This class collects various static methods for examining the layout.
58  * For modifying methods see LayoutOperations class.
59  *
60  * @author Martin Grebac
61  */

62
63 public class LayoutTestUtils implements LayoutConstants {
64     
65     static void writeString(List JavaDoc codeList, String JavaDoc name, String JavaDoc value) {
66         if (value != null) {
67             codeList.add("String " + name + "= \"" + value + "\";"); //NOI18N
68
} else {
69             codeList.add("String " + name + " = null;"); //NOI18N
70
}
71     }
72
73     static void writeLayoutComponentArray(List JavaDoc codeList, String JavaDoc arrayName, String JavaDoc lcName) {
74         codeList.add("LayoutComponent[] " + arrayName + " = new LayoutComponent[] { " + lcName + " };"); //NOI18N
75
}
76     
77     static void writeCollection(List JavaDoc codeList, String JavaDoc name, Collection JavaDoc c) {
78         codeList.add("Collection " + name + " = new ArrayList();"); //NOI18N
79
Iterator JavaDoc i = c.iterator();
80         while (i.hasNext()) {
81             codeList.add(name + ".add(\"" + (String JavaDoc)i.next() + "\");"); // NOI18N
82
}
83     }
84
85     static void writeStringArray(List JavaDoc codeList, String JavaDoc name, String JavaDoc[] compIds) {
86         codeList.add("String[] " + name + " = new String[] {"); //NOI18N
87
for (int i=0; i < compIds.length; i++) {
88             codeList.add("\"" + compIds[i] + "\"" + (i+1 < compIds.length ? "," : "")); // NOI18N
89
}
90         codeList.add("};"); //NOI18N
91
}
92
93     static void writeIntArray(List JavaDoc codeList, String JavaDoc name, int[] values) {
94         codeList.add("int[] " + name + " = new int[] {"); //NOI18N
95
for (int i=0; i < values.length; i++) {
96             codeList.add(Integer.toString(values[i]) + (i+1 < values.length ? "," : "")); // NOI18N
97
}
98         codeList.add("};"); //NOI18N
99
}
100     
101     static void writeRectangleArray(List JavaDoc codeList, String JavaDoc name, Rectangle JavaDoc[] bounds) {
102         codeList.add("Rectangle[] " + name + " = new Rectangle[] {"); //NOI18N
103
for (int i=0; i < bounds.length; i++) {
104             codeList.add("new Rectangle(" + bounds[i].x + ", " // NOI18N
105
+ bounds[i].y + ", " // NOI18N
106
+ bounds[i].width + ", " // NOI18N
107
+ bounds[i].height + (i+1 < bounds.length ? "), " : ")")); // NOI18N
108
}
109         codeList.add("};"); // NOI18N
110
}
111     
112     static void dumpTestcode(List JavaDoc codeList, DataObject form, final int modelCounter) {
113         FileWriter JavaDoc fw = null;
114         StringBuffer JavaDoc template = new StringBuffer JavaDoc();
115         
116         if (form == null) return;
117         try {
118
119             FileObject primaryFile = form.getPrimaryFile();
120
121             //Read the template for test class
122
InputStream JavaDoc in = LayoutTestUtils.class.getResourceAsStream("/org/netbeans/modules/form/resources/LayoutModelAutoTest_template"); //NOI18N
123
LineNumberReader JavaDoc lReader = new LineNumberReader JavaDoc(new InputStreamReader JavaDoc(in));
124             while (lReader.ready()) {
125                 template.append(lReader.readLine()).append('\n');
126             }
127             lReader.close();
128
129             //Get the code into one string
130
final StringBuffer JavaDoc code = new StringBuffer JavaDoc();
131             Iterator JavaDoc i = codeList.iterator();
132             while (i.hasNext()) {
133                 String JavaDoc line = (String JavaDoc)i.next();
134                 code.append(line).append('\n');
135             }
136         
137             //Find a name for the test file
138
ClassPath cpath = ClassPath.getClassPath(primaryFile, ClassPath.SOURCE);
139             final String JavaDoc primaryFileClassFQN = cpath.getResourceName(primaryFile, '.', false);
140             final boolean[] resolved = new boolean[1];
141             JavaSource js = JavaSource.forFileObject(primaryFile);
142             js.runUserActionTask(new CancellableTask<CompilationController>() {
143                 public void cancel() {
144                 }
145                 public void run(CompilationController controller) throws Exception JavaDoc {
146                     controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
147                     TypeElement clazz = controller.getElements().getTypeElement(primaryFileClassFQN);
148                     resolved[0] = clazz != null;
149                 }
150             }, true);
151             
152             if (!resolved[0]) return;
153             
154             String JavaDoc testClassName = primaryFile.getName() + "Test"; //NOI18N
155

156             FileObject testFO = primaryFile.getParent().getFileObject(testClassName, "java");//NOI18N
157
if (testFO == null) {
158                 testFO = primaryFile.getParent().createData(testClassName, "java"); //NOI18N
159

160                 //Rename the class in template to correct class name
161
String JavaDoc output = Utilities.replaceString(template.toString(), "${CLASS_NAME}", testFO.getName()); //NOI18N
162

163                 //Write the file to disc
164
fw = new FileWriter JavaDoc(FileUtil.toFile(testFO));
165                 fw.write(output);
166                 fw.close();
167             }
168
169             //8. Add the method to test class
170
final String JavaDoc testClassFQN = "org.netbeans.modules.form.layoutdesign." + testFO.getName(); //NOI18N
171
js = JavaSource.forFileObject(testFO);
172             js.runModificationTask(new CancellableTask<WorkingCopy>() {
173                 public void cancel() {
174                 }
175                 public void run(WorkingCopy wcopy) throws Exception JavaDoc {
176                     wcopy.toPhase(JavaSource.Phase.RESOLVED);
177                     
178                     TypeElement classElm = wcopy.getElements().getTypeElement(testClassFQN);
179                     if (classElm != null) {
180                         ClassTree classTree = wcopy.getTrees().getTree(classElm);
181                         TreeMaker make = wcopy.getTreeMaker();
182                         MethodTree method = make.Method(
183                                 make.Modifiers(EnumSet.of(Modifier.PUBLIC)),
184                                 "doChanges" + modelCounter, // NOI18N
185
make.PrimitiveType(TypeKind.VOID),
186                                 Collections.<TypeParameterTree>emptyList(),
187                                 Collections.<VariableTree>emptyList(),
188                                 Collections.<ExpressionTree>emptyList(),
189                                 code.toString(),
190                                 null
191                                 );
192                         ClassTree classCopy = make.addClassMember(classTree, method);
193                         wcopy.rewrite(classTree, classCopy);
194                     }
195                     
196                 }
197             }).commit();
198             
199         } catch (IOException JavaDoc ex) {
200             ex.printStackTrace();
201             return;
202         }
203         
204     }
205     
206     public static FileObject getTargetFolder(FileObject file) {
207     FileObject targetFolder = file.getParent();
208     try {
209         FileObject folder = file.getParent().getParent().getParent().getParent().getParent().getParent().getParent().getFileObject("data/goldenfiles"); //NOI18N
210
if (folder != null) {
211         targetFolder = folder;
212         }
213     } catch (NullPointerException JavaDoc npe) {
214         // just ignore, it means the path doesn't exist
215
}
216     return targetFolder;
217     }
218     
219     public static void writeTest(FormDesigner fd, FormDataObject formDO, Map JavaDoc idToNameMap, LayoutModel lm) {
220     FileObject formFO = formDO.getFormFile();
221
222     fd.getLayoutDesigner().dumpTestcode(formDO);
223
224     FileWriter JavaDoc fw = null;
225     try {
226         FileObject targetFolder = getTargetFolder(formFO);
227         FileObject fo = targetFolder.createData(formFO.getName() + "Test-ExpectedEndModel" + Integer.toString(fd.getLayoutDesigner().getModelCounter()), "txt"); //NOI18N
228
fw = new FileWriter JavaDoc(FileUtil.toFile(fo));
229         fw.write(lm.dump(idToNameMap));
230         StatusDisplayer.getDefault().setStatusText("The test was successfully written: " + fo.getPath()); // NOI18N
231
} catch (IOException JavaDoc ex) {
232         ex.printStackTrace();
233         return;
234     } finally {
235         try {
236         if (fw != null) fw.close();
237         } catch (IOException JavaDoc io) {
238         //TODO
239
}
240     }
241     }
242     
243 }
244
Popular Tags