KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > gnu > trove > generate > Generate


1 ///////////////////////////////////////////////////////////////////////////////
2
// This library is free software; you can redistribute it and/or
3
// modify it under the terms of the GNU Lesser General Public
4
// License as published by the Free Software Foundation; either
5
// version 2.1 of the License, or (at your option) any later version.
6
//
7
// This library is distributed in the hope that it will be useful,
8
// but WITHOUT ANY WARRANTY; without even the implied warranty of
9
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10
// GNU General Public License for more details.
11
//
12
// You should have received a copy of the GNU Lesser General Public
13
// License along with this program; if not, write to the Free Software
14
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
15
///////////////////////////////////////////////////////////////////////////////
16
package gnu.trove.generate;
17
18 import java.io.*;
19 import java.util.regex.Pattern JavaDoc;
20 import java.util.Arrays JavaDoc;
21 import java.net.URL JavaDoc;
22 import java.security.MessageDigest JavaDoc;
23 import java.security.NoSuchAlgorithmException JavaDoc;
24
25
26 /**
27  * Generates classes that are created from templates. The "*.template" files must be in
28  * the classpath (because Class.getResource() is used to load the files).
29  */

30 public class Generate {
31     private static final String JavaDoc P2P_MAP_DECORATOR_NAME = "P2PMapDecorator.template";
32     private static final String JavaDoc[] WRAPPERS = new String JavaDoc[] {
33         // v V
34
"double", "Double",
35         "float", "Float",
36         "int", "Integer",
37         "long", "Long",
38         "byte", "Byte",
39         "short", "Short"
40     };
41     public static void main(String JavaDoc[] args) throws IOException {
42         if ( args.length == 0 ) {
43             System.out.println( "Usage: Generate <output_path>" );
44             return;
45         }
46
47         File output_path = new File( args[ 0 ] );
48         if ( !output_path.exists() ) {
49             System.err.println( "\"" + output_path + "\" does not exist" );
50             return;
51         }
52
53
54         generateP2PMapDecorators(output_path);
55
56         // Decorators
57
generate("P2OMapDecorator.template", "decorator/T", "ObjectHashMapDecorator.java", output_path);
58         generate("O2PMapDecorator.template", "decorator/TObject", "HashMapDecorator.java", output_path);
59         generate("PHashSetDecorator.template", "decorator/T", "HashSetDecorator.java", output_path);
60
61         // Iterators
62
generate("O2PIterator.template", "TObject", "Iterator.java", output_path);
63         generate("P2OIterator.template", "T", "ObjectIterator.java", output_path);
64         generateP2P("P2PIterator.template", "T", "Iterator.java", output_path);
65         generate("PIterator.template", "T", "Iterator.java", output_path);
66
67         // Procedures
68
generate("O2PProcedure.template", "TObject", "Procedure.java", output_path);
69         generate("P2OProcedure.template", "T", "ObjectProcedure.java", output_path);
70         generateP2P("P2PProcedure.template", "T", "Procedure.java", output_path);
71         generate("PProcedure.template", "T", "Procedure.java", output_path);
72
73         // Functions
74
generate("PFunction.template", "T", "Function.java", output_path);
75
76         // Hashing Strategy interfaces
77
generate("PHashingStrategy.template", "T", "HashingStrategy.java", output_path);
78
79         // Hash abstract classes
80
generate("PHash.template", "T", "Hash.java", output_path);
81
82         // HashMaps
83
generate("P2OHashMap.template", "T", "ObjectHashMap.java", output_path);
84         generate("O2PHashMap.template", "TObject", "HashMap.java", output_path);
85         generateP2P("P2PHashMap.template", "T", "HashMap.java", output_path);
86
87         // ArrayLists
88
generate( "PArrayList.template", "T", "ArrayList.java", output_path);
89
90         // HashSets
91
generate( "PHashSet.template", "T", "HashSet.java", output_path);
92
93         System.out.println( "Generation complete." );
94     }
95
96     private static void generate(String JavaDoc templateName, String JavaDoc pathPrefix, String JavaDoc pathSuffix,
97         File output_path) throws IOException {
98
99         String JavaDoc template = readFile(templateName);
100         for (int i = 0; i < WRAPPERS.length; i+=2) {
101             String JavaDoc e = WRAPPERS[i];
102             String JavaDoc ET = WRAPPERS[i+1];
103             String JavaDoc E = shortInt(ET);
104             String JavaDoc out = template;
105             out = Pattern.compile("#e#").matcher(out).replaceAll(e);
106             out = Pattern.compile("#E#").matcher(out).replaceAll(E);
107             out = Pattern.compile("#ET#").matcher(out).replaceAll(ET);
108             String JavaDoc outFile = pathPrefix + E + pathSuffix;
109             writeFile(outFile, out, output_path);
110         }
111     }
112
113     private static void generateP2P(String JavaDoc templateName, String JavaDoc pathPrefix,
114         String JavaDoc pathSuffix, File output_path) throws IOException {
115
116         String JavaDoc template = readFile(templateName);
117         for (int i = 0; i < WRAPPERS.length; i+=2) {
118             String JavaDoc e = WRAPPERS[i];
119             String JavaDoc ET = WRAPPERS[i+1];
120             String JavaDoc E = shortInt(ET);
121
122             for( int j = 0; j < WRAPPERS.length; j+= 2 ) {
123                 String JavaDoc out = template;
124                 out = Pattern.compile("#e#").matcher(out).replaceAll(e);
125                 out = Pattern.compile("#E#").matcher(out).replaceAll(E);
126                 out = Pattern.compile("#ET#").matcher(out).replaceAll(ET);
127
128                 String JavaDoc f = WRAPPERS[j];
129                 String JavaDoc FT = WRAPPERS[j+1];
130                 String JavaDoc F = shortInt(FT);
131                 out = Pattern.compile("#f#").matcher(out).replaceAll(f);
132                 out = Pattern.compile("#F#").matcher(out).replaceAll(F);
133                 out = Pattern.compile("#FT#").matcher(out).replaceAll(FT);
134
135                 String JavaDoc outFile = pathPrefix + E + F + pathSuffix;
136                 writeFile(outFile, out, output_path);
137             }
138         }
139     }
140
141     private static void generateP2PMapDecorators(File output_path) throws IOException {
142         String JavaDoc template = readFile(P2P_MAP_DECORATOR_NAME);
143         for (int i = 0; i < WRAPPERS.length; i += 2) {
144             for (int j = 0; j < WRAPPERS.length; j += 2) {
145                 String JavaDoc k = WRAPPERS[i];
146                 String JavaDoc KT = WRAPPERS[i + 1];
147                 String JavaDoc v = WRAPPERS[j];
148                 String JavaDoc VT = WRAPPERS[j + 1];
149                 String JavaDoc K = shortInt(KT);
150                 String JavaDoc V = shortInt(VT);
151                 String JavaDoc out = template;
152                 out = Pattern.compile("#v#").matcher(out).replaceAll(v);
153                 out = Pattern.compile("#V#").matcher(out).replaceAll(V);
154                 out = Pattern.compile("#k#").matcher(out).replaceAll(k);
155                 out = Pattern.compile("#K#").matcher(out).replaceAll(K);
156                 out = Pattern.compile("#KT#").matcher(out).replaceAll(KT);
157                 out = Pattern.compile("#VT#").matcher(out).replaceAll(VT);
158                 String JavaDoc outFile = "decorator/T" + K + V + "HashMapDecorator.java";
159                 writeFile(outFile, out, output_path);
160             }
161         }
162     }
163
164     private static void writeFile(String JavaDoc file, String JavaDoc out, File output_path) throws IOException {
165         File destination = new File( output_path.getPath() + "/" + file );
166         File parent = destination.getParentFile();
167         parent.mkdirs();
168
169         // Write to a temporary file
170
File temp = File.createTempFile( "trove", "gentemp" );
171         FileWriter writer = new FileWriter( temp );
172         writer.write(out);
173         writer.close();
174
175
176         // Now determine if it should be moved to the final location
177
final boolean need_to_move;
178         if ( destination.exists() ) {
179             boolean matches;
180             try {
181                 MessageDigest JavaDoc digest = MessageDigest.getInstance( "MD5" );
182
183                 byte[] current_file = digest( destination, digest );
184                 byte[] new_file = digest( temp, digest );
185
186                 matches = Arrays.equals( current_file, new_file );
187             }
188             catch( NoSuchAlgorithmException JavaDoc ex ) {
189                 System.err.println( "WARNING: Couldn't load digest algorithm to compare " +
190                     "new and old template. Generation will be forced." );
191                 matches = false;
192             }
193
194             need_to_move = !matches;
195         }
196         else need_to_move = true;
197
198
199         // Now move it if we need to move it
200
if ( need_to_move ) {
201             destination.delete();
202             if ( !temp.renameTo( destination ) ) {
203                 throw new IOException( "ERROR writing: " + destination );
204             }
205             else System.out.println( "Wrote: " + destination );
206         }
207         else System.out.println( "Skipped: " + destination );
208     }
209
210
211     private static byte[] digest( File file, MessageDigest JavaDoc digest ) throws IOException {
212         digest.reset();
213
214         byte[] buffer = new byte[ 1024 ];
215         FileInputStream in = new FileInputStream( file );
216         try {
217             int read = in.read( buffer );
218             while( read >= 0 ) {
219                 digest.update( buffer, 0, read );
220
221                 read = in.read( buffer );
222             }
223
224             return digest.digest();
225         }
226         finally {
227             try {
228                 in.close();
229             }
230             catch( IOException ex ) {
231                 // ignore
232
}
233         }
234     }
235
236
237
238     private static String JavaDoc shortInt(String JavaDoc type) {
239         return type.equals("Integer") ? "Int" : type;
240     }
241
242     private static String JavaDoc readFile(String JavaDoc name) throws IOException {
243         String JavaDoc packageName = Generate.class.getPackage().getName();
244         URL JavaDoc resource = Generate.class.getClassLoader().getResource(packageName.replace('.','/')+"/"+name);
245         if (resource == null) {
246             throw new NullPointerException JavaDoc( "Couldn't find: " +
247                 packageName.replace('.','/')+"/"+name );
248         }
249         InputStream inputStream = resource.openConnection().getInputStream();
250         BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
251         StringBuffer JavaDoc out = new StringBuffer JavaDoc();
252
253         while (true) {
254             String JavaDoc line = reader.readLine();
255             if (line == null) break;
256             out.append(line);
257             out.append("\n");
258         }
259         return out.toString();
260     }
261 }
262
Popular Tags