1 /************************************************************************
2  *
3  * Licensed Materials - Property of IBM.
4  * (C) Copyright IBM Corporation 2003, 2012.  All Rights Reserved.
5  * U.S. Government Users Restricted Rights:
6  * Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
7  *
8  ************************************************************************/
9 
10 package org.openoffice.test.common;
11 
12 import java.io.BufferedReader;
13 import java.io.DataOutputStream;
14 import java.io.File;
15 import java.io.FileInputStream;
16 import java.io.FileOutputStream;
17 import java.io.FileReader;
18 import java.io.FileWriter;
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.io.OutputStream;
22 import java.net.URL;
23 import java.net.URLConnection;
24 import java.text.DateFormat;
25 import java.text.SimpleDateFormat;
26 import java.util.Date;
27 import java.util.Properties;
28 import java.util.zip.ZipEntry;
29 import java.util.zip.ZipInputStream;
30 
31 import javax.xml.parsers.DocumentBuilder;
32 import javax.xml.parsers.DocumentBuilderFactory;
33 import javax.xml.xpath.XPath;
34 import javax.xml.xpath.XPathExpression;
35 import javax.xml.xpath.XPathExpressionException;
36 import javax.xml.xpath.XPathFactory;
37 
38 import org.w3c.dom.Document;
39 
40 
41 /**
42  * Utilities related to the file system
43  *
44  */
45 public class FileUtil {
46 
47 	private final static DateFormat FILENAME_FORMAT = new SimpleDateFormat("yyMMddHHmm");
48 
49 	private FileUtil(){
50 
51 	}
52 
53 	public static Document parseXML(String path) {
54 		try {
55 			DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
56 			dbfac.setNamespaceAware(true);
57 			DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
58 			return docBuilder.parse(path);
59 		} catch (Exception e) {
60 			return null;
61 		}
62 	}
63 
64 	public static String getStringByXPath(String xml, String xpathStr) {
65 		Document doc = parseXML(xml);
66 		if (doc == null)
67 			return null;
68 
69 	    try {
70 	    	XPathFactory factory = XPathFactory.newInstance();
71 			XPath xpath = factory.newXPath();
72 			XPathExpression expr = xpath.compile(xpathStr);
73 			return (String) expr.evaluate(doc);
74 		} catch (XPathExpressionException e) {
75 			e.printStackTrace();
76 			return null;
77 		}
78 
79 
80 	}
81 
82 
83 
84 	/**
85 	 * Update the given property in a properties file
86 	 * @param file the properties file path
87 	 * @param key the key
88 	 * @param value the value
89 	 */
90 	public static void updateProperty(String file, String key, String value) {
91 		Properties map = new Properties();
92 		map.put(key, value);
93 		updateProperty(file, map);
94 	}
95 
96 	/**
97 	 * Update the given properties in a properties file
98 	 * @param file the properties file path
99 	 * @param props properties updated
100 	 */
101 	public static void updateProperty(String file, Properties props) {
102 		Properties properties = loadProperties(file);
103 		properties.putAll(props);
104 		storeProperties(file, properties);
105 	}
106 
107 	/**
108 	 * Load a properties file to Properties class
109 	 * @param file the properties file path
110 	 * @return
111 	 */
112 	public static Properties loadProperties(String file) {
113 		Properties properties = new Properties();
114 		FileInputStream fis = null;
115 		try {
116 			fis = new FileInputStream(file);
117 			properties.load(fis);
118 		} catch (IOException e) {
119 			//System.out.println("Can't read properties file.");
120 		} finally {
121 			if (fis != null) {
122 				try {
123 					fis.close();
124 				} catch (IOException e) {
125 					// ignore
126 				}
127 			}
128 		}
129 
130 		return properties;
131 	}
132 
133 	/**
134 	 * Store properties into a file
135 	 * @param file the properties file path
136 	 * @param properties the properties to be stored
137 	 */
138 	public static void storeProperties(String file, Properties properties) {
139 		FileOutputStream fos = null;
140 		try {
141 			fos = new FileOutputStream(file);
142 			properties.store(fos, "Generated By PropertyFileUtils");
143 		} catch (IOException e) {
144 			throw new RuntimeException(e);
145 		} finally {
146 			if (fos != null) {
147 				try {
148 					fos.close();
149 				} catch (IOException e) {
150 					// ignore
151 				}
152 			}
153 		}
154 	}
155 
156 
157 
158 	/**
159 	 * Delete a property in a properties file
160 	 * @param file the properties file path
161 	 * @param key the key to be deleted
162 	 */
163 	public static void deleteProperty(String file, String key) {
164 		Properties properties = loadProperties(file);
165 		properties.remove(key);
166 		storeProperties(file, properties);
167 	}
168 
169 	/**
170 	 * Load a file as string
171 	 * @param file the file path
172 	 * @return
173 	 */
174 	public static String readFileAsString(String file) {
175 		return readFileAsString(new File(file));
176 	}
177 
178 	/**
179 	 * Load a file as string
180 	 * @param file the file path
181 	 * @return
182 	 */
183 	public static String readFileAsString(File file) {
184 		StringBuffer strBuffer = new StringBuffer(10240);
185 		BufferedReader reader = null;
186 		try {
187 			reader = new BufferedReader(new FileReader(file));
188 			char[] buf = new char[1024];
189 			int count = 0;
190 			while ((count = reader.read(buf)) != -1) {
191 				strBuffer.append(buf, 0, count);
192 			}
193 		} catch (IOException e) {
194 		} finally {
195 			if (reader != null)
196 				try {
197 					reader.close();
198 				} catch (IOException e) {
199 					// ignore
200 				}
201 		}
202 
203 		return strBuffer.toString();
204 	}
205 
206 	/**
207 	 * Find the first file matching the given name.
208 	 * @param dir The directory to search in
209 	 * @param name Regular Expression to match the file name
210 	 * @return
211 	 */
212 	public static File findFile(File dir, String name) {
213 		if (!dir.isDirectory())
214 			return null;
215 		File[] files = dir.listFiles();
216 		for (int i = 0; i < files.length; i++) {
217 			if (files[i].isDirectory()) {
218 				File ret = findFile(files[i], name);
219 				if (ret != null)
220 					return ret;
221 			} else if (files[i].getName().matches(name)) {
222 				return files[i];
223 			}
224 		}
225 
226 		return null;
227 	}
228 
229 	/**
230 	 * Find the last file matching the given name.
231 	 * @param dir The directory to search in
232 	 * @param name Regular Expression to match the file name
233 	 * @return
234 	 */
235 	public static File findLastFile(File dir, String name) {
236 		if (!dir.isDirectory())
237 			return null;
238 		File[] files = dir.listFiles();
239 		File file = null;
240 		for (int i = 0; i < files.length; i++) {
241 			if (files[i].isDirectory()) {
242 				File ret = findFile(files[i], name);
243 				if (ret != null)
244 					file = ret;
245 			} else if (files[i].getName().matches(name)) {
246 				file = files[i];
247 			}
248 		}
249 
250 		return file;
251 	}
252 
253 	/**
254 	 * find the first file matching the given name.
255 	 * @param dirs The directories to search in. Use ';' separate each directory.
256 	 * @param name Regular Expression to match the file name
257 	 * @return
258 	 */
259 	public static File findFile(String dirs, String name) {
260 		String[] directories = dirs.split(";");
261 		for (String s : directories) {
262 			File dir = new File(s);
263 			if (!dir.exists())
264 				continue;
265 			File file = findFile(dir, name);
266 			if (file != null)
267 				return file;
268 		}
269 
270 		return null;
271 	}
272 
273 
274 	/**
275 	 * find the last file matching the given name.
276 	 * @param dirs The directories to search in. Use ';' separate each directory.
277 	 * @param name Regular Expression to match the file name
278 	 * @return
279 	 */
280 	public static File findLastFile(String dirs, String name) {
281 		String[] directories = dirs.split(";");
282 		for (String s : directories) {
283 			File dir = new File(s);
284 			if (!dir.exists())
285 				continue;
286 			File file = findLastFile(dir, name);
287 			if (file != null)
288 				return file;
289 		}
290 
291 		return null;
292 	}
293 
294 	/**
295 	 * find the directory matching the given name.
296 	 * @param dir The directory to search in
297 	 * @param name Regular Expression to match the file name
298 	 * @return
299 	 */
300 	public static File findDir(String dir, String dirName) {
301 		File[] files = new File(dir).listFiles();
302 		for (int i = 0; i < files.length; i++) {
303 			if (!files[i].isDirectory()) {
304 				File ret = findFile(files[i], dirName);
305 				if (ret != null)
306 					return ret;
307 			} else if (files[i].getName().matches(dirName)) {
308 				return files[i];
309 			}
310 		}
311 
312 		return null;
313 	}
314 
315 
316 	public static void writeStringToFile(String filePath, String contents) {
317 		FileWriter writer = null;
318 		try {
319 			File file = new File(filePath);
320 			file.getParentFile().mkdirs();
321 			writer = new FileWriter(file);
322 			if (contents != null)
323 				writer.write(contents);
324 		} catch (IOException e) {
325 			e.printStackTrace();
326 		} finally {
327 			if (writer != null)
328 				try {
329 					writer.close();
330 				} catch (IOException e) {
331 				}
332 		}
333 	}
334 
335 	/**
336 	 * Appeand a string to the tail of a file
337 	 * @param file
338 	 * @param contents
339 	 */
340 	public static void appendStringToFile(String file, String contents) {
341 		FileWriter writer = null;
342 		try {
343 			writer = new FileWriter(file, true);
344 			writer.write(contents);
345 		} catch (IOException e) {
346 			System.out.println("Warning:" + e.getMessage());
347 		} finally {
348 			if (writer != null)
349 				try {
350 					writer.close();
351 				} catch (IOException e) {
352 				}
353 		}
354 	}
355 
356 	/**
357 	 * Replace string in the file use regular expression
358 	 * @param file
359 	 * @param expr
360 	 * @param substitute
361 	 */
362 	public static void replace(String file, String expr, String substitute) {
363 		String str = readFileAsString(file);
364 		str = str.replaceAll(expr, substitute);
365 		writeStringToFile(file, str);
366 	}
367 
368     /**
369      * Recursively copy all files in the source dir into the destination dir
370      * @param fromDirName the source dir
371      * @param toDirName the destination dir
372      * @return
373      */
374     public static boolean copyDir(String fromDirName, String toDirName)  {
375     	return copyDir(new File(fromDirName), new File(toDirName), true);
376     }
377 
378     /**
379      * Copy all files in the source dir into the destination dir
380      * @param fromDir
381      * @param toDir
382      * @param recursive
383      * @return
384      */
385     public static boolean copyDir(File fromDir, File toDir, boolean recursive) {
386     	if (!fromDir.exists() || !fromDir.isDirectory()) {
387     		System.err.println("The source dir doesn't exist, or isn't dir.");
388     		return false;
389     	}
390     	if (toDir.exists() && !toDir.isDirectory())
391     		return false;
392     	boolean result = true;
393     	toDir.mkdirs();
394     	File[] files = fromDir.listFiles();
395     	for (int i = 0; i < files.length; i++) {
396     		if (files[i].isDirectory() && recursive)
397     			result &= copyDir(files[i], new File(toDir, files[i].getName()), true);
398     		else
399     			result &= copyFile(files[i], toDir);
400     	}
401 
402     	return result;
403     }
404 
405     /**
406      * Copy a file
407      * @param fromFile
408      * @param toFile
409      * @return
410      */
411     public static boolean copyFile(File fromFile, File toFile) {
412     	 if (!fromFile.exists() || !fromFile.isFile() || !fromFile.canRead()) {
413          	System.err.println(fromFile.getAbsolutePath() + "doesn't exist, or isn't file, or can't be read");
414          	return false;
415          }
416 
417          if (toFile.isDirectory())
418            toFile = new File(toFile, fromFile.getName());
419 
420          FileInputStream from = null;
421          FileOutputStream to = null;
422          try {
423            from = new FileInputStream(fromFile);
424            File p = toFile.getParentFile();
425            if (p != null && !p.exists())
426         	   p.mkdirs();
427            to = new FileOutputStream(toFile);
428            byte[] buffer = new byte[4096];
429            int bytesRead;
430            while ((bytesRead = from.read(buffer)) != -1)
431              to.write(buffer, 0, bytesRead);
432 
433            return true;
434          } catch (IOException e) {
435          	//Can't copy
436          	e.printStackTrace();
437          	return false;
438          } finally {
439            if (from != null)
440              try {
441                from.close();
442              } catch (IOException e) {
443              }
444            if (to != null)
445              try {
446                to.close();
447              } catch (IOException e) {
448              }
449          }
450     }
451 
452     /**
453      * Copy a file
454      * @param fromFileName
455      * @param toFileName
456      * @return
457      */
458     public static boolean copyFile(String fromFileName, String toFileName) {
459     	return copyFile(new File(fromFileName), new File(toFileName));
460     }
461 
462     /**
463      * Copy all the files under fromDirName to toDirName
464      * @param fromDirName
465      * @param toDirName
466      * @return
467      */
468     public static boolean copyFiles(String fromDirName, String toDirName) {
469     	boolean res = true;
470 
471     	File fromDir = new File(fromDirName);
472     	if (!fromDir.exists() || !fromDir.isDirectory() || !fromDir.canRead()) {
473          	System.err.println(fromDir.getAbsolutePath() + "doesn't exist, or isn't file, or can't be read");
474          	return false;
475          }
476     	File [] files = fromDir.listFiles();
477     	for(int i=0; i<files.length; i++){
478     		if(files[i].isDirectory()){
479     			res = res && copyDir(fromDirName + "/" + files[i].getName(), toDirName + "/" + files[i].getName());
480     		}
481     		else
482     			res = res && copyFile(fromDirName + "/" + files[i].getName(), toDirName + "/" + files[i].getName());
483     	}
484     	return res;
485     }
486 
487     /**
488      * Delete a file
489      * @param file
490      * @return
491      */
492     public static boolean deleteFile(File path) {
493     	if (!path.exists())
494     		return true;
495 
496 		if (path.isDirectory()) {
497 			File[] files = path.listFiles();
498 			for (int i = 0; i < files.length; i++) {
499 				if (files[i].isDirectory()) {
500 					deleteFile(files[i]);
501 				} else {
502 					files[i].delete();
503 				}
504 			}
505 		}
506 
507 		return path.delete();
508 	}
509 
510     public static boolean deleteFile(String path) {
511 		return deleteFile(new File(path));
512 	}
513 
514     public static boolean fileExists(String file) {
515     	return new File(file).exists();
516     }
517 
518     /**
519      * Get the extension name of a file
520      * @param file
521      * @return
522      */
523 	public static String getFileExtName(String file) {
524 		if (file == null)
525 			return null;
526 		int i = file.lastIndexOf('.');
527 		if (i < 0 && i >= file.length() - 1)
528 			return null;
529 		return file.substring(i+1);
530 	}
531 	 /**
532      * Get the file's size
533      * @param file
534      * @return KB
535      */
536 	public static long getFileSize(String filePath){
537 		long totalSize = 0;
538 		FileInputStream f = null;
539 		File file = new File(filePath);
540 
541 		try {
542 			f = new FileInputStream(file);
543 			totalSize = f.available();
544 			f.close();
545 		} catch (Exception e) {
546 			// TODO Auto-generated catch block
547 			e.printStackTrace();
548 		}
549 
550 		return totalSize/1000;
551 	}
552 
553 	/**
554      * Get the folder's size
555      * @param folder's path
556      * @return Kb
557      */
558 	public static long getFolderSize(String dir){
559 		long totalSize = 0;
560 		File[] files = new File(dir).listFiles();
561 
562 		for(int i=0; i<files.length; i++){
563 			if(files[i].isDirectory())
564 				totalSize = totalSize + getFolderSize(files[i].getAbsolutePath())*1000;
565 			else
566 				totalSize = totalSize + files[i].length();
567 		}
568 
569 		return totalSize/1000;
570 	}
571 
572 	/**
573      * unzip file to the unzipToLoc
574      * @param folder's path
575      * @return Kb
576      */
577 	public static void unzipFile(String unzipfile, String unzipDest){
578 		    try {
579 		      File dest = new File(unzipDest);
580 		      ZipInputStream zin = new ZipInputStream(new FileInputStream(unzipfile));
581 		      ZipEntry entry;
582 		      //Create folder
583 		      while ( (entry = zin.getNextEntry()) != null){
584 		        if (entry.isDirectory()) {
585 		          File directory = new File(dest, entry.getName());
586 		          if (!directory.exists())
587 		            if (!directory.mkdirs())
588 		              System.exit(0);
589 		          zin.closeEntry();
590 		        }
591 		        if (!entry.isDirectory()) {
592 		          File myFile = new File(entry.getName());
593 		          FileOutputStream fout = new FileOutputStream(unzipDest + "/" + myFile.getPath());
594 		          DataOutputStream dout = new DataOutputStream(fout);
595 		          byte[] b = new byte[1024];
596 		          int len = 0;
597 		          while ( (len = zin.read(b)) != -1) {
598 		            dout.write(b, 0, len);
599 		          }
600 		          dout.close();
601 		          fout.close();
602 		          zin.closeEntry();
603 		        }
604 		      }
605 		    }
606 		    catch (IOException e) {
607 		      e.printStackTrace();
608 		      System.out.println(e);
609 		    }
610 	}
611 
612 	public static File getUniqueFile(File dir, String prefix, String suffix) {
613 		String name = prefix + "." + FILENAME_FORMAT.format(new Date()) + ".";
614 		for (int i = 0; i < Integer.MAX_VALUE; i++) {
615 			File file = new File(dir, name + i + suffix);
616 			if (!file.exists()) {
617 				return file;
618 			}
619 		}
620 
621 		return null;
622 	}
623 
624 	public static File getUniqueFile(String dir, String prefix, String suffix) {
625 		return getUniqueFile(new File(dir), prefix, suffix);
626 	}
627 
628 
629 	public static File download(String urlString, File output) {
630 		InputStream in = null;
631 		OutputStream out = null;
632 		System.out.println("[Vclauto] Download '" + urlString + "'");
633 		try {
634 			URL url = new URL(urlString);
635 			URLConnection urlConnection = url.openConnection();
636 			int totalSize = urlConnection.getContentLength();
637 			in = urlConnection.getInputStream();
638 			if (output.isDirectory()) {
639 				output = new File(output, url.getPath());
640 				output.getParentFile().mkdirs();
641 			}
642 			out = new FileOutputStream(output);
643 
644 			byte[] buffer = new byte[1024 * 100]; // 100k
645 			int count = 0;
646 			int totalCount = 0;
647 			int progress = 0;
648 			while ((count = in.read(buffer)) > 0) {
649 				out.write(buffer, 0, count);
650 				totalCount += count;
651 
652 				if (totalSize > 0) {
653 					int nowProgress = totalCount * 10 / totalSize;
654 					if (nowProgress > progress) {
655 						progress = nowProgress;
656 						System.out.print(".");
657 					}
658 				}
659 
660 			}
661 			System.out.println("Done!");
662 			return output;
663 		} catch (Exception e) {
664 			e.printStackTrace();
665 			System.out.println("Error!");
666 			return null;
667 		} finally {
668 			if (in != null)
669 				try {
670 					in.close();
671 				} catch (IOException e) {
672 				}
673 			if (out != null)
674 				try {
675 					out.close();
676 				} catch (IOException e) {
677 
678 				}
679 		}
680 	}
681 
682 }
683