KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > tool > common > FileUtil


1
2 /*
3  * Enhydra Java Application Server Project
4  *
5  * The contents of this file are subject to the Enhydra Public License
6  * Version 1.1 (the "License"); you may not use this file except in
7  * compliance with the License. You may obtain a copy of the License on
8  * the Enhydra web site ( http://www.enhydra.org/ ).
9  *
10  * Software distributed under the License is distributed on an "AS IS"
11  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
12  * the License for the specific terms governing rights and limitations
13  * under the License.
14  *
15  * The Initial Developer of the Enhydra Application Server is Lutris
16  * Technologies, Inc. The Enhydra Application Server and portions created
17  * by Lutris Technologies, Inc. are Copyright Lutris Technologies, Inc.
18  * All Rights Reserved.
19  *
20  * Contributor(s):
21  * Paul Mahar
22  *
23  */

24 package org.enhydra.tool.common;
25
26 // Standard imports
27
import java.io.BufferedInputStream JavaDoc;
28 import java.io.BufferedOutputStream JavaDoc;
29 import java.io.IOException JavaDoc;
30 import java.io.File JavaDoc;
31 import java.io.FileFilter JavaDoc;
32 import java.io.FileInputStream JavaDoc;
33 import java.io.FileNotFoundException JavaDoc;
34 import java.io.FileOutputStream JavaDoc;
35 import java.io.InputStream JavaDoc;
36 import java.io.OutputStream JavaDoc;
37 import java.net.URL JavaDoc;
38 import java.net.URLClassLoader JavaDoc;
39 import java.util.ArrayList JavaDoc;
40 import java.util.ResourceBundle JavaDoc;
41
42 //
43
public class FileUtil {
44     static ResourceBundle JavaDoc res =
45         ResourceBundle.getBundle("org.enhydra.tool.common.Res"); // nores
46

47     public static void copy(InputStream JavaDoc source,
48                             OutputStream JavaDoc dest) throws IOException JavaDoc {
49         BufferedInputStream JavaDoc in = null;
50         BufferedOutputStream JavaDoc out = null;
51         int read = 1;
52         int readSum = 0;
53         int available = 1;
54         int sleepCount = 0;
55
56         if (source instanceof BufferedInputStream JavaDoc) {
57             in = (BufferedInputStream JavaDoc) source;
58         } else {
59             in = new BufferedInputStream JavaDoc(source);
60         }
61         if (dest instanceof BufferedOutputStream JavaDoc) {
62             out = (BufferedOutputStream JavaDoc) dest;
63         } else {
64             out = new BufferedOutputStream JavaDoc(dest);
65         }
66         while (true) {
67             byte[] bytes = new byte[0];
68
69             available = in.available();
70             if (available < 1) {
71                 out.flush();
72                 if ((read < bytes.length) && (readSum > 0)) {
73                     break;
74                 } else if (sleepCount > 10) {
75                     break;
76                 } else {
77                     FileUtil.sleep(100);
78                     sleepCount++;
79                     available = in.available();
80                 }
81             }
82             if (available > 2048) {
83                 bytes = new byte[2048];
84             } else if (available > 1024) {
85                 bytes = new byte[1024];
86             } else if (available > 256) {
87                 bytes = new byte[256];
88             } else if (available > 16) {
89                 bytes = new byte[16];
90             } else {
91                 bytes = new byte[1];
92             }
93             read = in.read(bytes, 0, bytes.length);
94             if (read > 0) {
95               readSum += read;
96               out.write(bytes, 0, read);
97            }
98         }
99         out.flush();
100     }
101
102     //
103
public static File JavaDoc copy(InputStream JavaDoc source,
104                             File JavaDoc dest) throws ToolException {
105         FileOutputStream JavaDoc out = null;
106
107         try {
108             out = new FileOutputStream JavaDoc(dest);
109             FileUtil.copy(source, out);
110             source.close();
111             out.flush();
112             out.close();
113         } catch (FileNotFoundException JavaDoc e) {
114             String JavaDoc mess = new String JavaDoc();
115
116             mess = ResUtil.format(res.getString("Unable_to_create_0_"), dest);
117             throw new ToolException(e, mess);
118         } catch (IOException JavaDoc e) {
119             String JavaDoc mess = new String JavaDoc();
120
121             mess = ResUtil.format(res.getString("Unable_to_create_0_"), dest);
122             throw new ToolException(e, mess);
123         }
124         return dest;
125     }
126
127     public static File JavaDoc copy(Template source, File JavaDoc dest) throws ToolException {
128         File JavaDoc parentFile = null;
129         InputStream JavaDoc in = null;
130
131         if (source.isDirectory()) {
132             if (dest.isDirectory()) {
133                 return dest;
134             } else if (dest.exists()) {
135                 String JavaDoc mess = new String JavaDoc();
136
137                 mess = ResUtil.format(res.getString("Unable_to_copy"),
138                                       source.toString(), dest);
139                 throw new ToolException(mess);
140             } else {
141                 dest = source.getOutput();
142                 dest.mkdirs();
143                 return dest;
144             }
145         }
146         if (source.isFile() && dest.isDirectory()) {
147             parentFile = new File JavaDoc(dest.getAbsolutePath());
148             dest = source.getOutput();
149         } else {
150             parentFile = new File JavaDoc(dest.getParent());
151         }
152         parentFile.mkdirs();
153         try {
154             in = source.getInputStream();
155             dest = FileUtil.copy(in, dest);
156         } catch (IOException JavaDoc e) {
157             e.printStackTrace(System.err);
158             String JavaDoc mess = new String JavaDoc();
159
160             mess = ResUtil.format(res.getString("Unable_to_copy_file"),
161                                   source.toString(), dest);
162             throw new ToolException(e, mess);
163         } catch (ToolException e) {
164             e.printStackTrace(System.err);
165             String JavaDoc mess = new String JavaDoc();
166
167             mess = ResUtil.format(res.getString("Unable_to_copy_file"),
168                                   source.toString(), dest);
169             throw new ToolException(e, mess);
170         }
171         return dest;
172     }
173
174     public static File JavaDoc copy(File JavaDoc source, File JavaDoc dest) throws ToolException {
175         File JavaDoc parentFile = null;
176         FileInputStream JavaDoc in = null;
177
178         if (source.isDirectory()) {
179             if (dest.isDirectory()) {
180                 return dest;
181             } else if (dest.exists()) {
182                 String JavaDoc mess = new String JavaDoc();
183
184                 mess = ResUtil.format(res.getString("Unable_to_copy"),
185                                       source, dest);
186                 throw new ToolException(mess);
187             } else {
188                 dest = new File JavaDoc(dest, source.getName());
189                 dest.mkdirs();
190                 return dest;
191             }
192         }
193         if (source.isFile() && dest.isDirectory()) {
194             parentFile = new File JavaDoc(dest.getAbsolutePath());
195             dest = new File JavaDoc(dest, source.getName());
196         } else {
197             parentFile = new File JavaDoc(dest.getParent());
198         }
199         parentFile.mkdirs();
200         try {
201             in = new FileInputStream JavaDoc(source);
202             dest = FileUtil.copy(in, dest);
203         } catch (FileNotFoundException JavaDoc e) {
204             String JavaDoc mess = new String JavaDoc();
205
206             mess = ResUtil.format(res.getString("Unable_to_copy_file"),
207                                   source, dest);
208             throw new ToolException(e, mess);
209         } catch (ToolException e) {
210             String JavaDoc mess = new String JavaDoc();
211
212             mess = ResUtil.format(res.getString("Unable_to_copy_file"),
213                                   source, dest);
214             throw new ToolException(e, mess);
215         }
216         return dest;
217     }
218
219     public static boolean isDirectory(String JavaDoc path) {
220         boolean dir = false;
221
222         if (path != null) {
223             File JavaDoc file = new File JavaDoc(path);
224
225             dir = file.isDirectory();
226         }
227         return dir;
228     }
229
230     public static boolean isFile(String JavaDoc path) {
231         boolean file = false;
232
233         if (path != null) {
234             File JavaDoc f = new File JavaDoc(path);
235
236             file = f.isFile();
237         }
238         return file;
239     }
240
241     public static String JavaDoc toCanonicalPath(final String JavaDoc in) {
242         final String JavaDoc DOT = new String JavaDoc() + '.';
243         String JavaDoc current = FileUtil.toCurrentPath(in);
244         String JavaDoc out = new String JavaDoc(current);
245         int index = -1;
246
247         index = in.indexOf(DOT + DOT);
248         if (index < 0) {
249             index = current.indexOf(File.separator + '.');
250         }
251         if (index < 0) {
252             index = current.indexOf('.' + File.separator);
253         }
254         if ((index > -1) || in.startsWith(DOT) || in.endsWith(DOT)) {
255             File JavaDoc file = new File JavaDoc(current);
256
257             try {
258                 out = file.getCanonicalPath();
259             } catch (Exception JavaDoc e) {
260                 out = current;
261                 e.printStackTrace();
262             }
263         }
264         return out;
265     }
266
267     public static String JavaDoc toJavaPath(final String JavaDoc in) {
268         String JavaDoc path = new String JavaDoc(in);
269
270         path = FileUtil.toCurrentPath(path);
271         return path.replace('\\', '/');
272     }
273
274     public static String JavaDoc toCurrentPath(String JavaDoc path) {
275         String JavaDoc cPath = path;
276         File JavaDoc file;
277
278         if (File.separatorChar == '/') {
279             cPath = FileUtil.toShellPath(cPath);
280         } else {
281             cPath = FileUtil.toWindowsPath(cPath);
282         }
283         file = new File JavaDoc(cPath);
284
285         // Add default drive
286
file = new File JavaDoc(file.getAbsolutePath());
287         if (file.exists()) {
288             cPath = file.getAbsolutePath();
289         }
290         return cPath.trim();
291     }
292
293     /**
294      * Convert the given path to contain file seperators for
295      * a Unix shell. This also converts paths that start with a
296      * a Windows drive letter into one compatible with the
297      * Cygnus shell.
298      *
299      * @param path
300      * File path containing any combination of unix shell and Windows file
301      * seperators.
302      *
303      * @return
304      * The path compatible with the Cygnus shell.
305      */

306     public static String JavaDoc toShellPath(String JavaDoc inPath) {
307         StringBuffer JavaDoc path = new StringBuffer JavaDoc();
308         int index = -1;
309
310         inPath = inPath.trim();
311         index = inPath.indexOf(":\\"); // nores
312
inPath = inPath.replace('\\', '/');
313         if (index > -1) {
314             path.append("//"); // nores
315
path.append(inPath.substring(0, index));
316             path.append('/');
317             path.append(inPath.substring(index + 2));
318         } else {
319             path.append(inPath);
320         }
321         return path.toString();
322     }
323
324     /**
325      * Convert the given path to contain file seperators for
326      * Windows. This also converts paths that start with a
327      * '\\' into paths that start with a Windows drive letter.
328      *
329      * @param path
330      * File path containing any combination of unix shell and Windows file
331      * seperators.
332      *
333      * @return
334      * The path compatible with the Windows.
335      */

336     public static String JavaDoc toWindowsPath(String JavaDoc path) {
337         String JavaDoc winPath = path;
338         int index = winPath.indexOf("//"); // nores
339

340         if (index > -1) {
341             winPath = winPath.substring(0, index) + ":\\" // nores
342
+ winPath.substring(index + 2);
343         }
344         index = winPath.indexOf(':');
345         if (index == 1) {
346             winPath = winPath.substring(0, 1).toUpperCase()
347                       + winPath.substring(1);
348         }
349         winPath = winPath.replace('/', '\\');
350         return winPath;
351     }
352
353     public static File JavaDoc findFirst(FileFilter JavaDoc filter, String JavaDoc path) {
354         return FileUtil.findFirst(filter, new File JavaDoc(path), 0);
355     }
356
357     public static File JavaDoc findFirst(FileFilter JavaDoc filter, File JavaDoc dir, int count) {
358         final String JavaDoc DIR_CLASSES = "classes"; // nores
359
final String JavaDoc DIR_OUTPUT = "output"; // nores
360
File JavaDoc[] files = dir.listFiles(filter);
361         File JavaDoc found = null;
362         File JavaDoc candidate = null;
363
364         if (count > 500) {
365
366             // abort find if we've already searched through 500 directories
367
} else {
368             count++;
369             if (files != null && files.length >= 1) {
370                 found = files[0];
371             }
372             if (found == null) {
373                 files = dir.listFiles();
374                 if (files != null) {
375                     for (int i = 0; i < files.length; i++) {
376                         if (files[i].isDirectory()) {
377                             if (files[i].getName().equalsIgnoreCase(DIR_CLASSES)
378                                     || files[i].getName().equalsIgnoreCase(DIR_OUTPUT)) {
379
380                                 // ignore
381
} else {
382                                 candidate = FileUtil.findFirst(filter,
383                                                                files[i],
384                                                                count);
385                                 if (found == null) {
386                                     found = candidate;
387                                 } else if (candidate != null) {
388                                     if (FileUtil.charCount(found.getAbsolutePath(), File.separatorChar)
389                                             > FileUtil.charCount(candidate.getAbsolutePath(),
390                                                                  File.separatorChar)) {
391                                         found = candidate;
392                                     }
393                                 }
394                             }
395                         }
396                     }
397                 }
398             }
399         }
400         return found;
401     }
402
403     public static String JavaDoc[] findJarPaths(String JavaDoc jar, ClassLoader JavaDoc loader) {
404
405         //
406
ArrayList JavaDoc list = new ArrayList JavaDoc();
407         String JavaDoc[] paths = new String JavaDoc[0];
408         URLClassLoader JavaDoc urlLoader = null;
409
410         if (loader == null || (!(loader instanceof URLClassLoader JavaDoc))) {
411             loader = ClassLoader.getSystemClassLoader();
412         }
413         if (loader instanceof URLClassLoader JavaDoc) {
414             urlLoader = (URLClassLoader JavaDoc) loader;
415             for (int i = 0; i < urlLoader.getURLs().length; i++) {
416                 String JavaDoc path = null;
417                 PathHandle ph = null;
418
419                 path = urlLoader.getURLs()[i].getFile().toLowerCase();
420                 if (path.endsWith(jar.toLowerCase())) {
421                     if (path.charAt(2) == ':') {
422                         path = path.substring(1);
423                     }
424                     ph = PathHandle.createPathHandle(path);
425                     if (ph.isFile()) {
426                         list.add(ph.getPath());
427                     }
428                 }
429             }
430             list.trimToSize();
431             paths = new String JavaDoc[list.size()];
432             paths = (String JavaDoc[]) list.toArray(paths);
433             list.clear();
434         }
435         return paths;
436     }
437
438     private static int charCount(String JavaDoc in, char lookFor) {
439         String JavaDoc search = new String JavaDoc(in);
440         int index = search.indexOf(lookFor);
441         int count = 0;
442
443         while (index > 0) {
444             count++;
445             search = search.substring(index + 1);
446             index = search.indexOf(lookFor);
447         }
448         return count;
449     }
450
451     private static void sleep(int m) {
452         try {
453             Thread.sleep(m);
454         } catch (InterruptedException JavaDoc e) {
455             e.printStackTrace(System.err);
456         }
457     }
458
459 }
460
Popular Tags