KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > google > gwt > util > tools > Utility


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.util.tools;
17
18 import java.io.ByteArrayOutputStream JavaDoc;
19 import java.io.File JavaDoc;
20 import java.io.FileInputStream JavaDoc;
21 import java.io.FileNotFoundException JavaDoc;
22 import java.io.FileWriter JavaDoc;
23 import java.io.IOException JavaDoc;
24 import java.io.InputStream JavaDoc;
25 import java.io.OutputStream JavaDoc;
26 import java.io.RandomAccessFile JavaDoc;
27 import java.io.Reader JavaDoc;
28 import java.io.Writer JavaDoc;
29 import java.net.URI JavaDoc;
30 import java.net.URL JavaDoc;
31 import java.util.Iterator JavaDoc;
32 import java.util.Map JavaDoc;
33 import java.util.Set JavaDoc;
34
35 /**
36  * A smattering of useful file functions.
37  */

38 public final class Utility {
39
40   private static String JavaDoc sDevJarName = null;
41   private static String JavaDoc sInstallPath = null;
42
43   /**
44    * Helper that ignores exceptions during close, because what are you going to
45    * do?
46    */

47   public static void close(InputStream JavaDoc is) {
48     try {
49       if (is != null) {
50         is.close();
51       }
52     } catch (IOException JavaDoc e) {
53     }
54   }
55
56   /**
57    * Helper that ignores exceptions during close, because what are you going to
58    * do?
59    */

60   public static void close(OutputStream JavaDoc os) {
61     try {
62       if (os != null) {
63         os.close();
64       }
65       
66     } catch (IOException JavaDoc e) {
67     }
68   }
69
70   /**
71    * Helper that ignores exceptions during close, because what are you going to
72    * do?
73    */

74   public static void close(RandomAccessFile JavaDoc f) {
75     if (f != null) {
76       try {
77         f.close();
78       } catch (IOException JavaDoc e) {
79       }
80     }
81   }
82
83   /**
84    * Helper that ignores exceptions during close, because what are you going to
85    * do?
86    */

87   public static void close(Reader JavaDoc reader) {
88     try {
89       if (reader != null) {
90         reader.close();
91       }
92     } catch (IOException JavaDoc e) {
93     }
94   }
95
96   /**
97    * Helper that ignores exceptions during close, because what are you going to
98    * do?
99    */

100   public static void close(Writer JavaDoc writer) {
101     try {
102       if (writer != null) {
103         writer.close();
104       }
105     } catch (IOException JavaDoc e) {
106     }
107   }
108
109   /**
110    * @param parent Parent directory
111    * @param fileName New file name
112    * @param overwrite Is overwriting an existing file allowed?
113    * @return Handle to the file
114    * @throws IOException If the file cannot be created, or if the file already
115    * existed and overwrite was false.
116    */

117   public static File JavaDoc createNormalFile(File JavaDoc parent, String JavaDoc fileName,
118       boolean overwrite, boolean ignore) throws IOException JavaDoc {
119     File JavaDoc file = new File JavaDoc(parent, fileName);
120     if (file.createNewFile()) {
121       System.out.println("Created file " + file);
122       return file;
123     }
124
125     if (!file.exists() || file.isDirectory()) {
126       throw new IOException JavaDoc(file.getPath() + " : could not create normal file.");
127     }
128     
129     if (ignore) {
130       System.out.println(file + " already exists; skipping");
131       return null;
132     }
133
134     if (!overwrite) {
135       throw new IOException JavaDoc(
136         file.getPath()
137           + " : already exists; please remove it or use the -overwrite or -ignore option.");
138     }
139     
140     System.out.println("Overwriting existing file " + file);
141     return file;
142   }
143
144   public static String JavaDoc getDevJarName() {
145     if (sDevJarName == null) {
146       computeInstallationPath();
147     }
148     return sDevJarName;
149   }
150
151   /**
152    * @param parent Parent directory of the requested directory.
153    * @param dirName Requested name for the directory.
154    * @param create Create the directory if it does not already exist?
155    * @return A {@link File} representing a directory that now exists.
156    * @throws IOException If the directory is not found and/or cannot be created.
157    */

158   public static File JavaDoc getDirectory(File JavaDoc parent, String JavaDoc dirName, boolean create)
159       throws IOException JavaDoc {
160     File JavaDoc dir = new File JavaDoc(parent, dirName);
161     boolean alreadyExisted = dir.exists();
162
163     if (create) {
164       dir.mkdirs();
165     }
166
167     if (!dir.exists() || !dir.isDirectory()) {
168       if (create) {
169         throw new IOException JavaDoc(dir.getPath() + " : could not create directory.");
170       } else {
171         throw new IOException JavaDoc(dir.getPath() + " : could not find directory.");
172       }
173     }
174
175     if (create && !alreadyExisted) {
176       System.out.println("Created directory " + dir);
177     }
178     
179     return dir;
180   }
181
182   /**
183    * @param dirPath Requested path for the directory.
184    * @param create Create the directory if it does not already exist?
185    * @return A {@link File} representing a directory that now exists.
186    * @throws IOException If the directory is not found and/or cannot be created.
187    */

188   public static File JavaDoc getDirectory(String JavaDoc dirPath, boolean create)
189       throws IOException JavaDoc {
190     return getDirectory(null, dirPath, create);
191   }
192
193   /**
194    * Gets the contents of a file from the class path as a string.
195    *
196    * @param partialPath the partial path to the resource from this class's class
197    * file
198    * @return the contents of the file, or <code>null</code> if the file could
199    * not be found
200    * @throws IOException
201    */

202   public static String JavaDoc getFileFromClassPath(String JavaDoc partialPath)
203       throws IOException JavaDoc {
204     InputStream JavaDoc in = Utility.class.getClassLoader().getResourceAsStream(
205       partialPath);
206     try {
207       if (in == null) {
208         throw new FileNotFoundException JavaDoc(partialPath);
209       }
210       ByteArrayOutputStream JavaDoc os = new ByteArrayOutputStream JavaDoc();
211       int ch;
212       while ((ch = in.read()) != -1) {
213         os.write(ch);
214       }
215       return new String JavaDoc(os.toByteArray(), "UTF-8");
216     } finally {
217       close(in);
218     }
219   }
220
221   public static String JavaDoc getInstallPath() {
222     if (sInstallPath == null) {
223       computeInstallationPath();
224     }
225     return sInstallPath;
226   }
227
228   public static void streamOut(File JavaDoc file, OutputStream JavaDoc out, int bufferSize)
229       throws IOException JavaDoc {
230     FileInputStream JavaDoc fis = null;
231     try {
232       fis = new FileInputStream JavaDoc(file);
233       streamOut(fis, out, bufferSize);
234     } finally {
235       com.google.gwt.util.tools.Utility.close(fis);
236     }
237   }
238
239   public static void streamOut(InputStream JavaDoc in, OutputStream JavaDoc out, int bufferSize)
240       throws IOException JavaDoc {
241     assert (bufferSize >= 0);
242
243     byte[] buffer = new byte[bufferSize];
244     int bytesRead = 0;
245     while (true) {
246       bytesRead = in.read(buffer);
247       if (bytesRead >= 0) {
248         // Copy the bytes out.
249
out.write(buffer, 0, bytesRead);
250       } else {
251         // End of input stream.
252
return;
253       }
254     }
255   }
256
257   public static void writeTemplateFile(File JavaDoc file, String JavaDoc contents,
258       Map JavaDoc replacements) throws IOException JavaDoc {
259
260     String JavaDoc replacedContents = contents;
261     Set JavaDoc entries = replacements.entrySet();
262     for (Iterator JavaDoc iter = entries.iterator(); iter.hasNext();) {
263       Map.Entry JavaDoc entry = (Map.Entry JavaDoc) iter.next();
264       String JavaDoc replaceThis = (String JavaDoc) entry.getKey();
265       String JavaDoc withThis = (String JavaDoc) entry.getValue();
266       withThis = withThis.replaceAll("\\\\", "\\\\\\\\");
267       withThis = withThis.replaceAll("\\$", "\\\\\\$");
268       replacedContents = replacedContents.replaceAll(replaceThis, withThis);
269     }
270
271     FileWriter JavaDoc fw = new FileWriter JavaDoc(file);
272     fw.write(replacedContents);
273     close(fw);
274   }
275
276   private static void computeInstallationPath() {
277     try {
278       String JavaDoc override = System.getProperty("gwt.devjar");
279       if (override == null) {
280         String JavaDoc partialPath = Utility.class.getName().replace('.', '/').concat(
281           ".class");
282         URL JavaDoc url = Utility.class.getClassLoader().getResource(partialPath);
283         if (url != null && "jar".equals(url.getProtocol())) {
284           String JavaDoc path = url.toString();
285           String JavaDoc jarPath = path.substring(path.indexOf("file:"),
286             path.lastIndexOf('!'));
287           File JavaDoc devJarFile = new File JavaDoc(URI.create(jarPath));
288           if (!devJarFile.isFile()) {
289             throw new IOException JavaDoc("Could not find jar file; "
290               + devJarFile.getCanonicalPath()
291               + " does not appear to be a valid file");
292           }
293           sDevJarName = devJarFile.getName();
294
295           String JavaDoc dirPath = jarPath.substring(0, jarPath.lastIndexOf('/') + 1);
296           File JavaDoc installDirFile = new File JavaDoc(URI.create(dirPath));
297           if (!installDirFile.isDirectory()) {
298             throw new IOException JavaDoc("Could not find installation directory; "
299               + installDirFile.getCanonicalPath()
300               + " does not appear to be a valid directory");
301           }
302           
303           sInstallPath = installDirFile.getCanonicalPath().replace(
304             File.separatorChar, '/');
305         } else {
306           throw new IOException JavaDoc(
307             "Cannot determine installation directory; apparently not running from a jar");
308         }
309       } else {
310         override = override.replace('\\', '/');
311         int pos = override.lastIndexOf('/');
312         if (pos < 0) {
313           sInstallPath = "";
314           sDevJarName = override;
315         } else {
316           sInstallPath = override.substring(0, pos);
317           sDevJarName = override.substring(pos + 1);
318         }
319       }
320     } catch (IOException JavaDoc e) {
321       throw new RuntimeException JavaDoc(
322         "Installation problem detected, please reinstall GWT", e);
323     }
324   }
325
326 }
327
Popular Tags