001: /*
002: * Copyright 2006 Google Inc.
003: *
004: * Licensed under the Apache License, Version 2.0 (the "License"); you may not
005: * use this file except in compliance with the License. You may obtain a copy of
006: * the License at
007: *
008: * http://www.apache.org/licenses/LICENSE-2.0
009: *
010: * Unless required by applicable law or agreed to in writing, software
011: * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
012: * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
013: * License for the specific language governing permissions and limitations under
014: * the License.
015: */
016: package com.google.gwt.util.tools;
017:
018: import java.io.ByteArrayOutputStream;
019: import java.io.File;
020: import java.io.FileInputStream;
021: import java.io.FileNotFoundException;
022: import java.io.FileWriter;
023: import java.io.IOException;
024: import java.io.InputStream;
025: import java.io.OutputStream;
026: import java.io.RandomAccessFile;
027: import java.io.Reader;
028: import java.io.Writer;
029: import java.net.URI;
030: import java.net.URL;
031: import java.util.Iterator;
032: import java.util.Map;
033: import java.util.Set;
034:
035: /**
036: * A smattering of useful file functions.
037: */
038: public final class Utility {
039:
040: private static String sDevJarName = null;
041: private static String sInstallPath = null;
042:
043: /**
044: * Helper that ignores exceptions during close, because what are you going to
045: * do?
046: */
047: public static void close(InputStream is) {
048: try {
049: if (is != null) {
050: is.close();
051: }
052: } catch (IOException e) {
053: }
054: }
055:
056: /**
057: * Helper that ignores exceptions during close, because what are you going to
058: * do?
059: */
060: public static void close(OutputStream os) {
061: try {
062: if (os != null) {
063: os.close();
064: }
065:
066: } catch (IOException e) {
067: }
068: }
069:
070: /**
071: * Helper that ignores exceptions during close, because what are you going to
072: * do?
073: */
074: public static void close(RandomAccessFile f) {
075: if (f != null) {
076: try {
077: f.close();
078: } catch (IOException e) {
079: }
080: }
081: }
082:
083: /**
084: * Helper that ignores exceptions during close, because what are you going to
085: * do?
086: */
087: public static void close(Reader reader) {
088: try {
089: if (reader != null) {
090: reader.close();
091: }
092: } catch (IOException e) {
093: }
094: }
095:
096: /**
097: * Helper that ignores exceptions during close, because what are you going to
098: * do?
099: */
100: public static void close(Writer writer) {
101: try {
102: if (writer != null) {
103: writer.close();
104: }
105: } catch (IOException 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 createNormalFile(File parent, String fileName,
118: boolean overwrite, boolean ignore) throws IOException {
119: File file = new File(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(file.getPath()
127: + " : could not create normal file.");
128: }
129:
130: if (ignore) {
131: System.out.println(file + " already exists; skipping");
132: return null;
133: }
134:
135: if (!overwrite) {
136: throw new IOException(
137: file.getPath()
138: + " : already exists; please remove it or use the -overwrite or -ignore option.");
139: }
140:
141: System.out.println("Overwriting existing file " + file);
142: return file;
143: }
144:
145: public static String getDevJarName() {
146: if (sDevJarName == null) {
147: computeInstallationPath();
148: }
149: return sDevJarName;
150: }
151:
152: /**
153: * @param parent Parent directory of the requested directory.
154: * @param dirName Requested name for the directory.
155: * @param create Create the directory if it does not already exist?
156: * @return A {@link File} representing a directory that now exists.
157: * @throws IOException If the directory is not found and/or cannot be created.
158: */
159: public static File getDirectory(File parent, String dirName,
160: boolean create) throws IOException {
161: File dir = new File(parent, dirName);
162: boolean alreadyExisted = dir.exists();
163:
164: if (create) {
165: dir.mkdirs();
166: }
167:
168: if (!dir.exists() || !dir.isDirectory()) {
169: if (create) {
170: throw new IOException(dir.getPath()
171: + " : could not create directory.");
172: } else {
173: throw new IOException(dir.getPath()
174: + " : could not find directory.");
175: }
176: }
177:
178: if (create && !alreadyExisted) {
179: System.out.println("Created directory " + dir);
180: }
181:
182: return dir;
183: }
184:
185: /**
186: * @param dirPath Requested path for the directory.
187: * @param create Create the directory if it does not already exist?
188: * @return A {@link File} representing a directory that now exists.
189: * @throws IOException If the directory is not found and/or cannot be created.
190: */
191: public static File getDirectory(String dirPath, boolean create)
192: throws IOException {
193: return getDirectory(null, dirPath, create);
194: }
195:
196: /**
197: * Gets the contents of a file from the class path as a string.
198: *
199: * @param partialPath the partial path to the resource from this class's class
200: * file
201: * @return the contents of the file, or <code>null</code> if the file could
202: * not be found
203: * @throws IOException
204: */
205: public static String getFileFromClassPath(String partialPath)
206: throws IOException {
207: InputStream in = Utility.class.getClassLoader()
208: .getResourceAsStream(partialPath);
209: try {
210: if (in == null) {
211: throw new FileNotFoundException(partialPath);
212: }
213: ByteArrayOutputStream os = new ByteArrayOutputStream();
214: int ch;
215: while ((ch = in.read()) != -1) {
216: os.write(ch);
217: }
218: return new String(os.toByteArray(), "UTF-8");
219: } finally {
220: close(in);
221: }
222: }
223:
224: public static String getInstallPath() {
225: if (sInstallPath == null) {
226: computeInstallationPath();
227: }
228: return sInstallPath;
229: }
230:
231: public static void streamOut(File file, OutputStream out,
232: int bufferSize) throws IOException {
233: FileInputStream fis = null;
234: try {
235: fis = new FileInputStream(file);
236: streamOut(fis, out, bufferSize);
237: } finally {
238: com.google.gwt.util.tools.Utility.close(fis);
239: }
240: }
241:
242: public static void streamOut(InputStream in, OutputStream out,
243: int bufferSize) throws IOException {
244: assert (bufferSize >= 0);
245:
246: byte[] buffer = new byte[bufferSize];
247: int bytesRead = 0;
248: while (true) {
249: bytesRead = in.read(buffer);
250: if (bytesRead >= 0) {
251: // Copy the bytes out.
252: out.write(buffer, 0, bytesRead);
253: } else {
254: // End of input stream.
255: return;
256: }
257: }
258: }
259:
260: public static void writeTemplateFile(File file, String contents,
261: Map replacements) throws IOException {
262:
263: String replacedContents = contents;
264: Set entries = replacements.entrySet();
265: for (Iterator iter = entries.iterator(); iter.hasNext();) {
266: Map.Entry entry = (Map.Entry) iter.next();
267: String replaceThis = (String) entry.getKey();
268: String withThis = (String) entry.getValue();
269: withThis = withThis.replaceAll("\\\\", "\\\\\\\\");
270: withThis = withThis.replaceAll("\\$", "\\\\\\$");
271: replacedContents = replacedContents.replaceAll(replaceThis,
272: withThis);
273: }
274:
275: FileWriter fw = new FileWriter(file);
276: fw.write(replacedContents);
277: close(fw);
278: }
279:
280: private static void computeInstallationPath() {
281: try {
282: String override = System.getProperty("gwt.devjar");
283: if (override == null) {
284: String partialPath = Utility.class.getName().replace(
285: '.', '/').concat(".class");
286: URL url = Utility.class.getClassLoader().getResource(
287: partialPath);
288: if (url != null && "jar".equals(url.getProtocol())) {
289: String path = url.toString();
290: String jarPath = path.substring(path
291: .indexOf("file:"), path.lastIndexOf('!'));
292: File devJarFile = new File(URI.create(jarPath));
293: if (!devJarFile.isFile()) {
294: throw new IOException(
295: "Could not find jar file; "
296: + devJarFile.getCanonicalPath()
297: + " does not appear to be a valid file");
298: }
299: sDevJarName = devJarFile.getName();
300:
301: String dirPath = jarPath.substring(0, jarPath
302: .lastIndexOf('/') + 1);
303: File installDirFile = new File(URI.create(dirPath));
304: if (!installDirFile.isDirectory()) {
305: throw new IOException(
306: "Could not find installation directory; "
307: + installDirFile
308: .getCanonicalPath()
309: + " does not appear to be a valid directory");
310: }
311:
312: sInstallPath = installDirFile.getCanonicalPath()
313: .replace(File.separatorChar, '/');
314: } else {
315: throw new IOException(
316: "Cannot determine installation directory; apparently not running from a jar");
317: }
318: } else {
319: override = override.replace('\\', '/');
320: int pos = override.lastIndexOf('/');
321: if (pos < 0) {
322: sInstallPath = "";
323: sDevJarName = override;
324: } else {
325: sInstallPath = override.substring(0, pos);
326: sDevJarName = override.substring(pos + 1);
327: }
328: }
329: } catch (IOException e) {
330: throw new RuntimeException(
331: "Installation problem detected, please reinstall GWT",
332: e);
333: }
334: }
335:
336: }
|