KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > google > gwt > i18n > tools > I18NSync


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.i18n.tools;
17
18 import com.google.gwt.i18n.client.Constants;
19 import com.google.gwt.i18n.client.ConstantsWithLookup;
20 import com.google.gwt.i18n.client.Messages;
21 import com.google.gwt.i18n.rebind.LocalizableGenerator;
22 import com.google.gwt.i18n.rebind.util.AbstractLocalizableInterfaceCreator;
23 import com.google.gwt.i18n.rebind.util.ConstantsInterfaceCreator;
24 import com.google.gwt.i18n.rebind.util.MessagesInterfaceCreator;
25 import com.google.gwt.util.tools.ArgHandlerExtra;
26 import com.google.gwt.util.tools.ArgHandlerFlag;
27 import com.google.gwt.util.tools.ArgHandlerString;
28 import com.google.gwt.util.tools.ToolBase;
29
30 import java.io.File JavaDoc;
31 import java.io.FileNotFoundException JavaDoc;
32 import java.io.IOException JavaDoc;
33 import java.net.URL JavaDoc;
34
35 /**
36  * Common public access point for localization support methods.
37  */

38 public class I18NSync extends ToolBase {
39
40   private class classNameArgHandler extends ArgHandlerExtra {
41
42     public boolean addExtraArg(String JavaDoc str) {
43       if (classNameArg != null) {
44         System.err.println("Too many arguments.");
45         return false;
46       }
47       // We wish to use the same sets of checks for validity whether the user
48
// calls the static method to create localizable fields or uses the
49
// command line, as the java call must throw IOException, here we must
50
// catch it and convert it to a System.err message.
51
try {
52         File JavaDoc resourceFile = urlToResourceFile(str);
53         checkValidResourceInputFile(resourceFile);
54         classNameArg = str;
55       } catch (IOException JavaDoc e) {
56         System.err.println("Error: " + e.getMessage());
57         return false;
58       }
59       return true;
60     }
61
62     public String JavaDoc[] getDefaultArgs() {
63       return null;
64     }
65
66     public String JavaDoc getPurpose() {
67       return "Identifies the Constants/Messages class to be created. For example com.google.sample.i18n.client.Colors";
68     }
69
70     public String JavaDoc[] getTagArgs() {
71       String JavaDoc[] interfaceArg = {"name of the Constants/Messages interface to create"};
72       return interfaceArg;
73     }
74
75     public boolean isRequired() {
76       return true;
77     }
78   }
79
80   private class outDirHandler extends ArgHandlerString {
81
82     public String JavaDoc[] getDefaultArgs() {
83       return null;
84     }
85
86     public String JavaDoc getPurpose() {
87       return "Java source directory, defaults to the resource's class path.";
88     }
89
90     public String JavaDoc getTag() {
91       return "-out";
92     }
93
94     public String JavaDoc[] getTagArgs() {
95       String JavaDoc[] resourceArgs = {"fileName"};
96       return resourceArgs;
97     }
98
99     public boolean isRequired() {
100       return false;
101     }
102
103     public boolean setString(String JavaDoc str) {
104
105       // We wish to use the same sets of checks for validity whether the user
106
// calls the static method to create localizable classes or uses the
107
// command line, as the java call must throw IOException, here we must
108
// catch it and convert it to a System.err message.
109
outDirArg = new File JavaDoc(str);
110       try {
111         checkValidSourceDir(outDirArg);
112       } catch (IOException JavaDoc e) {
113         System.err.println("Error: " + e.getMessage());
114         return false;
115       }
116       return true;
117     }
118   }
119
120   /**
121    * Created Key.
122    */

123   public static final String JavaDoc ID = "@" + LocalizableGenerator.GWT_KEY + " ";
124
125   /**
126    * Creates a <code>Constants</code> interface from a class name. The
127    * resource file needed to create the class must be on your class path.
128    *
129    * @param className the name of the Constants class to be created
130    * @param outDir source dir root
131    * @throws IOException
132    */

133   public static void createConstantsInterfaceFromClassName(String JavaDoc className,
134       File JavaDoc outDir) throws IOException JavaDoc {
135     createLocalizableInterfaceFromClassName(className, outDir, Constants.class);
136   }
137
138   /**
139    * Creates a <code>ConstantsWithLookup</code> interface from a class name.
140    * The resource file needed to create the class must be on your class path.
141    *
142    * @param className the name of the Constants class to be created
143    * @throws IOException
144    */

145   public static void createConstantsWithLookupInterfaceFromClassName(
146       String JavaDoc className) throws IOException JavaDoc {
147     createLocalizableInterfaceFromClassName(className, null,
148         ConstantsWithLookup.class);
149   }
150
151   /**
152    * Creates a <code>ConstantsWithLookup</code> interface from a class name.
153    * The resource file needed to create the class must be on your class path.
154    *
155    * @param className the name of the Constants class to be created
156    * @param outDir source dir root
157    * @throws IOException
158    */

159   public static void createConstantsWithLookupInterfaceFromClassName(
160       String JavaDoc className, File JavaDoc outDir) throws IOException JavaDoc {
161     createLocalizableInterfaceFromClassName(className, outDir,
162         ConstantsWithLookup.class);
163   }
164
165   /**
166    * Creates a <code>Messages</code> interface from a class name. The resource
167    * file needed to create the class must be on your class path.
168    *
169    * @param className the name of the Constants class to be created
170    * @throws IOException
171    */

172   public static void createMessagesInterfaceFromClassName(String JavaDoc className)
173       throws IOException JavaDoc {
174     createLocalizableInterfaceFromClassName(className, null, Messages.class);
175   }
176
177   /**
178    * Creates a <code>Messages</code> interface from a class name. The resource
179    * file needed to create the class must be on your class path.
180    *
181    * @param className the name of the Constants class to be created
182    * @param outDir source dir root
183    * @throws IOException
184    */

185   public static void createMessagesInterfaceFromClassName(String JavaDoc className,
186       File JavaDoc outDir) throws IOException JavaDoc {
187     createLocalizableInterfaceFromClassName(className, outDir, Messages.class);
188   }
189
190   /**
191    * Creates Messages and Constants java source files.
192    *
193    * @param args arguements for generation
194    */

195   public static void main(String JavaDoc[] args) {
196     I18NSync creator = new I18NSync();
197     if (creator.processArgs(args)) {
198       if (creator.run()) {
199         return;
200       }
201     }
202     System.exit(1);
203   }
204
205   static void checkValidJavaSourceOutputFile(File JavaDoc targetSource)
206       throws IOException JavaDoc {
207
208     if (targetSource.isDirectory()) {
209       throw new IOException JavaDoc("Output file'" + targetSource
210           + "' exists and is a directory; cannot overwrite");
211     }
212     if (targetSource.getParentFile().isDirectory() == false) {
213       throw new IOException JavaDoc("The target source's directory '"
214           + targetSource.getParent() + "' must be an existing directory");
215     }
216   }
217
218   static void checkValidResourceInputFile(File JavaDoc resource) throws IOException JavaDoc {
219     if (!resource.getPath().endsWith(".properties")) {
220       throw new IOException JavaDoc("Properties files " + resource
221           + " should end with '.properties'");
222     }
223     if (!resource.exists() || !resource.isFile()) {
224       throw new IOException JavaDoc("Properties file not found: " + resource);
225     }
226   }
227
228   private static void checkValidSourceDir(File JavaDoc outDir) throws IOException JavaDoc {
229     if (outDir.isDirectory() == false) {
230       throw new IOException JavaDoc(outDir
231           + " must be an existing directory. Current path is "
232           + new File JavaDoc(".").getCanonicalPath());
233     }
234   }
235
236   private static void createLocalizableInterfaceFromClassName(String JavaDoc className,
237       File JavaDoc sourceDir, Class JavaDoc interfaceClass) throws FileNotFoundException JavaDoc,
238       IOException JavaDoc {
239     File JavaDoc resource = urlToResourceFile(className);
240     File JavaDoc source;
241     if (sourceDir == null) {
242       source = synthesizeSourceFile(resource);
243     } else {
244       checkValidSourceDir(sourceDir);
245       String JavaDoc sourcePath = className.replace('.', File.separatorChar);
246       sourcePath = sourceDir.getCanonicalFile() + File.separator + sourcePath
247           + ".java";
248       source = new File JavaDoc(sourcePath);
249     }
250     // Need both source path and class name for this check
251
checkValidJavaSourceOutputFile(source);
252     checkValidResourceInputFile(resource);
253
254     int classDiv = className.lastIndexOf(".");
255     String JavaDoc packageName = className.substring(0, classDiv);
256     String JavaDoc name = className.substring(classDiv + 1);
257     AbstractLocalizableInterfaceCreator creator;
258     if (interfaceClass.equals(Messages.class)) {
259       creator = new MessagesInterfaceCreator(name, packageName, resource,
260           source);
261     } else {
262       creator = new ConstantsInterfaceCreator(name, packageName, resource,
263           source, interfaceClass);
264     }
265     creator.generate();
266   }
267
268   private static File JavaDoc synthesizeSourceFile(File JavaDoc resource) {
269     String JavaDoc javaPath = resource.getName();
270     javaPath = javaPath.substring(0, javaPath.lastIndexOf("."));
271     javaPath = resource.getParentFile().getPath() + File.separator + javaPath
272         + ".java";
273     File JavaDoc targetClassFile = new File JavaDoc(javaPath);
274     return targetClassFile;
275   }
276
277   private static File JavaDoc urlToResourceFile(String JavaDoc className)
278       throws FileNotFoundException JavaDoc, IOException JavaDoc {
279     if (className.endsWith(".java") || className.endsWith(".properties")
280         || className.endsWith(".class")
281         || className.indexOf(File.separator) > 0) {
282       throw new IllegalArgumentException JavaDoc(
283           "class '"
284               + className
285               + "'should not contain an extension. \"com.google.gwt.SomeClass\" is an example of a correctly formed class string");
286     }
287     String JavaDoc resourcePath = className.replace('.', '/') + ".properties";
288     URL JavaDoc r = ClassLoader.getSystemResource(resourcePath);
289     if (r == null) {
290       throw new FileNotFoundException JavaDoc("Could not find the resource '"
291           + resourcePath + " matching '" + className
292           + "' did you remember to add it to your classpath?");
293     }
294     File JavaDoc resourceFile = new File JavaDoc(r.getFile());
295     return resourceFile;
296   }
297
298   private String JavaDoc classNameArg;
299
300   private boolean createMessagesArg = false;
301
302   private File JavaDoc outDirArg;
303
304   private I18NSync() {
305     registerHandler(new classNameArgHandler());
306     registerHandler(new outDirHandler());
307     registerHandler(new ArgHandlerFlag() {
308
309       public String JavaDoc getPurpose() {
310         return "create Messages interface rather than Constants interface.";
311       }
312
313       public String JavaDoc getTag() {
314         return "-createMessages";
315       }
316
317       public boolean setFlag() {
318         createMessagesArg = true;
319         return true;
320       }
321     });
322   }
323
324   /**
325    * Creates the interface.
326    *
327    * @return whether the interface was created
328    */

329   protected boolean run() {
330     try {
331       Class JavaDoc createMe;
332       if (createMessagesArg) {
333         createMe = Messages.class;
334       } else {
335         createMe = Constants.class;
336       }
337       createLocalizableInterfaceFromClassName(classNameArg, outDirArg, createMe);
338       return true;
339     } catch (Throwable JavaDoc e) {
340       System.err.println(e.getMessage());
341       return false;
342     }
343   }
344 }
345
Popular Tags