KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > google > gwt > i18n > rebind > util > AbstractLocalizableInterfaceCreator


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.rebind.util;
17
18 import com.google.gwt.dev.util.Util;
19 import com.google.gwt.dev.util.log.PrintWriterTreeLogger;
20 import com.google.gwt.i18n.tools.I18NSync;
21 import com.google.gwt.user.rebind.ClassSourceFileComposerFactory;
22 import com.google.gwt.user.rebind.SourceWriter;
23
24 import org.apache.tapestry.util.text.LocalizedProperties;
25
26 import java.io.File JavaDoc;
27 import java.io.FileInputStream JavaDoc;
28 import java.io.FileNotFoundException JavaDoc;
29 import java.io.FileOutputStream JavaDoc;
30 import java.io.IOException JavaDoc;
31 import java.io.InputStream JavaDoc;
32 import java.io.OutputStreamWriter JavaDoc;
33 import java.io.PrintWriter JavaDoc;
34 import java.io.Writer JavaDoc;
35 import java.util.ArrayList JavaDoc;
36 import java.util.HashSet JavaDoc;
37 import java.util.Iterator JavaDoc;
38 import java.util.List JavaDoc;
39 import java.util.Set JavaDoc;
40 import java.util.Map.Entry;
41 import java.util.regex.Pattern JavaDoc;
42
43 /**
44  * Abstract base functionality for <code>MessagesInterfaceCreator</code> and
45  * <code>ConstantsInterfaceCreator</code>.
46  */

47 public abstract class AbstractLocalizableInterfaceCreator {
48   private static class RenameDuplicates extends ResourceKeyFormatter {
49     private Set JavaDoc methodNames = new HashSet JavaDoc();
50
51     public String JavaDoc format(String JavaDoc key) {
52       if (methodNames.contains(key)) {
53         key += "_dup";
54         return format(key);
55       } else {
56         methodNames.add(key);
57         return key;
58       }
59     }
60   }
61
62   private static class ReplaceBadChars extends ResourceKeyFormatter {
63     public String JavaDoc format(String JavaDoc key) {
64       return DEFAULT_CHARS.matcher(key).replaceAll("_");
65     }
66   }
67
68   private abstract static class ResourceKeyFormatter {
69     public abstract String JavaDoc format(String JavaDoc key);
70   }
71
72   private static Pattern JavaDoc DEFAULT_CHARS = Pattern.compile("[.-]");
73
74   /**
75    * Composer for the current Constant.
76    */

77   protected SourceWriter composer;
78
79   private List JavaDoc formatters = new ArrayList JavaDoc();
80
81   private File JavaDoc resourceFile;
82
83   private File JavaDoc sourceFile;
84
85   private PrintWriter JavaDoc writer;
86
87   /**
88    * Creates a new constants creator.
89    *
90    * @param className constant class to create
91    * @param packageName package to create it in
92    * @param resourceBundle resource bundle with value
93    * @param targetLocation
94    * @throws IOException
95    */

96   public AbstractLocalizableInterfaceCreator(String JavaDoc className,
97       String JavaDoc packageName, File JavaDoc resourceBundle, File JavaDoc targetLocation,
98       Class JavaDoc interfaceClass) throws IOException JavaDoc {
99     setup(packageName, className, resourceBundle, targetLocation,
100         interfaceClass);
101   }
102
103   /**
104    * Generate class.
105    *
106    * @throws FileNotFoundException
107    * @throws IOException
108    */

109   public void generate() throws FileNotFoundException JavaDoc, IOException JavaDoc {
110     try {
111       try {
112         // right now, only property files are legal
113
generateFromPropertiesFile();
114       } finally {
115         writer.close();
116       }
117     } catch (IOException JavaDoc e) {
118       sourceFile.delete();
119       throw e;
120     } catch (RuntimeException JavaDoc e) {
121       sourceFile.delete();
122       throw e;
123     }
124   }
125
126   /**
127    * Create a String method declaration from a Dictionary/value pair.
128    *
129    * @param key Dictionary
130    * @param defaultValue default value
131    */

132   public void genSimpleMethodDecl(String JavaDoc key, String JavaDoc defaultValue) {
133     genMethodDecl("String", defaultValue, key, key);
134   }
135
136   /**
137    * Create method args based upon the default value.
138    *
139    * @param defaultValue
140    */

141   protected abstract void genMethodArgs(String JavaDoc defaultValue);
142
143   /**
144    * Returns the javaDocComment for the class.
145    *
146    * @param path path of class
147    * @return java doc comment
148    */

149   protected abstract String JavaDoc javaDocComment(String JavaDoc path);
150
151   void generateFromPropertiesFile() throws IOException JavaDoc {
152     InputStream JavaDoc propStream = new FileInputStream JavaDoc(resourceFile);
153     LocalizedProperties p = new LocalizedProperties();
154     p.load(propStream, Util.DEFAULT_ENCODING);
155     addFormatters();
156     Iterator JavaDoc elements = p.getPropertyMap().entrySet().iterator();
157     if (elements.hasNext() == false) {
158       throw new IllegalStateException JavaDoc(
159           "File '"
160               + resourceFile
161               + "' cannot be used to generate message classes, as it has no key/value pairs defined.");
162     }
163     while (elements.hasNext()) {
164       Entry s = (Entry) elements.next();
165       genSimpleMethodDecl((String JavaDoc) s.getKey(), (String JavaDoc) s.getValue());
166     }
167     composer.commit(new PrintWriterTreeLogger());
168   }
169
170   private void addFormatters() {
171     // For now, we completely control property key formatters.
172
formatters.add(new ReplaceBadChars());
173
174     // Rename Duplicates must always come last.
175
formatters.add(new RenameDuplicates());
176   }
177
178   private String JavaDoc formatKey(String JavaDoc key) {
179     for (int i = 0; i < formatters.size(); i++) {
180       ResourceKeyFormatter formatter = (ResourceKeyFormatter) formatters.get(i);
181       key = formatter.format(key);
182     }
183     if (Util.isValidJavaIdent(key) == false) {
184       System.err.println("Warning: " + key
185           + " is not a legitimate method name. " + sourceFile
186           + " will have compiler errors");
187     }
188     return key;
189   }
190
191   private void genMethodDecl(String JavaDoc type, String JavaDoc defaultValue, String JavaDoc key,
192       String JavaDoc typeArg) {
193     composer.beginJavaDocComment();
194     composer.println("Translated \"" + defaultValue + "\".\n");
195     composer.println("@return translated \"" + defaultValue + "\"");
196     composer.print(I18NSync.ID + typeArg);
197     composer.endJavaDocComment();
198     key = formatKey(key);
199     composer.print(type + " " + key);
200     composer.print("(");
201     genMethodArgs(defaultValue);
202     composer.print(");\n");
203   }
204
205   private void setup(String JavaDoc packageName, String JavaDoc className, File JavaDoc resourceBundle,
206       File JavaDoc targetLocation, Class JavaDoc interfaceClass) throws IOException JavaDoc {
207     ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(
208         packageName, className);
209     factory.makeInterface();
210     factory.setJavaDocCommentForClass(javaDocComment(resourceBundle.getCanonicalPath().replace(
211         File.separatorChar, '/')));
212     factory.addImplementedInterface(interfaceClass.getName());
213     FileOutputStream JavaDoc file = new FileOutputStream JavaDoc(targetLocation);
214     Writer underlying = new OutputStreamWriter JavaDoc(file, Util.DEFAULT_ENCODING);
215     writer = new PrintWriter JavaDoc(underlying);
216     composer = factory.createSourceWriter(writer);
217     resourceFile = resourceBundle;
218     sourceFile = targetLocation;
219   }
220 }
221
Popular Tags