KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > google > gwt > user > tools > ApplicationCreator


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.user.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.ToolBase;
24 import com.google.gwt.util.tools.Utility;
25
26 import java.io.File JavaDoc;
27 import java.io.IOException JavaDoc;
28 import java.util.HashMap JavaDoc;
29 import java.util.Map JavaDoc;
30
31 /**
32  * Creates a GWT application.
33  *
34  */

35 public final class ApplicationCreator extends ToolBase {
36
37   /**
38    * Arguments for the application creator.
39    *
40    */

41   protected class ArgHandlerAppClass 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("'" + arg
52             + "' does not appear to be a valid fully-qualified Java class name");
53         return false;
54       }
55
56       // Check out the class name.
57
//
58
if (arg.indexOf('$') != -1) {
59         System.err.println("'" + arg
60             + "': This version of the tool does not support nested classes");
61         return false;
62       }
63
64       String JavaDoc[] parts = arg.split("\\.");
65       if (parts.length < 2 || !parts[parts.length - 2].equals("client")) {
66         System.err.println("'"
67             + arg
68             + "': Please use 'client' as the final package, as in 'com.example.foo.client.MyApp'.\n"
69             + "It isn't technically necessary, but this tool enforces the best practice.");
70         return false;
71       }
72
73       fullClassName = arg;
74       return true;
75     }
76
77     public String JavaDoc getPurpose() {
78       return "The fully-qualified name of the application class to create";
79     }
80
81     public String JavaDoc[] getTagArgs() {
82       return new String JavaDoc[] {"className"};
83     }
84
85     public boolean isRequired() {
86       return true;
87     }
88   }
89
90   private static final String JavaDoc PACKAGE_PATH;
91
92   static {
93     String JavaDoc path = ApplicationCreator.class.getName();
94     path = path.substring(0, path.lastIndexOf('.') + 1);
95     PACKAGE_PATH = path.replace('.', '/');
96   }
97
98   public static void main(String JavaDoc[] args) {
99     ApplicationCreator creator = new ApplicationCreator();
100     if (creator.processArgs(args)) {
101       if (creator.run()) {
102         return;
103       }
104     }
105     System.exit(1);
106   }
107
108   /**
109    * @param fullClassName Name of the fully-qualified Java class to create as an
110    * Application.
111    * @param outDir Where to put the output files
112    * @param eclipse The name of a project to attach a .launch config to
113    * @param overwrite Overwrite an existing files if they exist.
114    * @param ignore Ignore existing files if they exist.
115    * @throws IOException
116    */

117   static void createApplication(String JavaDoc fullClassName, File JavaDoc outDir,
118       String JavaDoc eclipse, boolean overwrite, boolean ignore) throws IOException JavaDoc {
119
120     // Figure out the installation directory
121
String JavaDoc installPath = Utility.getInstallPath();
122     String JavaDoc gwtUserPath = installPath + '/' + "gwt-user.jar";
123     String JavaDoc gwtDevPath = installPath + '/' + Utility.getDevJarName();
124
125     // Figure out what platform we're on
126
//
127
boolean isWindows = gwtDevPath.substring(gwtDevPath.lastIndexOf('/') + 1).indexOf(
128         "windows") >= 0;
129     boolean isMacOsX = gwtDevPath.substring(gwtDevPath.lastIndexOf('/') + 1).indexOf(
130         "mac") >= 0;
131
132     // If the path from here to the install directory is relative, we need to
133
// set specific "base" directory tags; this is for sample generation during
134
// the build.
135
String JavaDoc basePathEnv;
136     if (!new File JavaDoc(installPath).isAbsolute()) {
137       if (isWindows) {
138         basePathEnv = "%~dp0\\";
139       } else {
140         basePathEnv = "$APPDIR/";
141       }
142     } else {
143       basePathEnv = "";
144     }
145
146     // Check out the class and package names.
147
//
148
int pos = fullClassName.lastIndexOf('.');
149     String JavaDoc clientPackageName = fullClassName.substring(0, pos);
150     String JavaDoc className = fullClassName.substring(pos + 1);
151
152     // Compute module name and directories
153
//
154
pos = clientPackageName.lastIndexOf('.');
155     File JavaDoc basePackageDir;
156     String JavaDoc moduleName;
157     File JavaDoc javaDir = Utility.getDirectory(outDir, "src", true);
158     if (pos >= 0) {
159       String JavaDoc basePackage = clientPackageName.substring(0, pos);
160       moduleName = basePackage + "." + className;
161       basePackage = basePackage.replace('.', '/');
162       basePackageDir = Utility.getDirectory(javaDir, basePackage, true);
163     } else {
164       moduleName = className;
165       basePackageDir = javaDir;
166     }
167     File JavaDoc clientDir = Utility.getDirectory(basePackageDir, "client", true);
168     File JavaDoc publicDir = Utility.getDirectory(basePackageDir, "public", true);
169     String JavaDoc startupUrl = moduleName + "/" + className + ".html";
170
171     // Create a map of replacements
172
//
173
Map JavaDoc replacements = new HashMap JavaDoc();
174     replacements.put("@className", className);
175     replacements.put("@moduleName", moduleName);
176     replacements.put("@clientPackage", clientPackageName);
177     replacements.put("@gwtUserPath", basePathEnv + gwtUserPath);
178     replacements.put("@gwtDevPath", basePathEnv + gwtDevPath);
179     replacements.put("@shellClass", "com.google.gwt.dev.GWTShell");
180     replacements.put("@compileClass", "com.google.gwt.dev.GWTCompiler");
181     replacements.put("@startupUrl", startupUrl);
182     replacements.put("@vmargs", isMacOsX ? "-XstartOnFirstThread" : "");
183
184     {
185       // Create the module
186
File JavaDoc moduleXML = Utility.createNormalFile(basePackageDir, className
187           + ".gwt.xml", overwrite, ignore);
188       if (moduleXML != null) {
189         String JavaDoc out = Utility.getFileFromClassPath(PACKAGE_PATH
190             + "Module.gwt.xmlsrc");
191         Utility.writeTemplateFile(moduleXML, out, replacements);
192       }
193     }
194
195     {
196       // Create a skeleton html file
197
File JavaDoc publicHTML = Utility.createNormalFile(publicDir,
198           className + ".html", overwrite, ignore);
199       if (publicHTML != null) {
200         String JavaDoc out = Utility.getFileFromClassPath(PACKAGE_PATH
201             + "AppHtml.htmlsrc");
202         Utility.writeTemplateFile(publicHTML, out, replacements);
203       }
204     }
205
206     {
207       // Create a skeleton Application class
208
File JavaDoc javaClass = Utility.createNormalFile(clientDir, className + ".java",
209           overwrite, ignore);
210       if (javaClass != null) {
211         String JavaDoc out = Utility.getFileFromClassPath(PACKAGE_PATH
212             + "AppClassTemplate.javasrc");
213         Utility.writeTemplateFile(javaClass, out, replacements);
214       }
215     }
216
217     if (eclipse != null) {
218       // Create an eclipse launch config
219
replacements.put("@projectName", eclipse);
220       File JavaDoc launchConfig = Utility.createNormalFile(outDir, className
221           + ".launch", overwrite, ignore);
222       if (launchConfig != null) {
223         String JavaDoc out = Utility.getFileFromClassPath(PACKAGE_PATH
224             + "App.launchsrc");
225         Utility.writeTemplateFile(launchConfig, 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 gwtshell = Utility.createNormalFile(outDir, className + "-shell"
238         + extension, overwrite, ignore);
239     if (gwtshell != null) {
240       String JavaDoc out = Utility.getFileFromClassPath(PACKAGE_PATH + "gwtshell"
241           + extension + "src");
242       Utility.writeTemplateFile(gwtshell, out, replacements);
243       if (extension.length() == 0) {
244         chmodExecutable(gwtshell);
245       }
246     }
247
248     File JavaDoc gwtcompile = Utility.createNormalFile(outDir, className + "-compile"
249         + extension, overwrite, ignore);
250     if (gwtcompile != null) {
251       String JavaDoc out = Utility.getFileFromClassPath(PACKAGE_PATH + "gwtcompile"
252           + extension + "src");
253       Utility.writeTemplateFile(gwtcompile, out, replacements);
254       if (extension.length() == 0) {
255         chmodExecutable(gwtcompile);
256       }
257     }
258   }
259
260   /**
261    * Try to make the given file executable. Implementation tries to exec chmod,
262    * which may fail if the platform doesn't support it. Prints a warning to
263    * stderr if the call fails.
264    *
265    * @param file the file to make executable
266    */

267   private static void chmodExecutable(File JavaDoc file) {
268     try {
269       Runtime.getRuntime().exec("chmod u+x " + file.getAbsolutePath());
270     } catch (Throwable JavaDoc e) {
271       System.err.println(("Warning: cannot exec chmod to set permission on generated file."));
272     }
273   }
274
275   private String JavaDoc eclipse = null;
276   private String JavaDoc fullClassName = null;
277   private boolean ignore = false;
278   private File JavaDoc outDir;
279   private boolean overwrite = false;
280
281   protected ApplicationCreator() {
282
283     registerHandler(new ArgHandlerEclipse() {
284       public String JavaDoc getPurpose() {
285         return "Creates a debug launch config for the named eclipse project";
286       }
287
288       public boolean setString(String JavaDoc str) {
289         eclipse = str;
290         return true;
291       }
292     });
293
294     registerHandler(new ArgHandlerOutDir() {
295       public void setDir(File JavaDoc dir) {
296         outDir = dir;
297       }
298     });
299
300     registerHandler(new ArgHandlerOverwrite() {
301       public boolean setFlag() {
302         if (ignore) {
303           System.err.println("-overwrite cannot be used with -ignore");
304           return false;
305         }
306         overwrite = true;
307         return true;
308       }
309     });
310
311     registerHandler(new ArgHandlerIgnore() {
312       public boolean setFlag() {
313         if (overwrite) {
314           System.err.println("-ignore cannot be used with -overwrite");
315           return false;
316         }
317         ignore = true;
318         return true;
319       }
320     });
321
322     registerHandler(new ArgHandlerAppClass());
323   }
324
325   protected boolean run() {
326     try {
327       createApplication(fullClassName, outDir, eclipse, overwrite, ignore);
328       return true;
329     } catch (IOException JavaDoc e) {
330       System.err.println(e.getClass().getName() + ": " + e.getMessage());
331       return false;
332     }
333   }
334
335 }
336
Popular Tags