James Moger
2014-10-10 a74ddc24545ec45d0bb82ca2bb8f628ffdaa9da3
commit | author | age
892570 1 /*
JM 2  * Copyright 2011 gitblit.com.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package com.gitblit.utils;
17
e36d4d 18 import java.io.BufferedInputStream;
892570 19 import java.io.BufferedReader;
a2709d 20 import java.io.BufferedWriter;
892570 21 import java.io.File;
JM 22 import java.io.FileInputStream;
e36d4d 23 import java.io.FileNotFoundException;
a2709d 24 import java.io.FileOutputStream;
e36d4d 25 import java.io.IOException;
892570 26 import java.io.InputStreamReader;
a2709d 27 import java.io.OutputStreamWriter;
892570 28 import java.nio.charset.Charset;
a74ddc 29 import java.nio.file.Path;
JM 30 import java.nio.file.Paths;
892570 31
JM 32 /**
33  * Common file utilities.
699e71 34  *
892570 35  * @author James Moger
699e71 36  *
892570 37  */
JM 38 public class FileUtils {
699e71 39
478678 40     /** 1024 (number of bytes in one kilobyte) */
JM 41     public static final int KB = 1024;
42
43     /** 1024 {@link #KB} (number of bytes in one megabyte) */
44     public static final int MB = 1024 * KB;
45
46     /** 1024 {@link #MB} (number of bytes in one gigabyte) */
47     public static final int GB = 1024 * MB;
48
49     /**
50      * Returns an int from a string representation of a file size.
51      * e.g. 50m = 50 megabytes
699e71 52      *
478678 53      * @param aString
JM 54      * @param defaultValue
55      * @return an int value or the defaultValue if aString can not be parsed
56      */
57     public static int convertSizeToInt(String aString, int defaultValue) {
58         return (int) convertSizeToLong(aString, defaultValue);
59     }
699e71 60
478678 61     /**
JM 62      * Returns a long from a string representation of a file size.
63      * e.g. 50m = 50 megabytes
699e71 64      *
478678 65      * @param aString
JM 66      * @param defaultValue
67      * @return a long value or the defaultValue if aString can not be parsed
68      */
69     public static long convertSizeToLong(String aString, long defaultValue) {
699e71 70         // trim string and remove all spaces
478678 71         aString = aString.toLowerCase().trim();
JM 72         StringBuilder sb = new StringBuilder();
73         for (String a : aString.split(" ")) {
74             sb.append(a);
75         }
76         aString = sb.toString();
699e71 77
478678 78         // identify value and unit
JM 79         int idx = 0;
80         int len = aString.length();
81         while (Character.isDigit(aString.charAt(idx))) {
82             idx++;
83             if (idx == len) {
84                 break;
85             }
86         }
87         long value = 0;
88         String unit = null;
89         try {
90             value = Long.parseLong(aString.substring(0, idx));
91             unit = aString.substring(idx);
92         } catch (Exception e) {
93             return defaultValue;
94         }
95         if (unit.equals("g") || unit.equals("gb")) {
96             return value * GB;
97         } else if (unit.equals("m") || unit.equals("mb")) {
98             return value * MB;
99         } else if (unit.equals("k") || unit.equals("kb")) {
100             return value * KB;
101         }
102         return defaultValue;
103     }
699e71 104
b42358 105     /**
JM 106      * Returns the byte [] content of the specified file.
699e71 107      *
b42358 108      * @param file
JM 109      * @return the byte content of the file
110      */
111     public static byte [] readContent(File file) {
112         byte [] buffer = new byte[(int) file.length()];
fdb31c 113         BufferedInputStream is = null;
b42358 114         try {
fdb31c 115             is = new BufferedInputStream(new FileInputStream(file));
b42358 116             is.read(buffer,  0,  buffer.length);
JM 117         } catch (Throwable t) {
118             System.err.println("Failed to read byte content of " + file.getAbsolutePath());
119             t.printStackTrace();
fdb31c 120         } finally {
FZ 121             if (is != null) {
122                 try {
123                     is.close();
124                 } catch (IOException ioe) {
125                     System.err.println("Failed to close file " + file.getAbsolutePath());
126                     ioe.printStackTrace();
127                 }
128             }
b42358 129         }
JM 130         return buffer;
131     }
892570 132
JM 133     /**
134      * Returns the string content of the specified file.
699e71 135      *
892570 136      * @param file
JM 137      * @param lineEnding
d9f687 138      * @return the string content of the file
892570 139      */
JM 140     public static String readContent(File file, String lineEnding) {
141         StringBuilder sb = new StringBuilder();
fdb31c 142         InputStreamReader is = null;
892570 143         try {
fdb31c 144             is = new InputStreamReader(new FileInputStream(file), Charset.forName("UTF-8"));
892570 145             BufferedReader reader = new BufferedReader(is);
JM 146             String line = null;
147             while ((line = reader.readLine()) != null) {
148                 sb.append(line);
149                 if (lineEnding != null) {
150                     sb.append(lineEnding);
151                 }
152             }
153         } catch (Throwable t) {
154             System.err.println("Failed to read content of " + file.getAbsolutePath());
155             t.printStackTrace();
fdb31c 156         } finally {
FZ 157             if (is != null) {
158                 try {
159                     is.close();
160                 } catch (IOException ioe) {
161                     System.err.println("Failed to close file " + file.getAbsolutePath());
162                     ioe.printStackTrace();
163                 }
164             }
892570 165         }
JM 166         return sb.toString();
167     }
5c2841 168
JM 169     /**
a2709d 170      * Writes the string content to the file.
699e71 171      *
a2709d 172      * @param file
JM 173      * @param content
174      */
175     public static void writeContent(File file, String content) {
fdb31c 176         OutputStreamWriter os = null;
a2709d 177         try {
fdb31c 178             os = new OutputStreamWriter(new FileOutputStream(file), Charset.forName("UTF-8"));
a2709d 179             BufferedWriter writer = new BufferedWriter(os);
JM 180             writer.append(content);
fdb31c 181             writer.flush();
a2709d 182         } catch (Throwable t) {
JM 183             System.err.println("Failed to write content of " + file.getAbsolutePath());
184             t.printStackTrace();
fdb31c 185         } finally {
FZ 186             if (os != null) {
187                 try {
188                     os.close();
189                 } catch (IOException ioe) {
190                     System.err.println("Failed to close file " + file.getAbsolutePath());
191                     ioe.printStackTrace();
192                 }
193             }
a2709d 194         }
JM 195     }
196
197     /**
5c2841 198      * Recursively traverses a folder and its subfolders to calculate the total
JM 199      * size in bytes.
699e71 200      *
5c2841 201      * @param directory
JM 202      * @return folder size in bytes
203      */
204     public static long folderSize(File directory) {
205         if (directory == null || !directory.exists()) {
206             return -1;
699e71 207         }
11573e 208         if (directory.isDirectory()) {
JM 209             long length = 0;
210             for (File file : directory.listFiles()) {
5c2841 211                 length += folderSize(file);
88598b 212             }
11573e 213             return length;
JM 214         } else if (directory.isFile()) {
215             return directory.length();
5c2841 216         }
11573e 217         return 0;
5c2841 218     }
e36d4d 219
JM 220     /**
73d8e1 221      * Delete a file or recursively delete a folder.
JM 222      *
223      * @param fileOrFolder
224      * @return true, if successful
225      */
226     public static boolean delete(File fileOrFolder) {
227         boolean success = false;
228         if (fileOrFolder.isDirectory()) {
229             File [] files = fileOrFolder.listFiles();
230             if (files != null) {
231                 for (File file : files) {
232                     if (file.isDirectory()) {
233                         success |= delete(file);
234                     } else {
235                         success |= file.delete();
236                     }
237                 }
238             }
239         }
240         success |= fileOrFolder.delete();
241         return success;
242     }
243
244     /**
e36d4d 245      * Copies a file or folder (recursively) to a destination folder.
699e71 246      *
e36d4d 247      * @param destinationFolder
JM 248      * @param filesOrFolders
249      * @return
250      * @throws FileNotFoundException
251      * @throws IOException
252      */
253     public static void copy(File destinationFolder, File... filesOrFolders)
254             throws FileNotFoundException, IOException {
255         destinationFolder.mkdirs();
256         for (File file : filesOrFolders) {
257             if (file.isDirectory()) {
258                 copy(new File(destinationFolder, file.getName()), file.listFiles());
259             } else {
260                 File dFile = new File(destinationFolder, file.getName());
261                 BufferedInputStream bufin = null;
262                 FileOutputStream fos = null;
263                 try {
264                     bufin = new BufferedInputStream(new FileInputStream(file));
265                     fos = new FileOutputStream(dFile);
266                     int len = 8196;
267                     byte[] buff = new byte[len];
268                     int n = 0;
269                     while ((n = bufin.read(buff, 0, len)) != -1) {
270                         fos.write(buff, 0, n);
271                     }
272                 } finally {
273                     try {
fdb31c 274                         if (bufin != null) bufin.close();
e36d4d 275                     } catch (Throwable t) {
JM 276                     }
277                     try {
fdb31c 278                         if (fos != null) fos.close();
e36d4d 279                     } catch (Throwable t) {
JM 280                     }
281                 }
282                 dFile.setLastModified(file.lastModified());
283             }
284         }
285     }
699e71 286
1aa6e0 287     /**
JM 288      * Determine the relative path between two files.  Takes into account
289      * canonical paths, if possible.
699e71 290      *
1aa6e0 291      * @param basePath
JM 292      * @param path
293      * @return a relative path from basePath to path
294      */
295     public static String getRelativePath(File basePath, File path) {
a74ddc 296         Path exactBase = Paths.get(getExactFile(basePath).toURI());
JM 297         Path exactPath = Paths.get(getExactFile(path).toURI());
298         if (exactPath.startsWith(exactBase)) {
299             return exactBase.relativize(exactPath).toString();
5e0107 300         }
JM 301         // no relative relationship
302         return null;
1aa6e0 303     }
699e71 304
1aa6e0 305     /**
JM 306      * Returns the exact path for a file. This path will be the canonical path
307      * unless an exception is thrown in which case it will be the absolute path.
699e71 308      *
1aa6e0 309      * @param path
JM 310      * @return the exact file
311      */
312     public static File getExactFile(File path) {
313         try {
314             return path.getCanonicalFile();
315         } catch (IOException e) {
316             return path.getAbsoluteFile();
317         }
318     }
93d506 319
JM 320     public static File resolveParameter(String parameter, File aFolder, String path) {
321         if (aFolder == null) {
699e71 322             // strip any parameter reference
93d506 323             path = path.replace(parameter, "").trim();
JM 324             if (path.length() > 0 && path.charAt(0) == '/') {
325                 // strip leading /
326                 path = path.substring(1);
327             }
328         } else if (path.contains(parameter)) {
329             // replace parameter with path
330             path = path.replace(parameter, aFolder.getAbsolutePath());
331         }
332         return new File(path);
333     }
892570 334 }