KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openlaszlo > utils > FileUtils


1 /* *****************************************************************************
2  * FileUtils.java
3  * ****************************************************************************/

4
5 /* J_LZ_COPYRIGHT_BEGIN *******************************************************
6 * Copyright 2001-2004 Laszlo Systems, Inc. All Rights Reserved. *
7 * Use is subject to license terms. *
8 * J_LZ_COPYRIGHT_END *********************************************************/

9
10 package org.openlaszlo.utils;
11
12 import org.openlaszlo.server.LPS;
13
14 import java.io.File JavaDoc;
15 import java.io.RandomAccessFile JavaDoc;
16 import java.io.IOException JavaDoc;
17 import java.io.FileNotFoundException JavaDoc;
18 import java.io.FilenameFilter JavaDoc;
19 import java.io.FileInputStream JavaDoc;
20 import java.io.InputStream JavaDoc;
21 import java.io.OutputStream JavaDoc;
22 import java.io.FileOutputStream JavaDoc;
23 import java.io.FilterOutputStream JavaDoc;
24 import java.io.FilterInputStream JavaDoc;
25 import java.io.ByteArrayOutputStream JavaDoc;
26 import java.io.PushbackInputStream JavaDoc;
27
28 import java.io.ByteArrayInputStream JavaDoc;
29
30 import java.io.Writer JavaDoc;
31 import java.io.Writer JavaDoc;
32 import java.io.Reader JavaDoc;
33 import java.io.StringWriter JavaDoc;
34 import java.util.*;
35 import java.util.zip.*;
36
37 import org.apache.log4j.*;
38 import org.apache.oro.text.regex.*;
39
40 // A dir is absolute if it begins with "" (the empty string to
41
// the left of the initial '/'), or a drive letter.
42
class AbsolutePathnameTester {
43      static boolean test(List dirs) {
44         if (!dirs.isEmpty()) {
45             String JavaDoc dir = (String JavaDoc) dirs.get(0);
46             // Add '/' since c:/ will be split to c:, which
47
// isn't absolute. Also turns "" into "/" which
48
// is absolute, so the UNIX case can share this
49
// test.
50
return new File JavaDoc(dir + "/").isAbsolute();
51         }
52         return false;
53     }
54 }
55
56 /**
57  * A utility class containing file utility functions.
58  *
59  * @author Oliver Steele
60  * @author Eric Bloch
61  */

62 public abstract class FileUtils {
63
64     private static Logger mLogger = Logger.getLogger(FileUtils.class);
65
66     // TODO: [2003-09-23 bloch] could build out the encoder a bit more
67
public static final String JavaDoc GZIP = "gzip";
68     public static final String JavaDoc DEFLATE = "deflate";
69     public static final int GZIP_HEADER_LENGTH = 10;
70     public static final int MIN_GZIP_PEEK = 2;
71     public static final int MIN_SWF_PEEK = 9;
72
73     public static int BUFFER_SIZE = 10240;
74     public static int THROTTLE = 0;
75
76     static {
77         try {
78             String JavaDoc throttle = LPS.getProperty("lps.throttle");
79             BUFFER_SIZE = Integer.parseInt(LPS.getProperty("buffer.size", "10240"));
80             if (throttle != null) {
81                 THROTTLE = Integer.parseInt(throttle);
82                 BUFFER_SIZE = 1024;
83                 mLogger.info("throttle " + throttle);
84             }
85
86
87         } catch (RuntimeException JavaDoc e) {
88             mLogger.error("Exception initializing FileUtils", e);
89         } catch (Exception JavaDoc e) {
90             mLogger.error("Exception initializing FileUtils", e);
91         }
92     }
93
94     /** Returns the contents of <var>file</var> as a byte[].
95      * @param file a File
96      * @return a byte[]
97      * @throws IOException if an error occurs
98      */

99     public static byte[] readFileBytes(File JavaDoc file)
100         throws IOException JavaDoc
101     {
102         java.io.InputStream JavaDoc istr = new java.io.FileInputStream JavaDoc(file);
103         byte bytes[] = new byte[istr.available()];
104         istr.read(bytes);
105         istr.close();
106         return bytes;
107     }
108
109     /** Returns the contents of <var>file</var> as a String, using UTF-8 character encoding <var>encoding</var>.
110      * @param file a File
111      * @return a String
112      * @throws IOException if an error occurs
113      */

114
115     public static String JavaDoc readFileString(File JavaDoc file)
116         throws IOException JavaDoc
117     {
118         byte data[] = readFileBytes(file);
119         return new String JavaDoc(data, "UTF-8");
120     }
121
122     /** Returns the contents of <var>file</var> as a String, using character encoding <var>encoding</var>.
123      * @param file a File
124      * @param encoding a character set encoding name
125      * @return a String
126      * @throws IOException if an error occurs
127      */

128
129     public static String JavaDoc readFileString(File JavaDoc file, String JavaDoc defaultEncoding)
130         throws IOException JavaDoc
131     {
132         Reader JavaDoc reader = makeXMLReaderForFile(file.getAbsolutePath(), defaultEncoding);
133         StringWriter JavaDoc s = new StringWriter JavaDoc();
134         send(reader, s);
135         reader.close();
136         return s.toString();
137     }
138
139
140     /** Attempt to deduce the encoding of an XML file, by looking for the "encoding" attribute in the
141      * XML declaration.
142      * Default is to return "UTF-8"
143      * @param pathname a filename
144      * @return the encoding name
145      * @throws IOException if an error occurs
146      */

147     public static String JavaDoc getXMLEncodingFromFile(String JavaDoc pathname, String JavaDoc defaultEncoding)
148       throws IOException JavaDoc {
149         java.io.FileInputStream JavaDoc ifs = new java.io.FileInputStream JavaDoc(pathname);
150         ByteArrayOutputStream JavaDoc bout = new ByteArrayOutputStream JavaDoc();
151         send(ifs, bout);
152         Perl5Matcher matcher = new Perl5Matcher();
153         try {
154             Perl5Compiler compiler = new Perl5Compiler();
155             Pattern pattern = compiler.compile("[^<]*\\s*<[?]xml\\s+[^>]*encoding=[\"'](.*)['\"][^>]*?>");
156             if (matcher.contains(new String JavaDoc(bout.toByteArray()), pattern)) {
157                 MatchResult result = matcher.getMatch();
158                 String JavaDoc encoding = result.group(1);
159                 return encoding;
160             } else {
161                 return "UTF-8";
162             }
163         } catch (MalformedPatternException e) {
164             throw new RuntimeException JavaDoc(e.getMessage());
165         }
166     }
167
168     /**
169      * Set up a reader for an XML file with the correct charset encoding, and strip
170      * out any Unicode Byte Order Mark if there is one present. We need to scan the file
171      * once to try to parse the charset encoding in the XML declaration.
172      * @param pathname the name of a file to open
173      * @return reader stream for the file
174      */

175     public static Reader JavaDoc makeXMLReaderForFile (String JavaDoc pathname, String JavaDoc defaultEncoding)
176       throws IOException JavaDoc {
177         String JavaDoc encoding = getXMLEncodingFromFile(pathname, defaultEncoding);
178         java.io.FileInputStream JavaDoc ifs = new java.io.FileInputStream JavaDoc(pathname);
179         java.io.PushbackInputStream JavaDoc pbis = new java.io.PushbackInputStream JavaDoc(ifs, 1024);
180         // We will ignore the byte order mark encoding for now,
181
// hopefully no one is going to be using UTF16. I don't want
182
// to deal right now with the case where the XML encoding
183
// directive conflicts with the byte order mark.
184
FileUtils.stripByteOrderMark(pbis);
185         return new java.io.InputStreamReader JavaDoc(pbis, encoding);
186     }
187     
188     /** Read a (pushback-able) byte input stream looking for some form of
189         Unicode Byte Order Mark Defaults. If found, strip it out.
190      * @param pbis a byte input stream
191      * @return encoding name, defaults to null if we have no byte order mark
192      */

193     public static String JavaDoc stripByteOrderMark (PushbackInputStream JavaDoc pbis) throws IOException JavaDoc {
194         // We need to peek at the stream and if the first three chars
195
// are a UTF-8 or UTF-16 encoded BOM (byte order mark) we will
196
// discard them.
197
int c1 = pbis.read();
198         int c2 = pbis.read();
199         int c3 = pbis.read();
200         if (c1 == 0xFF & c2 == 0xFE) {
201             // UTF16 Big Endian BOM
202
// discard the first two chars
203
pbis.unread(c3);
204             return "UTF-16BE";
205         } else if (c1 == 0xFE & c2 == 0xFF) {
206             // UTF16 Little Endian BOM
207
// discard the first two chars
208
pbis.unread(c3);
209             return "UTF-16LE";
210         } else if (c1 == 0xEF && c2 == 0xBB && c3 == 0xBF) {
211             // UTF-8 BOM
212
// discard all three chars
213
return "UTF-8";
214         } else {
215             // Otherwise put back the chars we just read and proceed
216
pbis.unread(c3);
217             pbis.unread(c2);
218             pbis.unread(c1);
219             return null;
220         }
221     }
222
223     /**
224      * @param file file to read
225      * @return size of file
226      * @throws FileNotFoundException
227      * @throws IOException
228      */

229     static public long fileSize(File JavaDoc file)
230         throws IOException JavaDoc, FileNotFoundException JavaDoc {
231
232         RandomAccessFile JavaDoc raf = null;
233         try {
234             raf = new RandomAccessFile JavaDoc(file, "r");
235             return raf.length();
236         } finally {
237             if (raf != null) {
238                 try {
239                     raf.close();
240                 } catch (Exception JavaDoc e) {
241                     mLogger.warn("ignoring exception while closing random access file: ", e);
242                 }
243             }
244         }
245     }
246     /**
247      * @param file file to read
248      * @return size of file or -1 if it can't be determined.
249      */

250     static public long getSize(File JavaDoc file) {
251         try {
252             return fileSize(file);
253         } catch (Exception JavaDoc e) {
254             return -1;
255         }
256     }
257
258     /** Returns the base name (without the extension) of
259      * <var>pathname</var>. For example,
260      * <code>FileUtils.getBase("a/b.c") == "a/b"</code>.
261      * @param pathname a String
262      * @return a String
263      */

264     public static String JavaDoc getBase(String JavaDoc pathname) {
265         int pos = pathname.lastIndexOf('.');
266         if (pos >= 0) {
267             return pathname.substring(0, pos);
268         } else {
269             return pathname;
270         }
271     }
272
273     /**
274      * @return the ending extension
275      * @param pathname a string
276      */

277     public static String JavaDoc getExtension(String JavaDoc pathname) {
278         int pos = pathname.lastIndexOf('.');
279         if (pos >= 0 && pos != pathname.length() - 1) {
280             return pathname.substring(pos+1);
281         }
282         return "";
283     }
284
285     /** Remove the : from Windows Drive specifier found
286      * in Absolute path names.
287      *
288      * @param src
289      * @return a fixed string
290      */

291     public static String JavaDoc fixAbsWindowsPaths(String JavaDoc src) {
292
293         // See if we're on Windows
294
if (File.separatorChar == '/')
295             return src;
296
297         // One char strings
298
if (src.length() < 2)
299             return src;
300
301         // Check to make sure we have a Windows absolute path
302
if (src.charAt(1) != ':')
303             return src;
304
305         // Sanity check to make sure we really have a drive specifier
306
char c = src.charAt(0);
307         int t = Character.getType(c);
308         boolean isAscii = (t == Character.UPPERCASE_LETTER ||
309                            t == Character.LOWERCASE_LETTER);
310         if (!isAscii) {
311             return src;
312         }
313         
314         // Remove the : that was the 2nd character.
315
return src.substring(0,1) + src.substring(2);
316     }
317
318     /**
319      * Insure a file and all parent directories exist.
320      * @param file the file
321      * @throws IOException
322      */

323     public static void makeFileAndParentDirs(File JavaDoc file)
324         throws IOException JavaDoc {
325         File JavaDoc dir = file.getParentFile();
326         if (dir != null)
327             dir.mkdirs();
328         file.createNewFile();
329     }
330
331     /** Delete an entire directory tree. Named after the Python
332      * function.
333      * @return true if full removal of cache was successful, otherwise false.
334      */

335     public static boolean rmTree(File JavaDoc file) {
336         boolean delTreeOk = true;
337         boolean delFileOk = true;
338         File JavaDoc[] files = file.listFiles(); // null if not a directory
339
if (files != null) {
340             for (Iterator iter = Arrays.asList(files).iterator();
341                  iter.hasNext(); ) {
342                 if (! rmTree((File JavaDoc) iter.next()))
343                     delTreeOk = false;
344             }
345         }
346         delFileOk = file.delete();
347
348         return (delFileOk && delTreeOk);
349     }
350     
351     /**
352      * Read the input stream and write contents to output stream.
353      * @param input stream to read
354      * @param output stream to write
355      * @return number of bytes written to output
356      * @throws IOException if there's an error reading or writing
357      * the steams
358      */

359     public static int send(InputStream JavaDoc input, OutputStream JavaDoc output)
360         throws IOException JavaDoc {
361
362         int available = input.available();
363         int bsize;
364         if (available == 0) {
365             bsize = BUFFER_SIZE;
366         } else {
367             bsize = Math.min(input.available(), BUFFER_SIZE);
368         }
369         return send(input, output, bsize);
370     }
371     
372     /**
373      * Exception when there's an error writing a stream
374      */

375     public static class StreamWritingException extends IOException JavaDoc {
376         public StreamWritingException (String JavaDoc s)
377         {
378             super(s);
379         }
380     }
381
382     /**
383      * Exception when there's an error reading a stream
384      */

385     public static class StreamReadingException extends IOException JavaDoc {
386         public StreamReadingException (String JavaDoc s)
387         {
388             super(s);
389         }
390     }
391
392     
393     /**
394      * Read the input character stream and write contents to output stream.
395      * @param input stream to read
396      * @param output stream to write
397      * @return number of bytes written to output
398      * @throws IOException if there's an error reading or writing
399      * the steams
400      */

401     public static int send(Reader JavaDoc input, Writer JavaDoc output)
402         throws IOException JavaDoc {
403         int bsize = BUFFER_SIZE;
404         return send(input, output, bsize);
405     }
406
407
408     /**
409      * Read the input stream and write contents to output
410      * stream using a buffer of the requested size.
411      * @param input stream to read
412      * @param output stream to write
413      * @param size size of buffer to use
414      * @return number of bytes written to output
415      * @throws IOException if there's an error reading or writing
416      * the steams
417      */

418     public static int send(Reader JavaDoc input, Writer JavaDoc output, int size)
419         throws IOException JavaDoc {
420         int c = 0;
421         char[] buffer = new char[size];
422         int b = 0;
423         while((b = input.read(buffer)) > 0) {
424             c += b;
425             output.write(buffer, 0, b);
426         }
427         return c;
428     }
429
430
431     /**
432      * Read the input stream and write contents to output
433      * stream using a buffer of the requested size.
434      * @param input stream to read
435      * @param output stream to write
436      * @param size size of buffer to use
437      * @return number of bytes written to output
438      * @throws IOException if there's an error reading or writing
439      * the steams
440      */

441     public static int send(InputStream JavaDoc input, OutputStream JavaDoc output, int size)
442         throws IOException JavaDoc {
443         int c = 0;
444         byte[] buffer = new byte[size];
445         int b = 0;
446         while((b = input.read(buffer)) > 0) {
447             c += b;
448             output.write(buffer, 0, b);
449         }
450         return c;
451     }
452
453     /**
454      * Read the input stream and write contents to output stream.
455      * @param input stream to read
456      * @param output stream to write
457      * @return number of bytes written to output
458      * @throws StreamWritingException if there's an error writing output
459      * @throws StreamReadingException if there's an error reading input
460      */

461     public static int sendToStream(InputStream JavaDoc input, OutputStream JavaDoc output)
462         throws IOException JavaDoc {
463
464         int available = input.available();
465         int bsize;
466         if (available == 0) {
467             bsize = BUFFER_SIZE;
468         } else {
469             bsize = Math.min(input.available(), BUFFER_SIZE);
470         }
471         return sendToStream(input, output, bsize);
472     }
473
474     /**
475      * Read the input stream and write contents to output
476      * stream using a buffer of the requested size.
477      * @param input stream to read
478      * @param output stream to write
479      * @param size size of buffer to use
480      * @return number of bytes written to output
481      * @throws StreamWritingException if there's an error writing output
482      * @throws StreamReadingException if there's an error reading input
483      */

484     public static int sendToStream(InputStream JavaDoc input,
485             OutputStream JavaDoc output, int size)
486         throws IOException JavaDoc {
487         int c = 0;
488         byte[] buffer = new byte[size];
489         int b = 0;
490         while(true) {
491             try {
492                 // Until end of stream
493
if ((b = input.read(buffer)) <= 0) {
494                     return c;
495                 }
496             } catch (IOException JavaDoc e) {
497                 throw new StreamReadingException(e.getMessage());
498             }
499             c += b;
500             try {
501                 output.write(buffer, 0, b);
502             } catch (IOException JavaDoc e) {
503                 throw new StreamWritingException(e.getMessage());
504             }
505             if (THROTTLE != 0) {
506                 try {
507                     mLogger.info("Sleeping " + THROTTLE + " msecs ");
508                     Thread.currentThread().sleep(THROTTLE);
509                 } catch (InterruptedException JavaDoc e) {
510                     mLogger.warn("interrupted during sleep", e);
511                 }
512             }
513         }
514     }
515
516     /**
517      * Read the input stream and write contents to output stream.
518      * @param input stream to read
519      * @param output stream to write
520      * @return number of bytes written to output
521      * @throws IOException
522      */

523     public static int escapeHTMLAndSend(InputStream JavaDoc input, OutputStream JavaDoc output)
524         throws IOException JavaDoc {
525
526         int available = input.available();
527         int bsize;
528         if (available == 0) {
529             bsize = BUFFER_SIZE;
530         } else {
531             bsize = Math.min(input.available(), BUFFER_SIZE);
532         }
533         return escapeHTMLAndSend(input, output, bsize);
534     }
535     /**
536      * Read the input stream and write contents to output
537      * stream using a buffer of the requested size.
538      * @param input stream to read
539      * @param output stream to write
540      * @param size size of buffer to use
541      * @param return number of bytes written to output
542      * @throws IOException
543      */

544     public static int escapeHTMLAndSend(InputStream JavaDoc input, OutputStream JavaDoc output, int size)
545         throws IOException JavaDoc {
546         int c = 0;
547         byte[] buffer = new byte[size];
548         byte[] buffer2 = new byte[size*4]; // big enuff to escape each char
549
int b = 0;
550         int b2 = 0;
551         while((b = input.read(buffer)) > 0) {
552             b2 = escapeHTML(buffer, b, buffer2);
553             c += b2;
554             output.write(buffer2, 0, b2);
555         }
556         return c;
557     }
558
559     /**
560      * copy input into output escaping HTML chars
561      * escaped. Output buffer must be 4 x the input buffer size.
562      *
563      * @param ib input buffer
564      * @param buflen input buffer size;
565      * @param ob output buffer size;
566      * @param return number of bytes written to ob
567      */

568     public static int escapeHTML(byte[] ib, int buflen, byte[] ob) {
569         int bc = 0;
570         for(int i = 0; i < buflen; i++) {
571             if (ib[i] == '<') {
572                 ob[bc++] = '&';
573                 ob[bc++] = 'l';
574                 ob[bc++] = 't';
575                 ob[bc++] = ';';
576             } else if (ib[i] == '>') {
577                 ob[bc++] = '&';
578                 ob[bc++] = 'g';
579                 ob[bc++] = 't';
580                 ob[bc++] = ';';
581             } else {
582                 ob[bc++] = ib[i];
583             }
584         }
585
586         return bc;
587     }
588
589     public static class RelativizationError extends Error JavaDoc {
590         RelativizationError(String JavaDoc message) {
591             super(message);
592         }
593     }
594
595     /** Return a path that resolves to the same file relative to
596      * dest as path does relative to source. Paths use '/' as
597      * separators. source and dest are assumed to be directories. */

598     public static String JavaDoc adjustRelativePath(String JavaDoc path,
599                                             String JavaDoc source, String JavaDoc dest)
600         throws RelativizationError
601     {
602         final String JavaDoc separator = "/";
603         if (path.endsWith(separator)) {
604             return path;
605         }
606         if (source.endsWith(separator)) {
607             source = source.substring(0, source.length() - 1);
608         }
609         if (dest.endsWith(separator)) {
610             dest = dest.substring(0, dest.length() - 1);
611         }
612         List sourcedirs = new Vector(Arrays.asList(StringUtils.split(source, separator)));
613         List destdirs = new Vector(Arrays.asList(StringUtils.split(dest, separator)));
614         normalizePath(sourcedirs);
615         normalizePath(destdirs);
616         // Remove the common prefix
617
while (!sourcedirs.isEmpty() && !destdirs.isEmpty() &&
618                ((String JavaDoc) sourcedirs.get(0)).equals((String JavaDoc) destdirs.get(0))) {
619             sourcedirs.remove(0);
620             destdirs.remove(0);
621         }
622         // If either dir is absolute, we can't relativize a file in
623
// one to the other. Do this after removing the common
624
// prefix, since if both files are absolute and are not on
625
// different drives (Windows only) then a pathname that's
626
// relative to one can be rewritten relative to the other.
627
//
628
//System.err.println("" + sourcedirs + " -> " + AbsolutePathnameTester.test(sourcedirs));
629
if (AbsolutePathnameTester.test(sourcedirs) ||
630             AbsolutePathnameTester.test(destdirs)) {
631             throw new RelativizationError(
632               "can't create a pathname relative to " +dest +
633               " that refers to a file relative to "+ source);
634         }
635         List components = new Vector();
636         // '..'s to get out of the source directory...
637
for (Iterator iter = sourcedirs.iterator(); iter.hasNext(); ) {
638             iter.next();
639             components.add("..");
640         }
641         // ...and directory names to get into the dest directory
642
for (Iterator iter = destdirs.iterator(); iter.hasNext(); ) {
643             components.add(iter.next());
644         }
645         components.add(path);
646         return StringUtils.join(components, separator);
647     }
648
649     /**
650      * @return the path to the given file, relative to the
651      * given directory name. If the file isn't inside the directory,
652      * just return the entire file name. Path separators are
653      * modified to always be '/'.
654      */

655     public static String JavaDoc relativePath(File JavaDoc file, String JavaDoc directoryName) {
656         try {
657             String JavaDoc fileName = file.getCanonicalPath().replace('\\', '/');
658             String JavaDoc dirName = new File JavaDoc(directoryName).getCanonicalPath().replace('\\', '/');
659             if (!fileName.startsWith(dirName)) {
660                 return fileName;
661             }
662             return fileName.substring(dirName.length());
663         } catch (IOException JavaDoc ioe) {
664             throw new ChainedException(ioe);
665         }
666     }
667
668     /**
669      * @return the path to the given file, relative to the
670      * given directory name. If the file isn't inside the directory,
671      * just return the entire file name. Path separators are
672      * modified to always be '/'.
673      */

674     public static String JavaDoc relativePath(String JavaDoc filename, String JavaDoc directoryName) {
675         return relativePath(new File JavaDoc(filename), directoryName);
676     }
677
678     public static String JavaDoc toURLPath(File JavaDoc file) {
679         // Can't call File.toURL, since it looks at the disk
680
return StringUtils.join(StringUtils.split(file.getPath(),
681                                                   file.separator),
682                                 "/");
683     }
684
685     /** Remove "." and non-top "..". Destructive. */
686     public static void normalizePath(List path) {
687         for (int i = 0; i < path.size(); i++) {
688             String JavaDoc component = (String JavaDoc) path.get(i);
689             if (component.equals(".") || component.equals("")) {
690                 path.remove(i--);
691             } else if (component.equals("..") && i > 0) {
692                 path.remove(i--);
693                 path.remove(i--);
694             }
695         }
696     }
697
698     /**
699      * Encode the given file as requested to an outputFile.
700      * @param inputFile file to be encoded
701      * @param outputFile encoded file
702      * @param encoding type of encoding to use ("gzip" or "deflate" supported).
703      * @throws ChainedException if the requested encoding is not supported.
704      */

705     static public void encode(File JavaDoc inputFile, File JavaDoc outputFile, String JavaDoc encoding)
706         throws IOException JavaDoc {
707
708         FileInputStream JavaDoc in = null;
709
710         try {
711             in = new FileInputStream JavaDoc(inputFile);
712             encode(in, outputFile, encoding);
713         } finally {
714             if (in != null)
715                 in.close();
716         }
717     }
718
719     /**
720      * Decode the given file as requested to an outputFile.
721      * @param inputFile file to be decoded
722      * @param outputFile decoded file
723      * @param encoding type of encoding to use ("gzip" or "deflate" supported).
724      * @throws ChainedException if the requested encoding is not supported.
725      */

726     static public void decode(File JavaDoc inputFile, File JavaDoc outputFile, String JavaDoc encoding)
727         throws IOException JavaDoc {
728
729         mLogger.debug("Starting decoding from " + encoding);
730         FilterInputStream JavaDoc in = null;
731         OutputStream JavaDoc out = new FileOutputStream JavaDoc(outputFile);
732         InputStream JavaDoc ins = new FileInputStream JavaDoc(inputFile);
733
734         try {
735             if (encoding.equals(GZIP)) {
736                 in = new GZIPInputStream(ins);
737             } else if (encoding.equals(DEFLATE)) {
738                 in = new InflaterInputStream(ins);
739             } else {
740                 String JavaDoc message = "Unsuppored encoding: " + encoding;
741                 mLogger.error(message);
742                 throw new ChainedException(message);
743             }
744     
745             // Note: use fixed size for buffer. The send(in, out) method
746
// will use in.available() to guess a good buffersize but
747
// that won't work out well for these input streams.
748
int b = FileUtils.send(in, out, BUFFER_SIZE);
749             mLogger.debug("decoded into " + b + " bytes" );
750         } finally {
751             close(in);
752             close(ins);
753             close(out);
754         }
755         mLogger.debug("Done decoding from " + encoding);
756     }
757
758     /**
759      * Encode the given file as requested to an outputFile.
760      * @param inputFile file to be encodeded
761      * @param outputFile encoded file
762      * @param encoding type of encoding to use ("gzip" or "deflate" supported).
763      * @throws ChainedException if the requested encoding is not supported.
764      */

765     static public void encode(InputStream JavaDoc input, File JavaDoc outputFile, String JavaDoc encoding)
766         throws IOException JavaDoc {
767
768         FileOutputStream JavaDoc out = null;
769         FilterOutputStream JavaDoc filter = null;
770
771         mLogger.debug("Encoding into " + encoding);
772
773         try {
774             FileUtils.makeFileAndParentDirs(outputFile);
775
776             out = new FileOutputStream JavaDoc(outputFile);
777
778             if (encoding.equals(GZIP)) {
779                 filter = new GZIPOutputStream(out);
780             } else if (encoding.equals(DEFLATE)) {
781                 filter = new DeflaterOutputStream(out);
782             } else {
783                 String JavaDoc message = "Unsupported encoding: " + encoding;
784                 mLogger.error(message);
785                 throw new ChainedException(message);
786             }
787
788             FileUtils.send(input, filter, BUFFER_SIZE);
789
790         } finally {
791             if (filter != null)
792                 close(filter);
793             if (out != null)
794                 close(out);
795         }
796
797         mLogger.debug("Done encoding into " + encoding);
798     }
799
800     /**
801      * Make sure you really want to ignore the exception
802      * before using this.
803      * @param in stream to close w/out throwing an exception
804      */

805     static public void close(InputStream JavaDoc in) {
806         try {
807             if (in != null) {
808                 in.close();
809             }
810         } catch (Exception JavaDoc e) {
811         }
812     }
813
814     /**
815      * Make sure you really want to ignore the exception
816      * before using this.
817      * @param out stream to close w/out throwing an exception
818      */

819     static public void close(OutputStream JavaDoc out) {
820         try {
821             if (out != null) {
822                 out.close();
823             }
824         } catch (Exception JavaDoc e) {
825         }
826     }
827
828     /**
829      * Make sure you really want to ignore the exception
830      * before using this.
831      * @param w write to close w/out throwing an exception
832      */

833     static public void close(Writer JavaDoc w) {
834         try {
835             if (w != null) {
836                 w.close();
837             }
838         } catch (Exception JavaDoc e) {
839         }
840     }
841
842     /**
843      * Remove all files in the given list that are immediate children
844      * of this directory. This does <b>not</b> recursively remove
845      * files in subdirecetories.
846      *
847      * @return true if all files to be removed, could be removed
848      */

849     static public boolean deleteFiles(File JavaDoc dir, String JavaDoc[] fileNames) {
850         boolean ok = true;
851
852         for(int i = 0; i < fileNames.length; i++) {
853             File JavaDoc file = new File JavaDoc(dir + File.separator + fileNames[i]);
854             try {
855                 if (!file.isDirectory()) {
856                     file.delete();
857                 }
858             } catch (Throwable JavaDoc e) {
859                 mLogger.error("can't delete file: " + fileNames[i]);
860                 ok = false;
861             }
862         }
863         return ok;
864     }
865
866     /**
867      * Remove all files that are immediate children
868      * of this directory. This does <b>not</b> recursively remove
869      * files in subdirecetories.
870      *
871      * @return true if all files to be removed, could be removed
872      */

873     static public boolean deleteFiles(File JavaDoc dir) {
874
875         if (!dir.isDirectory()) {
876             return false;
877         }
878         String JavaDoc[] fileNames = dir.list();
879
880         return deleteFiles(dir, fileNames);
881     }
882
883     /**
884      * Remove all files that start with the following name
885      * in the given directory. This does <b>not</b> recursively remove
886      * files in subdirecetories.
887      * @return true if all files to be removed, could be removed
888      */

889     static public boolean deleteFilesStartingWith(File JavaDoc dir, String JavaDoc name) {
890
891         boolean ok = true;
892
893         /**
894          * Filter that selects all files that begin with a
895          * given file name. See java.io.FilenameFilter.
896          */

897         class StartsWithNameFilter implements FilenameFilter JavaDoc {
898             final String JavaDoc _name;
899         
900             StartsWithNameFilter(String JavaDoc n) {
901                 _name = n;
902             }
903             public boolean accept(File JavaDoc d, String JavaDoc n) {
904                 return (n.startsWith(_name));
905             }
906         }
907
908         String JavaDoc[] fileNames = dir.list(new StartsWithNameFilter(name));
909
910         return deleteFiles(dir, fileNames);
911     }
912 }
913
Popular Tags