KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > google > gwt > junit > tools > JUnitCreator


1 /*
2  * Copyright 2006 Google Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5  * use this file except in compliance with the License. You may obtain a copy of
6  * the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13  * License for the specific language governing permissions and limitations under
14  * the License.
15  */

16 package com.google.gwt.junit.tools;
17
18 import com.google.gwt.user.tools.util.ArgHandlerEclipse;
19 import com.google.gwt.user.tools.util.ArgHandlerIgnore;
20 import com.google.gwt.user.tools.util.ArgHandlerOverwrite;
21 import com.google.gwt.util.tools.ArgHandlerExtra;
22 import com.google.gwt.util.tools.ArgHandlerOutDir;
23 import com.google.gwt.util.tools.ArgHandlerString;
24 import com.google.gwt.util.tools.ToolBase;
25 import com.google.gwt.util.tools.Utility;
26
27 import java.io.File JavaDoc;
28 import java.io.IOException JavaDoc;
29 import java.util.HashMap JavaDoc;
30 import java.util.Map JavaDoc;
31
32 /**
33  * Tool to create JUnit test case.
34  *
35  */

36 public final class JUnitCreator extends ToolBase {
37
38   /**
39    * Arg Handler for <code>JUnitCreator</code>.
40    */

41   protected class ArgHandlerTestClass extends ArgHandlerExtra {
42
43     public boolean addExtraArg(String JavaDoc arg) {
44       if (fullClassName != null) {
45         System.err.println("Too many arguments.");
46         return false;
47       }
48
49       // Check className for certain properties
50
if (!arg.matches("[\\w\\$]+(\\.[\\w\\$]+)+")) {
51         System.err.println("'"
52             + arg
53             + "' does not appear to be a valid fully-qualified Java class name.");
54         return false;
55       }
56
57       // Check out the class name.
58
//
59
if (arg.indexOf('$') != -1) {
60         System.err.println("'" + arg
61             + "': This version of the tool does not support nested classes");
62         return false;
63       }
64
65       String JavaDoc[] parts = arg.split("\\.");
66       if (parts.length < 2) {
67         System.err.println("'" + arg
68             + "': Cannot live in the root package. Please specify a package.");
69         return false;
70       }
71
72       fullClassName = arg;
73       return true;
74     }
75
76     public String JavaDoc getPurpose() {
77       return "The fully-qualified name of the test class to create";
78     }
79
80     public String JavaDoc[] getTagArgs() {
81       return new String JavaDoc[] {"className"};
82     }
83
84     public boolean isRequired() {
85       return true;
86     }
87   }
88
89   private static final String JavaDoc PACKAGE_PATH;
90
91   static {
92     String JavaDoc path = JUnitCreator.class.getName();
93     path = path.substring(0, path.lastIndexOf('.') + 1);
94     PACKAGE_PATH = path.replace('.', '/');
95   }
96
97   public static void main(String JavaDoc[] args) {
98     JUnitCreator creator = new JUnitCreator();
99     if (creator.processArgs(args)) {
100       if (creator.run()) {
101         return;
102       }
103     }
104
105     System.exit(1);
106   }
107
108   /**
109    * @param junitPath the path to the user's junit jar
110    * @param moduleName the name of the module to contain this test
111    * @param fullClassName Name of the fully-qualified Java class to create as an
112    * Application.
113    * @param outDir Where to put the output files
114    * @param eclipse The name of a project to attach a .launch config to
115    * @param overwrite Overwrite an existing files if they exist.
116    * @param ignore Ignore existing files if they exist.
117    * @throws IOException
118    */

119   static void createTest(String JavaDoc junitPath, String JavaDoc moduleName,
120       String JavaDoc fullClassName, File JavaDoc outDir, String JavaDoc eclipse, boolean overwrite,
121       boolean ignore) throws IOException JavaDoc {
122
123     // Figure out the installation directory
124
String JavaDoc installPath = Utility.getInstallPath();
125     String JavaDoc gwtUserPath = installPath + '/' + "gwt-user.jar";
126     String JavaDoc gwtDevPath = installPath + '/' + Utility.getDevJarName();
127
128     // Figure out what platform we're on
129
//
130
boolean isWindows = gwtDevPath.substring(gwtDevPath.lastIndexOf('/') + 1).indexOf(
131         "windows") >= 0;
132     boolean isMacOsX = gwtDevPath.substring(gwtDevPath.lastIndexOf('/') + 1).indexOf(
133         "mac") >= 0;
134
135     // If the path from here to the install directory is relative, we need to
136
// set specific "base" directory tags; this is for sample generation during
137
// the build.
138
String JavaDoc basePathEnv;
139     if (!new File JavaDoc(installPath).isAbsolute()) {
140       if (isWindows) {
141         basePathEnv = "%~dp0\\";
142       } else {
143         basePathEnv = "$APPDIR/";
144       }
145     } else {
146       basePathEnv = "";
147     }
148
149     // Check if junit path is absolute, add base if needed
150
if (!new File JavaDoc(junitPath).isAbsolute()
151         && junitPath.charAt(0) != File.separatorChar) {
152       if (isWindows) {
153         junitPath = "%~dp0\\" + junitPath;
154       } else {
155         junitPath = "$APPDIR/" + junitPath;
156       }
157     }
158
159     // Check out the class and package names.
160
//
161
int pos = fullClassName.lastIndexOf('.');
162     String JavaDoc clientPackageName = fullClassName.substring(0, pos);
163     String JavaDoc className = fullClassName.substring(pos + 1);
164
165     // Is the requested moduleName in a parent package of the clientPackage?
166
//
167
pos = moduleName.lastIndexOf('.');
168     if (pos >= 0) {
169       String JavaDoc modulePackageName = moduleName.substring(0, pos);
170       if (modulePackageName.length() == clientPackageName.length()
171           || !clientPackageName.startsWith(modulePackageName + '.')) {
172         System.err.println("Warning: '" + modulePackageName
173             + "' is not a parent package of '" + clientPackageName
174             + "'. The source for '" + className + "' may be unavailable.");
175       }
176     }
177
178     // Compute module name and directories
179
//
180
pos = clientPackageName.lastIndexOf('.');
181     File JavaDoc clientDir = Utility.getDirectory(outDir, "test", true);
182     if (pos >= 0) {
183       String JavaDoc clientPackage = clientPackageName.replace('.', '/');
184       clientDir = Utility.getDirectory(clientDir, clientPackage, true);
185     }
186
187     // Create a map of replacements
188
//
189
Map JavaDoc replacements = new HashMap JavaDoc();
190     replacements.put("@className", className);
191     replacements.put("@moduleName", moduleName);
192     replacements.put("@clientPackage", clientPackageName);
193     replacements.put("@junitPath", junitPath);
194     replacements.put("@gwtUserPath", basePathEnv + gwtUserPath);
195     replacements.put("@gwtDevPath", basePathEnv + gwtDevPath);
196     replacements.put("@vmargs", isMacOsX ? "-XstartOnFirstThread" : "");
197
198     {
199       // Create a skeleton Test class
200
File JavaDoc javaClass = Utility.createNormalFile(clientDir, className + ".java",
201           overwrite, ignore);
202       if (javaClass != null) {
203         String JavaDoc out = Utility.getFileFromClassPath(PACKAGE_PATH
204             + "JUnitClassTemplate.javasrc");
205         Utility.writeTemplateFile(javaClass, out, replacements);
206       }
207     }
208
209     if (eclipse != null) {
210       // Create an eclipse launch config
211
replacements.put("@projectName", eclipse);
212       File JavaDoc hostedConfig = Utility.createNormalFile(outDir, className
213           + "-hosted.launch", overwrite, ignore);
214       if (hostedConfig != null) {
215         String JavaDoc out = Utility.getFileFromClassPath(PACKAGE_PATH
216             + "JUnit-hosted.launchsrc");
217         Utility.writeTemplateFile(hostedConfig, out, replacements);
218       }
219
220       File JavaDoc webConfig = Utility.createNormalFile(outDir, className
221           + "-web.launch", overwrite, ignore);
222       if (webConfig != null) {
223         String JavaDoc out = Utility.getFileFromClassPath(PACKAGE_PATH
224             + "JUnit-web.launchsrc");
225         Utility.writeTemplateFile(webConfig, out, replacements);
226       }
227     }
228
229     // create startup files
230
String JavaDoc extension;
231     if (isWindows) {
232       extension = ".cmd";
233     } else {
234       extension = "";
235     }
236
237     File JavaDoc junitHosted = Utility.createNormalFile(outDir, className + "-hosted"
238         + extension, overwrite, ignore);
239     if (junitHosted != null) {
240       String JavaDoc out = Utility.getFileFromClassPath(PACKAGE_PATH + "junit-hosted"
241           + extension + "src");
242       Utility.writeTemplateFile(junitHosted, out, replacements);
243       if (extension.length() == 0) {
244         Runtime.getRuntime().exec("chmod u+x " + junitHosted.getAbsolutePath());
245       }
246     }
247
248     File JavaDoc junitWeb = Utility.createNormalFile(outDir, className + "-web"
249         + extension, overwrite, ignore);
250     if (junitWeb != null) {
251       String JavaDoc out = Utility.getFileFromClassPath(PACKAGE_PATH + "junit-web"
252           + extension + "src");
253       Utility.writeTemplateFile(junitWeb, out, replacements);
254       if (extension.length() == 0) {
255         Runtime.getRuntime().exec("chmod u+x " + junitWeb.getAbsolutePath());
256       }
257     }
258   }
259
260   private String JavaDoc eclipse = null;
261
262   private String JavaDoc fullClassName = null;
263
264   private boolean ignore = false;
265   private String JavaDoc junitPath = null;
266   private String JavaDoc moduleName = null;
267   private File JavaDoc outDir;
268   private boolean overwrite = false;
269
270   protected JUnitCreator() {
271
272     registerHandler(new ArgHandlerString() {
273
274       public String JavaDoc[] getDefaultArgs() {
275         return null;
276       }
277
278       public String JavaDoc getPurpose() {
279         return "Specify the path to your junit.jar (required)";
280       }
281
282       public String JavaDoc getTag() {
283         return "-junit";
284       }
285
286       public String JavaDoc[] getTagArgs() {
287         return new String JavaDoc[] {"pathToJUnitJar"};
288       }
289
290       public boolean isRequired() {
291         return true;
292       }
293
294       public boolean setString(String JavaDoc str) {
295         File JavaDoc f = new File JavaDoc(str);
296         if (!f.exists() || !f.isFile()) {
297           System.err.println("File not found: " + str);
298           return false;
299         }
300         junitPath = str;
301         return true;
302       }
303     });
304
305     registerHandler(new ArgHandlerString() {
306
307       public String JavaDoc[] getDefaultArgs() {
308         return null;
309       }
310
311       public String JavaDoc getPurpose() {
312         return "Specify the name of the GWT module to use (required)";
313       }
314
315       public String JavaDoc getTag() {
316         return "-module";
317       }
318
319       public String JavaDoc[] getTagArgs() {
320         return new String JavaDoc[] {"moduleName"};
321       }
322
323       public boolean isRequired() {
324         return true;
325       }
326
327       public boolean setString(String JavaDoc str) {
328         moduleName = str;
329         return true;
330       }
331     });
332
333     registerHandler(new ArgHandlerEclipse() {
334       public String JavaDoc getPurpose() {
335         return "Creates a debug launch config for the named eclipse project";
336       }
337
338       public boolean setString(String JavaDoc str) {
339         eclipse = str;
340         return true;
341       }
342     });
343
344     registerHandler(new ArgHandlerOutDir() {
345
346       public void setDir(File JavaDoc dir) {
347         outDir = dir;
348       }
349     });
350
351     registerHandler(new ArgHandlerOverwrite() {
352
353       public boolean setFlag() {
354         if (ignore) {
355           System.err.println("-overwrite cannot be used with -ignore.");
356           return false;
357         }
358         overwrite = true;
359         return true;
360       }
361     });
362
363     registerHandler(new ArgHandlerIgnore() {
364
365       public boolean setFlag() {
366         if (overwrite) {
367           System.err.println("-ignore cannot be used with -overwrite.");
368           return false;
369         }
370         ignore = true;
371         return true;
372       }
373     });
374
375     registerHandler(new ArgHandlerTestClass());
376   }
377
378   protected boolean run() {
379     try {
380       createTest(junitPath, moduleName, fullClassName, outDir, eclipse,
381           overwrite, ignore);
382       return true;
383     } catch (IOException JavaDoc e) {
384       System.err.println(e.getClass().getName() + ": " + e.getMessage());
385       return false;
386     }
387   }
388 }
389
Popular Tags