KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > config > backup > util > FileUtils


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23
24 package com.sun.enterprise.config.backup.util;
25
26 import java.io.*;
27 import java.util.*;
28
29 public class FileUtils
30 {
31     private FileUtils()
32     {
33     }
34     
35     ///////////////////////////////////////////////////////////////////////////
36

37     public static boolean safeIsDirectory(File f)
38     {
39         if(f == null || !f.exists() || !f.isDirectory())
40             return false;
41         
42         return true;
43     }
44     
45     ///////////////////////////////////////////////////////////////////////////
46

47     public static boolean safeIsDirectory(String JavaDoc s)
48     {
49         return safeIsDirectory(new File(s));
50     }
51     
52     ///////////////////////////////////////////////////////////////////////////
53
/*
54     public static boolean safeIsRealDirectory(String s)
55     {
56         return safeIsRealDirectory(new File(s));
57     }
58     */

59     ///////////////////////////////////////////////////////////////////////////
60

61     /*
62     public static boolean safeIsRealDirectory(File f)
63     {
64         if(safeIsDirectory(f) == false)
65             return false;
66         
67         // these 2 values while be different for symbolic links
68         String canonical = safeGetCanonicalPath(f);
69         String absolute = f.getAbsolutePath();
70         
71         if(canonical.equals(absolute))
72             return true;
73         */

74         /* Bug 4715043 -- WHOA -- Bug Obscura!!
75          * In Windows, if you create the File object with, say, "d:/foo", then the
76          * absolute path will be "d:\foo" and the canonical path will be "D:\foo"
77          * and they won't match!!!
78          **/

79          /*
80         if(OS.isWindows() && canonical.equalsIgnoreCase(absolute))
81             return true;
82         
83         return false;
84     }
85     */

86     
87     ///////////////////////////////////////////////////////////////////////////
88

89     public static String JavaDoc safeGetCanonicalPath(File f)
90     {
91         if(f == null)
92             return null;
93         
94         try
95         {
96             return f.getCanonicalPath();
97         }
98         catch(IOException e)
99         {
100             return f.getAbsolutePath();
101         }
102     }
103     
104     ///////////////////////////////////////////////////////////////////////////
105

106     public static File safeGetCanonicalFile(File f)
107     {
108         if(f == null)
109             return null;
110         
111         try
112         {
113             return f.getCanonicalFile();
114         }
115         catch(IOException e)
116         {
117             return f.getAbsoluteFile();
118         }
119     }
120     
121     ///////////////////////////////////////////////////////////////////////////
122

123     public static boolean isZip(String JavaDoc filename)
124     {
125         return hasExtensionIgnoreCase(filename, ".zip");
126     }
127     
128     ///////////////////////////////////////////////////////////////////////////
129

130     public static boolean isZip(File f)
131     {
132         return hasExtensionIgnoreCase(f, ".zip");
133     }
134     
135     /////////////////////////////////////////////////////////
136

137     public static void whack(File parent)
138     {
139         if(safeIsDirectory(parent))
140         {
141             File[] kids = parent.listFiles();
142             
143             for(int i = 0; i < kids.length; i++)
144             {
145                 File f = kids[i];
146                 
147                 if(f.isDirectory())
148                     whack(f);
149                 
150                 if(!f.delete())
151                 {
152                     f.deleteOnExit();
153                 }
154             }
155         }
156         
157         parent.delete();
158     }
159
160     /**
161      */

162     
163     public static boolean protect(File f)
164     {
165         if(!f.exists())
166             return true;
167         
168         if(OS.isUNIX())
169             return protectUNIX(f);
170         else
171             return protectWindows(f);
172     }
173     
174     /**
175      **/

176     
177     public static boolean makeExecutable(File f)
178     {
179         if(!OS.isUNIX())
180             return true; // no such thing in Windows...
181

182         if(!f.exists())
183             return true; // no harm, no foul...
184

185         if(!f.isDirectory())
186             return makeExecutable(new File[] { f} );
187         
188         // if we get here -- f is a directory
189

190         return makeExecutable(f.listFiles());
191     }
192     /**
193      * Copies the entire tree to a new location.
194      *
195      * @param sourceTree File pointing at root of tree to copy
196      * @param destTree File pointing at root of new tree
197      *
198      * @exception IOException if an error while copying the content
199      */

200     public static void copyTree(File din, File dout) throws IOException
201     {
202         if(!safeIsDirectory(din))
203             throw new IllegalArgumentException JavaDoc("Source isn't a directory");
204         
205         dout.mkdirs();
206         
207         if(!safeIsDirectory(dout))
208             throw new IllegalArgumentException JavaDoc("Can't create destination directory");
209         
210         FileListerRelative flr = new FileListerRelative(din);
211         String JavaDoc[] files = flr.getFiles();
212         
213         for(int i = 0; i < files.length; i++)
214         {
215             File fin = new File(din, files[i]);
216             File fout = new File(dout, files[i]);
217             
218             copy(fin, fout);
219         }
220     }
221     
222     ///////////////////////////////////////////////////////////////////////////
223
////// PRIVATE METHODS ///////////////////////////////////////////
224
///////////////////////////////////////////////////////////////////////////
225

226     private static boolean hasExtension(String JavaDoc filename, String JavaDoc ext)
227     {
228         if(filename == null || filename.length() <= 0)
229             return false;
230         
231         return filename.endsWith(ext);
232     }
233     
234     ///////////////////////////////////////////////////////////////////////////
235

236     private static boolean hasExtension(File f, String JavaDoc ext)
237     {
238         if(f == null || !f.exists())
239             return false;
240         
241         return f.getName().endsWith(ext);
242     }
243     
244     ///////////////////////////////////////////////////////////////////////////
245

246     private static boolean hasExtensionIgnoreCase(String JavaDoc filename, String JavaDoc ext)
247     {
248         if(filename == null || filename.length() <= 0)
249             return false;
250         
251         return filename.toLowerCase().endsWith(ext.toLowerCase());
252     }
253     
254     ///////////////////////////////////////////////////////////////////////////
255

256     private static boolean hasExtensionIgnoreCase(File f, String JavaDoc ext)
257     {
258         if(f == null || !f.exists())
259             return false;
260         
261         return f.getName().toLowerCase().endsWith(ext.toLowerCase());
262     }
263     
264     /**
265      * Copies the bytes from the given input stream to the output stream.
266      * It closes the streams afterwards.
267      *
268      * @param inStream input stream from the src
269      * @param outStream output stream to the destination
270      *
271      * @exception IOException if an error while copying the content
272      */

273     private static void copy(InputStream inStream, OutputStream outStream) throws IOException
274     {
275         copyWithoutClose(inStream, outStream);
276         
277         // closes the streams
278
inStream.close();
279         outStream.close();
280     }
281     
282     /**
283      * Copies the bytes from the given input stream to the output stream.
284      * It does not close the streams afterwards.
285      *
286      * @param inStream input stream from the src
287      * @param outStream output stream to the destination
288      *
289      * @exception IOException if an error while copying the content
290      */

291     private static void copyWithoutClose(InputStream inStream, OutputStream outStream) throws IOException
292     {
293         BufferedInputStream bis = new BufferedInputStream(inStream, BUFFER_SIZE);
294         BufferedOutputStream bos = new BufferedOutputStream(outStream, BUFFER_SIZE);
295         byte[] buf = new byte[BUFFER_SIZE];
296
297         int len = 0;
298         while (len != -1)
299         {
300             try
301             {
302                 len = bis.read(buf, 0, buf.length);
303             }
304             catch (EOFException eof)
305             {
306                 break;
307             }
308
309             if (len != -1)
310             {
311                 bos.write(buf, 0, len);
312             }
313         }
314         bos.flush();
315     }
316     /**
317      * Copies a file.
318      *
319      * @param from Name of file to copy
320      * @param to Name of new file
321      * @exception IOException if an error while copying the content
322      */

323     private static void copy(String JavaDoc from, String JavaDoc to) throws IOException
324     {
325         //if(!StringUtils.ok(from) || !StringUtils.ok(to))
326
if(from == null || to == null)
327             throw new IllegalArgumentException JavaDoc("null or empty filename argument");
328         
329         File fin = new File(from);
330         File fout = new File(to);
331         
332         copy(fin, fout);
333     }
334     /**
335      * Copies a file.
336      *
337      * @param from File to copy
338      * @param to New file
339      *
340      * @exception IOException if an error while copying the content
341      */

342     private static void copy(File fin, File fout) throws IOException
343     {
344         if(safeIsDirectory(fin))
345         {
346             copyTree(fin, fout);
347             return;
348         }
349         
350         if(!fin.exists())
351             throw new IllegalArgumentException JavaDoc("File source doesn't exist");
352         
353         if(!safeIsDirectory(fout.getParentFile()))
354             fout.getParentFile().mkdirs();
355         
356         copy(new FileInputStream(fin), new FileOutputStream(fout));
357     }
358     
359     ///////////////////////////////////////////////////////////////////////////
360

361     private static boolean protectUNIX(File f)
362     {
363         if(f == null)
364             return false;
365         
366         try
367         {
368             List<String JavaDoc> cmds = new ArrayList<String JavaDoc>();
369             File[] files = null;
370             ProcessBuilder JavaDoc pb = null;
371             Process JavaDoc p = null;
372             boolean ret = false;
373             
374             if(f.isDirectory())
375             {
376                 // chmod to rwx------
377
// and chmod files inside dir to rw-------
378
cmds.add("chmod");
379                 cmds.add("0700");
380                 cmds.add(safeGetCanonicalPath(f));
381                 pb = new ProcessBuilder JavaDoc(cmds);
382                 p = pb.start();
383                 ret = p.waitFor() == 0 ? true : false;
384                 
385                 files = f.listFiles();
386         
387                 if(files == null || files.length < 1)
388                     return ret;
389             }
390             else
391             {
392                 ret = true;
393                 files = new File[] { f };
394             }
395             cmds.clear();
396             cmds.add("chmod");
397             cmds.add("0600");
398             
399             for(File file : files)
400                 cmds.add(safeGetCanonicalPath(file));
401             
402             pb = new ProcessBuilder JavaDoc(cmds);
403             p = pb.start();
404
405             // if either chmod returned false -- return false...
406
return ret && (p.waitFor() == 0 ? true : false);
407         }
408         catch(Exception JavaDoc e)
409         {
410             return false;
411         }
412     }
413     
414     ///////////////////////////////////////////////////////////////////////////
415

416     private static boolean protectWindows(File f)
417     {
418         // this is ugly. We'return calling a program installed with Windows.
419
// The program wants to confirm a change so we have to give it a 'Y'
420
// at runtime...
421

422         String JavaDoc fname = f.getAbsolutePath();
423         String JavaDoc uname = System.getProperty("user.name");
424         
425         try
426         {
427             ProcessBuilder JavaDoc pb = new ProcessBuilder JavaDoc("cacls", fname, "/G", uname + ":F");
428             Process JavaDoc p = pb.start();
429             BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
430             writer.write('Y');
431             writer.newLine();
432             writer.flush();
433             return p.waitFor() == 0 ? true : false;
434         }
435         catch(Exception JavaDoc e)
436         {
437             return false;
438         }
439     }
440     
441     ///////////////////////////////////////////////////////////////////////////
442

443     private static boolean makeExecutable(File[] files)
444     {
445         // WBN October 2005
446
// dirspace bugfix -- what if there is a space in the dirname? trouble!
447
// changed the argument to a File array
448

449         // we are using a String here so that you can pass in a bunch
450
// of space-separated filenames. Doing it one at a time would be inefficient...
451
// make it executable for ONLY the user
452

453         // Jan 19, 2005 -- rolled back the fix for 6206176. It has been decided
454
// that this is not a bug but rather a security feature.
455

456
457         // BUGFIX: 6206176
458
// permissions changed from 744 to 755.
459
// The reason is that if user 'A' does a restore then user 'A' will be the only
460
// user allowed to start or stop a domain. Whether or not a user is allowed to start a domain
461
// needs to be based on the AppServer authentication mechanism (username-password) rather
462
// than on the OS authentication mechanism.
463
// This case actually is common: user 'A' does the restore, root tries to start the restored domain.
464

465         if(files == null || files.length <= 0)
466             return true;
467         
468         List<String JavaDoc> cmds = new ArrayList<String JavaDoc>();
469         
470         cmds.add("chmod");
471         cmds.add("0744");
472         
473         for(File f : files)
474             cmds.add(safeGetCanonicalPath(f));
475
476         try
477         {
478             ProcessBuilder JavaDoc pb = new ProcessBuilder JavaDoc(cmds);
479             Process JavaDoc p = pb.start();
480             return p.waitFor() == 0 ? true : false;
481         }
482         catch(Exception JavaDoc e)
483         {
484             return false;
485         }
486     }
487     
488     ///////////////////////////////////////////////////////////////////////////
489

490     private static final int BUFFER_SIZE = 0x10000; // 64k
491
private final static char[] ILLEGAL_FILENAME_CHARS =
492     {'/', '\\', ':', '*', '?', '"', '<', '>', '|' };
493     private final static String JavaDoc ILLEGAL_FILENAME_STRING = "\\/:*?\"<>|";
494     private final static char REPLACEMENT_CHAR = '_';
495     private final static char BLANK = ' ';
496     private final static char DOT = '.';
497     private static String JavaDoc TMPFILENAME = "scratch";
498 }
499
Popular Tags