001: /*
002: * ChainBuilder ESB
003: * Visual Enterprise Integration
004: *
005: * Copyright (C) 2006 Bostech Corporation
006: *
007: * This program is free software; you can redistribute it and/or modify it
008: * under the terms of the GNU General Public License as published by the
009: * Free Software Foundation; either version 2 of the License, or (at your option)
010: * any later version.
011: *
012: * This program is distributed in the hope that it will be useful,
013: * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
014: * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
015: * for more details.
016: *
017: * You should have received a copy of the GNU General Public License along with
018: * this program; if not, write to the Free Software Foundation, Inc.,
019: * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
020: *
021: *
022: * $Id: FileUtil.java 11975 2008-02-16 06:33:03Z shou $
023: */
024: package com.bostechcorp.cbesb.common.util;
025:
026: import java.io.BufferedInputStream;
027: import java.io.BufferedOutputStream;
028: import java.io.BufferedReader;
029: import java.io.ByteArrayInputStream;
030: import java.io.ByteArrayOutputStream;
031: import java.io.File;
032: import java.io.FileFilter;
033: import java.io.FileInputStream;
034: import java.io.FileNotFoundException;
035: import java.io.FileOutputStream;
036: import java.io.IOException;
037: import java.io.InputStream;
038: import java.io.InputStreamReader;
039: import java.io.OutputStream;
040: import java.net.URI;
041: import java.net.URISyntaxException;
042: import java.net.URL;
043: import java.nio.MappedByteBuffer;
044: import java.nio.channels.FileChannel;
045: import java.util.Collection;
046: import java.util.Enumeration;
047: import java.util.HashMap;
048: import java.util.Vector;
049: import java.util.zip.ZipEntry;
050: import java.util.zip.ZipFile;
051: import java.util.zip.ZipOutputStream;
052:
053: import org.apache.commons.logging.Log;
054: import org.apache.commons.logging.LogFactory;
055: import org.eclipse.core.runtime.Path;
056:
057: /**
058: * File utilities
059: *
060: * @version $Revision: 383937 $
061: */
062: public class FileUtil {
063:
064: /**
065: * Buffer size used when copying the content of an input stream to an output
066: * stream.
067: */
068: private static final int DEFAULT_BUFFER_SIZE = 1024 * 1024;
069:
070: protected static transient Log logger = LogFactory
071: .getLog(FileUtil.class);
072:
073: public static File[] listFilesAsArray(File directory,
074: FileFilter filter, boolean recurse) {
075: Collection<File> files = listFiles(directory, filter, recurse);
076: // Java4: Collection files = listFiles(directory, filter, recurse);
077:
078: File[] arr = new File[files.size()];
079: return files.toArray(arr);
080: }
081:
082: public static Collection<File> listFiles(
083: // Java4: public static Collection listFiles(
084: File directory, FileFilter filter, boolean recurse) {
085: // List of files / directories
086: Vector<File> files = new Vector<File>();
087: // Java4: Vector files = new Vector();
088:
089: // Get files / directories in the directory
090: File[] entries = directory.listFiles();
091:
092: // Go over entries
093: for (File entry : entries) {
094: // Java4: for (int f = 0; f < files.length; f++) {
095: // Java4: File entry = (File) files[f];
096:
097: // If there is no filter or the filter accepts the
098: // file / directory, add it to the list
099: if (filter == null || filter.accept(entry)) {
100: files.add(entry);
101: }
102:
103: // If the file is a directory and the recurse flag
104: // is set, recurse into the directory
105: if (recurse && entry.isDirectory()) {
106: files.addAll(listFiles(entry, filter, recurse));
107: }
108: }
109:
110: // Return collection of files
111: return files;
112: }
113:
114: /**
115: *
116: * @param inputStream -
117: * to read from.
118: * @return the string that was read.
119: * @throws IOException
120: */
121: public static String readString(InputStream inputStream)
122: throws IOException {
123: BufferedReader in = new BufferedReader(new InputStreamReader(
124: inputStream, "utf-8"));
125: String s = null;
126: StringBuffer buffer = new StringBuffer();
127: try {
128: while ((s = in.readLine()) != null) {
129: buffer.append(s).append("\n");
130: }
131: } catch (IOException e) {
132: logger
133: .error("Exception in readString(): "
134: + e.getMessage());
135: if (logger.isDebugEnabled()) {
136: logger.debug("Exception in readString():", e);
137: }
138: }
139: return buffer.toString();
140: }
141:
142: /**
143: *
144: * @param inputStream -
145: * to read from.
146: * @return the bytes that were read.
147: * @throws IOException
148: */
149: public static byte[] readBytes(InputStream inputStream)
150: throws IOException {
151: ByteArrayOutputStream baos = new ByteArrayOutputStream();
152: BufferedInputStream bis = new BufferedInputStream(inputStream);
153: int b = bis.read();
154: while (b != -1) {
155: baos.write(b);
156: b = bis.read();
157: }
158: return baos.toByteArray();
159: }
160:
161: /**
162: *
163: * @param filename -
164: * filename to read.
165: * @return - the string that was read.
166: * @throws IOException
167: */
168: public static String readStringFromFile(String filename)
169: throws IOException {
170: return readString(new FileInputStream(filename));
171: }
172:
173: /**
174: *
175: * @param filename -
176: * filename to read.
177: * @return - the bytes that were read.
178: * @throws IOException
179: */
180: public static byte[] readBytesFromFile(String filename)
181: throws IOException {
182: return readBytes(new FileInputStream(filename));
183: }
184:
185: /**
186: *
187: * @param fileInClassPath
188: * the filename in class path.
189: * @return the string that was read from file.
190: * @throws IOException
191: */
192: public static String readString(String fileInClassPath)
193: throws IOException {
194: ClassLoader cl = Thread.currentThread().getContextClassLoader();
195: return readString(cl.getResourceAsStream(fileInClassPath));
196: }
197:
198: /**
199: *
200: * @param fileInClassPath
201: * the filename in class path.
202: * @return the bytes that were read from file.
203: * @throws IOException
204: */
205: public static byte[] readBytes(String fileInClassPath)
206: throws IOException {
207: ClassLoader cl = Thread.currentThread().getContextClassLoader();
208: return readBytes(cl.getResourceAsStream(fileInClassPath));
209: }
210:
211: public static File getFileFromClassPath(String name)
212: throws URISyntaxException {
213: URL url = Thread.currentThread().getContextClassLoader()
214: .getResource("xslident.xsl");
215: File file = new File(new URI(url.toString()));
216: return file;
217: }
218:
219: /**
220: * Fast & simple file copy.
221: * @param source
222: * @param dest
223: * @throws IOException
224: */
225: public static void copy(File source, File dest) throws IOException {
226: FileChannel in = null, out = null;
227: try {
228: in = new FileInputStream(source).getChannel();
229: out = new FileOutputStream(dest).getChannel();
230: long size = in.size();
231: MappedByteBuffer buf = in.map(
232: FileChannel.MapMode.READ_ONLY, 0, size);
233: out.write(buf);
234: } finally {
235: if (in != null)
236: in.close();
237: if (out != null)
238: out.close();
239: }
240: }
241:
242: /**
243: * Simple Copy "from" to "to"
244: * @param from
245: * @param to
246: * @return
247: * Note: use fast copy from V1.2
248: */
249: public static boolean copyFile(String from, String to) {
250: try {
251: copy(new File(from), new File(to));
252: } catch (Exception e) {
253: ErrorUtil.printError("Exception in copyFile(): ", e);
254: return false;
255: }
256: return true;
257: }
258:
259: public static void copy(String from, String to) throws IOException {
260: int buff_size = 100000;
261: byte[] buffer = new byte[buff_size];
262: InputStream in = null;
263: OutputStream out = null;
264:
265: try {
266: in = new FileInputStream(from);
267: out = new FileOutputStream(to);
268:
269: while (true) {
270: synchronized (buffer) {
271: int amountread = in.read(buffer);
272:
273: if (amountread == -1) {
274: break;
275: }
276:
277: out.write(buffer, 0, amountread);
278: }
279: }
280: } finally {
281: if (in != null) {
282: in.close();
283: }
284:
285: if (out != null) {
286: out.close();
287: }
288: }
289: }
290:
291: // public static boolean copyFile(String from, String to) {
292: // File fromFile, toFile;
293: // fromFile = new File(from);
294: // toFile = new File(to);
295: // FileInputStream fis = null;
296: // FileOutputStream fos = null;
297: // try {
298: // toFile.createNewFile();
299: // fis = new FileInputStream(fromFile);
300: // fos = new FileOutputStream(toFile);
301: // int bytesRead;
302: // byte[] buf = new byte[4 * 1024];// 4K buffer
303: // while ((bytesRead = fis.read(buf)) != -1) {
304: // fos.write(buf, 0, bytesRead);
305: // }
306: // fos.flush();
307: // fos.close();
308: // fis.close();
309: // } catch (IOException e) {
310: // ErrorUtil.printError("Exception in copyFile(): ", e);
311: // return false;
312: // }
313: // return true;
314: // }
315:
316: /**
317: * Move a File
318: *
319: * @param src
320: * @param targetDirectory
321: * @throws IOException
322: */
323: public static void moveFile(File src, File targetDirectory)
324: throws IOException {
325: if (!src.renameTo(new File(targetDirectory, src.getName()))) {
326: throw new IOException("Failed to move " + src + " to "
327: + targetDirectory);
328: }
329: }
330:
331: /**
332: * Build a path- but do not create it
333: *
334: * @param parent
335: * @param subDirectory
336: * @return a File representing the path
337: */
338: public static File getDirectoryPath(File parent, String subDirectory) {
339: File result = null;
340: if (parent != null) {
341: result = new File(parent, subDirectory);
342: }
343: return result;
344: }
345:
346: /**
347: * Build a directory path - creating directories if neccesary
348: *
349: * @param file
350: * @return true if the directory exists, or making it was successful
351: */
352: public static boolean buildDirectory(File file) {
353: return file.exists() || file.mkdirs();
354: }
355:
356: /**
357: * Copy in stream to an out stream
358: *
359: * @param in
360: * @param out
361: * @throws IOException
362: */
363: public static void copyInputStream(InputStream in, OutputStream out)
364: throws IOException {
365: byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
366: int len;
367: while ((len = in.read(buffer)) >= 0) {
368: out.write(buffer, 0, len);
369: }
370: in.close();
371: out.close();
372: }
373:
374: /**
375: * Unpack a zip file
376: *
377: * @param theFile
378: * @param targetDir
379: * @return the file
380: * @throws IOException
381: */
382: public static File unpackArchive(File theFile, File targetDir)
383: throws IOException {
384: if (!theFile.exists()) {
385: throw new IOException(theFile.getAbsolutePath()
386: + " does not exist");
387: }
388: if (!targetDir.exists()) {
389: targetDir.mkdirs();
390: }
391: ZipFile zipFile;
392: zipFile = new ZipFile(theFile);
393: for (Enumeration entries = zipFile.entries(); entries
394: .hasMoreElements();) {
395: ZipEntry entry = (ZipEntry) entries.nextElement();
396: File file = new File(targetDir, File.separator
397: + entry.getName());
398: // Take the sledgehammer approach to creating directories
399: // to work around ZIP's that incorrectly miss directories
400: file.mkdirs();
401: if (!entry.isDirectory()) {
402: file.delete();
403: copyInputStream(zipFile.getInputStream(entry),
404: new BufferedOutputStream(new FileOutputStream(
405: file)));
406: }
407: }
408: zipFile.close();
409: return theFile;
410: }
411:
412: /**
413: * Unpack a zip file
414: *
415: * @param theFile
416: * @param targetDir
417: * @return the file
418: * @throws IOException
419: */
420: public static File unpackArchiveCheckOverwrite(File theFile,
421: File targetDir) throws IOException {
422: if (!theFile.exists()) {
423: throw new IOException(theFile.getAbsolutePath()
424: + " does not exist");
425: }
426: if (!targetDir.exists()) {
427: targetDir.mkdirs();
428: }
429: ZipFile zipFile;
430: zipFile = new ZipFile(theFile);
431: for (Enumeration entries = zipFile.entries(); entries
432: .hasMoreElements();) {
433: ZipEntry entry = (ZipEntry) entries.nextElement();
434: File file = new File(targetDir, File.separator
435: + entry.getName());
436: // Take the sledgehammer approach to creating directories
437: // to work around ZIP's that incorrectly miss directories
438: if (file.lastModified() <= entry.getTime()) {
439: file.mkdirs();
440: if (!entry.isDirectory()) {
441: file.delete();
442: // if current file time > zip entry time then don't
443: // owerwrite
444: // entry.getTime();
445: copyInputStream(zipFile.getInputStream(entry),
446: new BufferedOutputStream(
447: new FileOutputStream(file)));
448: }
449: }
450: }
451: zipFile.close();
452: return theFile;
453: }
454:
455: /**
456: * Unpack an archive from a URL
457: *
458: * @param url
459: * @param targetDir
460: * @return the file to the url
461: * @throws IOException
462: */
463: public static File unpackArchive(URL url, File targetDir)
464: throws IOException {
465: if (!targetDir.exists()) {
466: targetDir.mkdirs();
467: }
468: InputStream in = new BufferedInputStream(url.openStream(),
469: DEFAULT_BUFFER_SIZE);
470: // make sure we get the actual file
471: File zip = File.createTempFile("arc", ".zip", targetDir);
472: OutputStream out = new BufferedOutputStream(
473: new FileOutputStream(zip));
474: copyInputStream(in, out);
475: out.close();
476: return unpackArchive(zip, targetDir);
477: }
478:
479: /**
480: * Validate that an archive contains a named entry
481: *
482: * @param theFile
483: * @param name
484: * @return true if the entry exists
485: * @throws IOException
486: */
487: public static boolean archiveContainsEntry(File theFile, String name)
488: throws IOException {
489: boolean result = false;
490: ZipFile zipFile;
491: zipFile = new ZipFile(theFile);
492: for (Enumeration entries = zipFile.entries(); entries
493: .hasMoreElements();) {
494: ZipEntry entry = (ZipEntry) entries.nextElement();
495: if (entry.getName().equals(name)) {
496: result = true;
497: break;
498: }
499: }
500: zipFile.close();
501: return result;
502: }
503:
504: /**
505: * Create a unique directory within a directory 'root'
506: *
507: * @param rootDir
508: * @param seed
509: * @return unique directory
510: * @throws IOException
511: */
512: public synchronized static File createUniqueDirectory(File rootDir,
513: String seed) throws IOException {
514: int index = seed.lastIndexOf('.');
515: if (index > 0) {
516: seed = seed.substring(0, index);
517: }
518: File result = null;
519: int count = 0;
520: while (result == null) {
521: String name = seed + "." + count + ".tmp";
522: File file = new File(rootDir, name);
523: if (!file.exists()) {
524: file.mkdirs();
525: result = file;
526: }
527: count++;
528: }
529: return result;
530: }
531:
532: /**
533: * Delete a file
534: *
535: * @param fileToDelete
536: * @return true if the File is deleted
537: */
538: public static boolean deleteFile(File fileToDelete) {
539: boolean result = true;
540: if (fileToDelete != null && fileToDelete.exists()) {
541: if (fileToDelete.isDirectory()) {
542: File[] files = fileToDelete.listFiles();
543: if (files == null) {
544: result = false;
545: } else {
546: for (int i = 0; i < files.length; i++) {
547: File file = files[i];
548: if (!file.getName().equals(".")
549: && !file.getName().equals("..")) {
550: if (file.isDirectory()) {
551: result &= deleteFile(file);
552: } else {
553: result &= file.delete();
554: }
555: }
556: }
557: }
558: }
559: result &= fileToDelete.delete();
560: }
561: return result;
562: }
563:
564: /**
565: * Zip up a directory
566: *
567: * @param directory
568: * @param zipName
569: * @throws IOException
570: */
571: public static void zipDir(String directory, String zipName)
572: throws IOException {
573: // create a ZipOutputStream to zip the data to
574: ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(
575: zipName));
576: String path = "";
577: zipDir(directory, zos, path);
578: // close the stream
579: zos.close();
580: }
581:
582: /**
583: * Zip up a directory path
584: *
585: * @param directory
586: * @param zos
587: * @param path
588: * @throws IOException
589: */
590: public static void zipDir(String directory, ZipOutputStream zos,
591: String path) throws IOException {
592: File zipDir = new File(directory);
593: // get a listing of the directory content
594: String[] dirList = zipDir.list();
595: byte[] readBuffer = new byte[2156];
596: int bytesIn = 0;
597: // loop through dirList, and zip the files
598: for (int i = 0; i < dirList.length; i++) {
599: File f = new File(zipDir, dirList[i]);
600: if (f.isDirectory()) {
601: String filePath = f.getPath();
602: zipDir(filePath, zos, path + f.getName() + "/");
603: continue;
604: }
605: FileInputStream fis = new FileInputStream(f);
606: ZipEntry anEntry = new ZipEntry(path + f.getName());
607: zos.putNextEntry(anEntry);
608: while ((bytesIn = fis.read(readBuffer)) != -1) {
609: zos.write(readBuffer, 0, bytesIn);
610: }
611: fis.close();
612: }
613: }
614:
615: public static InputStream String2InputStream(String str) {
616: ByteArrayInputStream stream = new ByteArrayInputStream(str
617: .getBytes());
618: return stream;
619: }
620:
621: // /**
622: // *
623: // * @param oldFile
624: // * @param newPath
625: // */
626: // @Deprecated
627: // // TODO: throw all the exceptions
628: // public static void copyFile(File oldFile, String newPath) {
629: // try {
630: // int byteRead = 0;
631: // int byteSum = 0;
632: // if (oldFile.exists()) {
633: // InputStream inputStream = new FileInputStream(oldFile);
634: // File newFolder = new File(newPath);
635: // if (!newFolder.exists() || !newFolder.isDirectory()) {
636: // newFolder.mkdirs();
637: // }
638: // String newFilename = newPath + File.separator
639: // + oldFile.getName();
640: // OutputStream outputStream = new FileOutputStream(newFilename);
641: // byte[] buffer = new byte[1024];
642: // while ((byteRead = inputStream.read(buffer)) != -1) {
643: // byteSum += byteRead;
644: // outputStream.write(buffer, 0, byteRead);
645: // }
646: // outputStream.close();
647: // inputStream.close();
648: // }
649: // } catch (Exception e) {
650: // e.printStackTrace();
651: // }
652: // }
653:
654: /**
655: * Copy source(old) file to it's new location - newPath
656: * Note: adapted to use fast Copy
657: * @param oldFile
658: * @param newPath
659: *
660: * Note: use fast copy from V1.2
661: */
662: public static void copyFile(File oldFile, String newPath) {
663: try {
664: if (oldFile.exists()) {
665: File newFolder = new File(newPath);
666: if (oldFile.getParent().equals(newPath))
667: return;
668: if (!newFolder.exists() || !newFolder.isDirectory()) {
669: newFolder.mkdir();
670: }
671: String newFilename = newPath + File.separator
672: + oldFile.getName();
673: copy(oldFile, new File(newFilename));
674: }
675: } catch (Exception e) {
676: e.printStackTrace();
677: }
678: }
679:
680: /**
681: * Copy File Resource from source to destination. If the File resource is a
682: * folder then it's content will be copyed recursively Note: Adapted to use
683: * Fast Copy
684: *
685: * @param sourceStringPath
686: * @param destinationStringPath
687: * @param filter -
688: * just in case you don't need all files
689: * @throws FileNotFoundException
690: * @throws IOException
691: */
692: public static void copyFilesRecursively(String sourceStringPath,
693: String destinationStringPath, FileFilter filter)
694: throws FileNotFoundException, IOException {
695: File src = new File(sourceStringPath);
696: File dest = new File(destinationStringPath);
697: // System.out.println("From:"+sourceStringPath+" \n To:"+destinationStringPath);
698: if (!src.exists())
699: throw new FileNotFoundException("Directory "
700: + sourceStringPath + " does not exist!");
701:
702: if (dest.exists()) // if destination exist then check more
703: if (dest.isDirectory() != src.isDirectory()) {
704: if (!src.isDirectory()) {
705: // change destination, ie append file name
706: dest = new File(dest.getAbsolutePath()
707: + File.separator + src.getName());
708: } else {
709: throw new IOException("Source("
710: + src.getAbsolutePath()
711: + ") \n is a Directory and Destination("
712: + dest.getAbsolutePath()
713: + ")\n is a File, "
714: + "Cannot copy directory to a file");
715: }
716: }
717:
718: if (src.isDirectory()) {
719: if (!buildDirectory(dest))
720: throw new IOException(destinationStringPath
721: + " could not be created.");
722: String list[] = src.list(null);
723: for (int i = 0; i < list.length; i++) {
724: String dest1 = dest.getAbsolutePath() + File.separator
725: + list[i];
726: String src1 = src.getAbsolutePath() + File.separator
727: + list[i];
728: copyFilesRecursively(src1, dest1, filter);
729: }
730: } else {
731: copy(src, dest);/* Fast copy */
732: }
733: }
734:
735: public static void copyFiles(HashMap<String, String> map)
736: throws IOException {
737: for (String source : map.keySet()) {
738: File src = new File(source);
739: File dest = new File(map.get(source));
740: FileUtil.buildDirectory(new Path(map.get(source))
741: .removeLastSegments(1).toFile());
742: copy(src, dest);
743: }
744: }
745:
746: /**
747: * return Absolut URI, so the file can be accesed
748: *
749: * @param WsdlLocation
750: * @param relativeLocationURI
751: * @return
752: */
753: public static String processLocationURI(String wsdlFixedURI,
754: String relativeLocationURI) {
755: String pathToFile = "";
756: URI uri = URI.create(wsdlFixedURI);
757: pathToFile += uri.resolve(relativeLocationURI);
758: return pathToFile;
759: }
760:
761: // public static void main(String[] args) {
762: // try {
763: // copyFilesRecursively("c:\\asd", "c:\\AUTOEXEC.BAT", null);
764: // } catch (FileNotFoundException e) {
765: // // TODO Auto-generated catch block
766: // e.printStackTrace();
767: // } catch (IOException e) {
768: // // TODO Auto-generated catch block
769: // e.printStackTrace();
770: // }
771: // }
772: }
|