001: /*
002: * BEGIN_HEADER - DO NOT EDIT
003: *
004: * The contents of this file are subject to the terms
005: * of the Common Development and Distribution License
006: * (the "License"). You may not use this file except
007: * in compliance with the License.
008: *
009: * You can obtain a copy of the license at
010: * https://open-esb.dev.java.net/public/CDDLv1.0.html.
011: * See the License for the specific language governing
012: * permissions and limitations under the License.
013: *
014: * When distributing Covered Code, include this CDDL
015: * HEADER in each file and include the License file at
016: * https://open-esb.dev.java.net/public/CDDLv1.0.html.
017: * If applicable add the following below this CDDL HEADER,
018: * with the fields enclosed by brackets "[]" replaced with
019: * your own identifying information: Portions Copyright
020: * [year] [name of copyright owner]
021: */
022:
023: /*
024: * @(#)FileHelper.java
025: * Copyright 2004-2007 Sun Microsystems, Inc. All Rights Reserved.
026: *
027: * END_HEADER - DO NOT EDIT
028: */
029: /**
030: * FileHelper.java
031: *
032: * SUN PROPRIETARY/CONFIDENTIAL.
033: * This software is the proprietary information of Sun Microsystems, Inc.
034: * Use is subject to license terms.
035: *
036: * Created on January 2, 2006, 4:49 PM
037: */package com.sun.jbi.management.util;
038:
039: import java.io.File;
040: import java.io.FileInputStream;
041: import java.io.FileOutputStream;
042: import java.io.InputStream;
043: import java.util.Date;
044: import java.text.SimpleDateFormat;
045:
046: import java.security.MessageDigest;
047: import java.security.DigestInputStream;
048:
049: /**
050: *
051: * @author Sun Microsystems, Inc
052: */
053: public class FileHelper {
054: private static boolean sMemoryCleaned = false;
055: private static final int BLOCK_SIZE = 8192;
056: private static final String FINGERPRINT_ALG = "SHA-256";
057:
058: /**
059: * Make a copy of the source file in the destination file.
060: * @param source the source file
061: * @param destination the destination file
062: * @return true if the operation was a success, false otherwise
063: */
064: public static boolean fileCopy(String source, String destination)
065: throws java.io.IOException {
066: return fileCopy(source, destination, false);
067: }
068:
069: /**
070: * Make a copy of the source file in the destination file.
071: * @param source the source file
072: * @param destination the destination file
073: * @param overwrite true if the destination file can be overwritten if it exists
074: * @return true if the operation was a success, false otherwise
075: */
076: public static boolean fileCopy(String source, String destination,
077: boolean overwrite) throws java.io.IOException {
078: File sourceFile = new File(source);
079: File destFile = new File(destination);
080:
081: if (!overwrite) {
082: if (destFile.exists()) {
083: return false;
084: }
085: }
086:
087: byte[] buf = new byte[BLOCK_SIZE];
088: java.io.FileInputStream fis = new java.io.FileInputStream(
089: sourceFile);
090: java.io.FileOutputStream fos = new java.io.FileOutputStream(
091: destFile);
092:
093: for (;;) {
094: int read;
095:
096: read = fis.read(buf, 0, buf.length);
097: if (read > 0) {
098: fos.write(buf, 0, read);
099: }
100: if (read < buf.length) {
101: break;
102: }
103: }
104: fis.close();
105: fos.close();
106: return true;
107:
108: }
109:
110: /**
111: * Compute the fingerprint for a file.
112: * @return fingerprint
113: */
114: public static String fileFingerprint(File file)
115: throws java.io.IOException {
116: MessageDigest md;
117: DigestInputStream dis;
118: byte[] buffer = new byte[BLOCK_SIZE];
119:
120: try {
121: md = MessageDigest.getInstance(FINGERPRINT_ALG);
122: dis = new DigestInputStream(new FileInputStream(file), md);
123: for (;;) {
124: int bytes = dis.read(buffer, 0, buffer.length);
125: if (bytes <= 0)
126: break;
127: }
128: byte[] digest = md.digest();
129: int dlen = digest.length / 2;
130: for (int i = 0; i < dlen; i += 2) {
131: digest[i] ^= digest[i + dlen];
132: }
133: return (encode(digest, dlen));
134: } catch (Exception e) {
135: throw new java.io.IOException(e.toString());
136: }
137: }
138:
139: /**
140: * Mapping of 5-bit integers to characters.
141: * Ambiguous characters like (0, 1, O) are skipped.
142: */
143: static char[] b32Chars = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
144: 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
145: 'W', 'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9' };
146:
147: /**
148: * Encode a byte array as a base32 string.
149: * @param bytes to be encoded
150: * @param len is the number of bytes to encode.
151: * @return base32 value
152: */
153: private static String encode(byte[] bytes, int len) {
154: StringBuilder sb = new StringBuilder((len * 8 + 4) / 5);
155: int pad = ((len * 8) % 5);
156: int bitCount = 8 - pad;
157: int bits = (bytes[0] & 0xff);
158:
159: if (pad != 0) {
160: sb.append(b32Chars[(bits >> 5) & ((1 << pad) - 1)]);
161: }
162: for (int i = 1;;) {
163: if (bitCount < 5) {
164: if (i >= len) {
165: break;
166: }
167: bitCount += 8;
168: bits = (bits << 8) + (bytes[i++] & 0xff);
169: }
170: sb.append(b32Chars[(bits >> (bitCount -= 5)) & 0x1f]);
171: }
172: return (sb.toString());
173: }
174:
175: /**
176: * Create a File. If the parent dirs don't exist create those first.
177: *
178: * @param file - File to Create.
179: * @return true if the File was created, false otherwise.
180: */
181: public static boolean createFile(File file) {
182: if (file.exists()) {
183: return true;
184: }
185:
186: try {
187: if (file.getParentFile() != null) {
188: if (!(file.getParentFile().exists())) {
189: file.getParentFile().mkdirs();
190: }
191: }
192: file.createNewFile();
193: return true;
194: } catch (java.io.IOException ioex) {
195: ioex.printStackTrace();
196: return false;
197: }
198: }
199:
200: /**
201: * Create a Foldr. If the parent dirs don't exist create those first.
202: *
203: * @param folder - folder to Create.
204: * @return true if the File was created, false otherwise.
205: */
206: public static boolean createFolder(File folder) {
207: if (folder.exists()) {
208: return true;
209: }
210:
211: if (folder.getParentFile() != null) {
212: if (!(folder.getParentFile().exists())) {
213: folder.getParentFile().mkdirs();
214: }
215: }
216: if (!folder.mkdir()) {
217: return false;
218: }
219: return true;
220: }
221:
222: /**
223: * Removes all files and child directories in the specified directory.
224: * @return false if unable to delete the file
225: */
226: public static boolean cleanDirectory(File dir) {
227: File[] tmps = dir.listFiles();
228: for (int i = 0; i < tmps.length; i++) {
229: if (tmps[i].isDirectory()) {
230: // -- Even if a single file / dir in a parent folder cannot be deleted
231: // -- break the recursion as there is no point in continuing the loop
232: if (!cleanDirectory(tmps[i])) {
233: return false;
234: }
235: }
236:
237: if (!tmps[i].delete()) {
238: if (!sMemoryCleaned) {
239: finalizeDiscardedObjects();
240: sMemoryCleaned = true;
241: }
242:
243: if (!tmps[i].delete()) {
244: return false;
245: }
246: }
247: }
248: return true;
249: }
250:
251: /**
252: * Reclaim memory, run object finalizers
253: */
254: public static void finalizeDiscardedObjects() {
255: System.gc();
256: System.runFinalization();
257: }
258:
259: /**
260: * Compare two files for equality. The two files are equal if the binary contents of
261: * of each of the files are identical.
262: *
263: *
264: */
265: public static boolean areFilesIdentical(File f1, File f2)
266: throws java.io.IOException {
267: int BLOCK_SIZE = 65536;
268:
269: byte[] bufF1 = new byte[BLOCK_SIZE];
270: byte[] bufF2 = new byte[BLOCK_SIZE];
271: boolean match = false;
272:
273: // If the files are not the same size they are obviously not identical
274: if (f1.length() == f2.length()) {
275: InputStream inputStreamF1 = new FileInputStream(f1);
276: InputStream inputStreamF2 = new FileInputStream(f2);
277: int bytesReadF1 = 0;
278: int bytesReadF2 = 0;
279: do {
280: bytesReadF1 = inputStreamF1.read(bufF1);
281: bytesReadF2 = inputStreamF2.read(bufF2);
282: match = ((bytesReadF1 == bytesReadF2) && java.util.Arrays
283: .equals(bufF1, bufF2));
284: } while (match && (bytesReadF1 > -1));
285:
286: if (inputStreamF1 != null) {
287: inputStreamF1.close();
288: }
289:
290: if (inputStreamF2 != null) {
291: inputStreamF2.close();
292: }
293: }
294:
295: return match;
296: }
297:
298: /**
299: * This method is used to perform directory copy
300: * @param from path to the source dir
301: * @param to path to the destination dir
302: * @return false if the dir could not be copied
303: * @throws IOException if there are problems in copying the fir
304: */
305: public static boolean copy(String from, String to)
306: throws java.io.IOException {
307: boolean copyFailed = false;
308: try {
309: File sourceFile = new File(from);
310:
311: if (sourceFile != null && !sourceFile.exists()) {
312: return false;
313: }
314:
315: if (sourceFile.isFile()) {
316: //overwrite the destination if it exists
317: return fileCopy(from, to, true);
318: }
319:
320: File destinationDir = new File(to);
321: if (!destinationDir.exists()) {
322: if (!createFolder(destinationDir)) {
323: return false;
324: }
325: }
326:
327: File sourceDir = new File(from);
328: String[] files = sourceDir.list();
329: for (int i = 0; i < files.length; i++) {
330: File source = new File(sourceDir, files[i]);
331: File dest = new File(destinationDir, files[i]);
332: //if copying one of the children fails continue with the other children
333: if (!copy(source.getAbsolutePath(), dest
334: .getAbsolutePath())) {
335: copyFailed = true;
336: }
337: }
338: if (copyFailed) {
339: return false;
340: } else {
341: return true;
342: }
343: } catch (Exception ex) {
344: throw new java.io.IOException(ex.toString());
345: }
346: }
347:
348: /**
349: * This method is used to create a timestamp that could be used to create
350: * file names
351: * @return String representation of the current time in yyyyMMddHHmm pattern
352: */
353: public static String getTimestamp() {
354: SimpleDateFormat format = new SimpleDateFormat(
355: "yyyyMMddHHmmssSSS");
356: return format.format(new Date());
357: }
358:
359: /**
360: * Read the file into a String and return the String value.
361: *
362: * @return the contents of the file as a String
363: */
364: public static String readFile(File aFile) throws Exception {
365: String result = "";
366:
367: if (aFile.exists()) {
368: java.io.FileInputStream fis = new java.io.FileInputStream(
369: aFile);
370:
371: byte[] bigBuffer = new byte[(int) aFile.length()];
372:
373: fis.read(bigBuffer);
374: fis.close();
375:
376: result = new String(bigBuffer);
377: }
378:
379: return result;
380: }
381:
382: }
|