You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

FileUtil.java 48KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612
  1. /* *******************************************************************
  2. * Copyright (c) 1999-2001 Xerox Corporation,
  3. * 2002 Palo Alto Research Center, Incorporated (PARC).
  4. * All rights reserved.
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Public License v1.0
  7. * which accompanies this distribution and is available at
  8. * http://www.eclipse.org/legal/epl-v10.html
  9. *
  10. * Contributors:
  11. * Xerox/PARC initial implementation
  12. * ******************************************************************/
  13. package org.aspectj.util;
  14. import java.io.BufferedOutputStream;
  15. import java.io.BufferedReader;
  16. import java.io.ByteArrayOutputStream;
  17. import java.io.DataInputStream;
  18. import java.io.DataOutputStream;
  19. import java.io.File;
  20. import java.io.FileFilter;
  21. import java.io.FileInputStream;
  22. import java.io.FileNotFoundException;
  23. import java.io.FileOutputStream;
  24. import java.io.FileReader;
  25. import java.io.FileWriter;
  26. import java.io.FilenameFilter;
  27. import java.io.IOException;
  28. import java.io.InputStream;
  29. import java.io.OutputStream;
  30. import java.io.PrintStream;
  31. import java.io.Reader;
  32. import java.io.StringReader;
  33. import java.io.Writer;
  34. import java.net.MalformedURLException;
  35. import java.net.URISyntaxException;
  36. import java.net.URL;
  37. import java.util.ArrayList;
  38. import java.util.Arrays;
  39. import java.util.Collections;
  40. import java.util.Iterator;
  41. import java.util.LinkedList;
  42. import java.util.List;
  43. import java.util.zip.ZipEntry;
  44. import java.util.zip.ZipFile;
  45. /**
  46. * @author Andy Clement
  47. * @author Kris De Volder
  48. */
  49. public class FileUtil {
  50. /** default parent directory File when a file has a null parent */
  51. public static final File DEFAULT_PARENT = new File("."); // XXX user.dir?
  52. /** unmodifiable List of String source file suffixes (including leading ".") */
  53. public static final List<String> SOURCE_SUFFIXES = Collections.unmodifiableList(Arrays.asList(new String[] { ".java", ".aj" }));
  54. public static final FileFilter ZIP_FILTER = new FileFilter() {
  55. public boolean accept(File file) {
  56. return isZipFile(file);
  57. }
  58. public String toString() {
  59. return "ZIP_FILTER";
  60. }
  61. };
  62. // public static final FileFilter SOURCE_FILTER = new FileFilter() {
  63. // public boolean accept(File file) {
  64. // return hasSourceSuffix(file);
  65. // }
  66. //
  67. // public String toString() {
  68. // return "SOURCE_FILTER";
  69. // }
  70. // };
  71. final static int[] INT_RA = new int[0];
  72. /** accept all files */
  73. public static final FileFilter ALL = new FileFilter() {
  74. public boolean accept(File f) {
  75. return true;
  76. }
  77. };
  78. public static final FileFilter DIRS_AND_WRITABLE_CLASSES = new FileFilter() {
  79. public boolean accept(File file) {
  80. return ((null != file) && (file.isDirectory() || (file.canWrite() && file.getName().toLowerCase().endsWith(".class"))));
  81. }
  82. };
  83. private static final boolean PERMIT_CVS;
  84. static {
  85. String name = FileUtil.class.getName() + ".PERMIT_CVS";
  86. PERMIT_CVS = LangUtil.getBoolean(name, false);
  87. }
  88. /** @return true if file exists and is a zip file */
  89. public static boolean isZipFile(File file) {
  90. try {
  91. return (null != file) && new ZipFile(file) != null;
  92. } catch (IOException e) {
  93. return false;
  94. }
  95. }
  96. /** @return true if path ends with .zip or .jar */
  97. // public static boolean hasZipSuffix(String path) {
  98. // return ((null != path) && (0 != zipSuffixLength(path)));
  99. // }
  100. /** @return 0 if file has no zip/jar suffix or 4 otherwise */
  101. public static int zipSuffixLength(File file) {
  102. return (null == file ? 0 : zipSuffixLength(file.getPath()));
  103. }
  104. /** @return 0 if no zip/jar suffix or 4 otherwise */
  105. public static int zipSuffixLength(String path) {
  106. if ((null != path) && (4 < path.length())) {
  107. String test = path.substring(path.length() - 4).toLowerCase();
  108. if (".zip".equals(test) || ".jar".equals(test)) {
  109. return 4;
  110. }
  111. }
  112. return 0;
  113. }
  114. /** @return true if file path has a source suffix */
  115. public static boolean hasSourceSuffix(File file) {
  116. return ((null != file) && hasSourceSuffix(file.getPath()));
  117. }
  118. /** @return true if path ends with .java or .aj */
  119. public static boolean hasSourceSuffix(String path) {
  120. return ((null != path) && (0 != sourceSuffixLength(path)));
  121. }
  122. /**
  123. * @return 0 if file has no source suffix or the length of the suffix otherwise
  124. */
  125. public static int sourceSuffixLength(File file) {
  126. return (null == file ? 0 : sourceSuffixLength(file.getPath()));
  127. }
  128. /** @return 0 if no source suffix or the length of the suffix otherwise */
  129. public static int sourceSuffixLength(String path) {
  130. if (LangUtil.isEmpty(path)) {
  131. return 0;
  132. }
  133. for (Iterator<String> iter = SOURCE_SUFFIXES.iterator(); iter.hasNext();) {
  134. String suffix = iter.next();
  135. if (path.endsWith(suffix) || path.toLowerCase().endsWith(suffix)) {
  136. return suffix.length();
  137. }
  138. }
  139. return 0;
  140. }
  141. /** @return true if this is a readable directory */
  142. public static boolean canReadDir(File dir) {
  143. return ((null != dir) && dir.canRead() && dir.isDirectory());
  144. }
  145. /** @return true if this is a readable file */
  146. public static boolean canReadFile(File file) {
  147. return ((null != file) && file.canRead() && file.isFile());
  148. }
  149. /** @return true if dir is a writable directory */
  150. public static boolean canWriteDir(File dir) {
  151. return ((null != dir) && dir.canWrite() && dir.isDirectory());
  152. }
  153. /** @return true if this is a writable file */
  154. public static boolean canWriteFile(File file) {
  155. return ((null != file) && file.canWrite() && file.isFile());
  156. }
  157. // /**
  158. // * @throws IllegalArgumentException unless file is readable and not a
  159. // * directory
  160. // */
  161. // public static void throwIaxUnlessCanReadFile(File file, String label) {
  162. // if (!canReadFile(file)) {
  163. // throw new IllegalArgumentException(label + " not readable file: " +
  164. // file);
  165. // }
  166. // }
  167. /**
  168. * @throws IllegalArgumentException unless dir is a readable directory
  169. */
  170. public static void throwIaxUnlessCanReadDir(File dir, String label) {
  171. if (!canReadDir(dir)) {
  172. throw new IllegalArgumentException(label + " not readable dir: " + dir);
  173. }
  174. }
  175. /**
  176. * @throws IllegalArgumentException unless file is readable and not a directory
  177. */
  178. public static void throwIaxUnlessCanWriteFile(File file, String label) {
  179. if (!canWriteFile(file)) {
  180. throw new IllegalArgumentException(label + " not writable file: " + file);
  181. }
  182. }
  183. /** @throws IllegalArgumentException unless dir is a readable directory */
  184. public static void throwIaxUnlessCanWriteDir(File dir, String label) {
  185. if (!canWriteDir(dir)) {
  186. throw new IllegalArgumentException(label + " not writable dir: " + dir);
  187. }
  188. }
  189. /** @return array same length as input, with String paths */
  190. public static String[] getPaths(File[] files) {
  191. if ((null == files) || (0 == files.length)) {
  192. return new String[0];
  193. }
  194. String[] result = new String[files.length];
  195. for (int i = 0; i < result.length; i++) {
  196. if (null != files[i]) {
  197. result[i] = files[i].getPath();
  198. }
  199. }
  200. return result;
  201. }
  202. /** @return array same length as input, with String paths */
  203. public static String[] getPaths(List<File> files) {
  204. final int size = (null == files ? 0 : files.size());
  205. if (0 == size) {
  206. return new String[0];
  207. }
  208. String[] result = new String[size];
  209. for (int i = 0; i < size; i++) {
  210. File file = files.get(i);
  211. if (null != file) {
  212. result[i] = file.getPath();
  213. }
  214. }
  215. return result;
  216. }
  217. /**
  218. * Extract the name of a class from the path to its file. If the basedir is null, then the class is assumed to be in the default
  219. * package unless the classFile has one of the top-level suffixes { com, org, java, javax } as a parent directory.
  220. *
  221. * @param basedir the File of the base directory (prefix of classFile)
  222. * @param classFile the File of the class to extract the name for
  223. * @throws IllegalArgumentException if classFile is null or does not end with ".class" or a non-null basedir is not a prefix of
  224. * classFile
  225. */
  226. public static String fileToClassName(File basedir, File classFile) {
  227. LangUtil.throwIaxIfNull(classFile, "classFile");
  228. String classFilePath = normalizedPath(classFile);
  229. if (!classFilePath.endsWith(".class")) {
  230. String m = classFile + " does not end with .class";
  231. throw new IllegalArgumentException(m);
  232. }
  233. classFilePath = classFilePath.substring(0, classFilePath.length() - 6);
  234. if (null != basedir) {
  235. String basePath = normalizedPath(basedir);
  236. if (!classFilePath.startsWith(basePath)) {
  237. String m = classFile + " does not start with " + basedir;
  238. throw new IllegalArgumentException(m);
  239. }
  240. classFilePath = classFilePath.substring(basePath.length() + 1);
  241. } else {
  242. final String[] suffixes = new String[] { "com", "org", "java", "javax" };
  243. boolean found = false;
  244. for (int i = 0; !found && (i < suffixes.length); i++) {
  245. int loc = classFilePath.indexOf(suffixes[i] + "/");
  246. if ((0 == loc) || ((-1 != loc) && ('/' == classFilePath.charAt(loc - 1)))) {
  247. classFilePath = classFilePath.substring(loc);
  248. found = true;
  249. }
  250. }
  251. if (!found) {
  252. int loc = classFilePath.lastIndexOf("/");
  253. if (-1 != loc) { // treat as default package
  254. classFilePath = classFilePath.substring(loc + 1);
  255. }
  256. }
  257. }
  258. return classFilePath.replace('/', '.');
  259. }
  260. /**
  261. * Normalize path for comparisons by rendering absolute, clipping basedir prefix, trimming and changing '\\' to '/'
  262. *
  263. * @param file the File with the path to normalize
  264. * @param basedir the File for the prefix of the file to normalize - ignored if null
  265. * @return "" if null or normalized path otherwise
  266. * @throws IllegalArgumentException if basedir is not a prefix of file
  267. */
  268. public static String normalizedPath(File file, File basedir) {
  269. String filePath = normalizedPath(file);
  270. if (null != basedir) {
  271. String basePath = normalizedPath(basedir);
  272. if (filePath.startsWith(basePath)) {
  273. filePath = filePath.substring(basePath.length());
  274. if (filePath.startsWith("/")) {
  275. filePath = filePath.substring(1);
  276. }
  277. }
  278. }
  279. return filePath;
  280. }
  281. /**
  282. * Render a set of files to String as a path by getting absolute paths of each and delimiting with infix.
  283. *
  284. * @param files the File[] to flatten - may be null or empty
  285. * @param infix the String delimiter internally between entries (if null, then use File.pathSeparator). (alias to
  286. * <code>flatten(getAbsolutePaths(files), infix)</code>
  287. * @return String with absolute paths to entries in order, delimited with infix
  288. */
  289. public static String flatten(File[] files, String infix) {
  290. if (LangUtil.isEmpty(files)) {
  291. return "";
  292. }
  293. return flatten(getPaths(files), infix);
  294. }
  295. /**
  296. * Flatten File[] to String.
  297. *
  298. * @param files the File[] of paths to flatten - null ignored
  299. * @param infix the String infix to use - null treated as File.pathSeparator
  300. */
  301. public static String flatten(String[] paths, String infix) {
  302. if (null == infix) {
  303. infix = File.pathSeparator;
  304. }
  305. StringBuffer result = new StringBuffer();
  306. boolean first = true;
  307. for (int i = 0; i < paths.length; i++) {
  308. String path = paths[i];
  309. if (null == path) {
  310. continue;
  311. }
  312. if (first) {
  313. first = false;
  314. } else {
  315. result.append(infix);
  316. }
  317. result.append(path);
  318. }
  319. return result.toString();
  320. }
  321. /**
  322. * Normalize path for comparisons by rendering absolute trimming and changing '\\' to '/'
  323. *
  324. * @return "" if null or normalized path otherwise
  325. */
  326. public static String normalizedPath(File file) {
  327. return (null == file ? "" : weakNormalize(file.getAbsolutePath()));
  328. }
  329. /**
  330. * Weakly normalize path for comparisons by trimming and changing '\\' to '/'
  331. */
  332. public static String weakNormalize(String path) {
  333. if (null != path) {
  334. path = path.replace('\\', '/').trim();
  335. }
  336. return path;
  337. }
  338. /**
  339. * Get best File for the first-readable path in input paths, treating entries prefixed "sp:" as system property keys. Safe to
  340. * call in static initializers.
  341. *
  342. * @param paths the String[] of paths to check.
  343. * @return null if not found, or valid File otherwise
  344. */
  345. public static File getBestFile(String[] paths) {
  346. if (null == paths) {
  347. return null;
  348. }
  349. File result = null;
  350. for (int i = 0; (null == result) && (i < paths.length); i++) {
  351. String path = paths[i];
  352. if (null == path) {
  353. continue;
  354. }
  355. if (path.startsWith("sp:")) {
  356. try {
  357. path = System.getProperty(path.substring(3));
  358. } catch (Throwable t) {
  359. path = null;
  360. }
  361. if (null == path) {
  362. continue;
  363. }
  364. }
  365. try {
  366. File f = new File(path);
  367. if (f.exists() && f.canRead()) {
  368. result = FileUtil.getBestFile(f);
  369. }
  370. } catch (Throwable t) {
  371. // swallow
  372. }
  373. }
  374. return result;
  375. }
  376. public static File getBestFile(String[] paths, boolean mustBeJar) {
  377. if (null == paths) {
  378. return null;
  379. }
  380. File result = null;
  381. for (int i = 0; (null == result) && (i < paths.length); i++) {
  382. String path = paths[i];
  383. if (null == path) {
  384. continue;
  385. }
  386. if (path.startsWith("sp:")) {
  387. try {
  388. path = System.getProperty(path.substring(3));
  389. } catch (Throwable t) {
  390. path = null;
  391. }
  392. if (null == path) {
  393. continue;
  394. }
  395. }
  396. try {
  397. File f = new File(path);
  398. if (f.exists() && f.canRead()) {
  399. if (mustBeJar && !f.isDirectory()) {
  400. result = FileUtil.getBestFile(f);
  401. }
  402. }
  403. } catch (Throwable t) {
  404. // swallow
  405. }
  406. }
  407. return result;
  408. }
  409. /**
  410. * Render as best file, canonical or absolute.
  411. *
  412. * @param file the File to get the best File for (not null)
  413. * @return File of the best-available path
  414. * @throws IllegalArgumentException if file is null
  415. */
  416. public static File getBestFile(File file) {
  417. LangUtil.throwIaxIfNull(file, "file");
  418. if (file.exists()) {
  419. try {
  420. return file.getCanonicalFile();
  421. } catch (IOException e) {
  422. return file.getAbsoluteFile();
  423. }
  424. } else {
  425. return file;
  426. }
  427. }
  428. /**
  429. * Render as best path, canonical or absolute.
  430. *
  431. * @param file the File to get the path for (not null)
  432. * @return String of the best-available path
  433. * @throws IllegalArgumentException if file is null
  434. */
  435. public static String getBestPath(File file) {
  436. LangUtil.throwIaxIfNull(file, "file");
  437. if (file.exists()) {
  438. try {
  439. return file.getCanonicalPath();
  440. } catch (IOException e) {
  441. return file.getAbsolutePath();
  442. }
  443. } else {
  444. return file.getPath();
  445. }
  446. }
  447. /** @return array same length as input, with String absolute paths */
  448. public static String[] getAbsolutePaths(File[] files) {
  449. if ((null == files) || (0 == files.length)) {
  450. return new String[0];
  451. }
  452. String[] result = new String[files.length];
  453. for (int i = 0; i < result.length; i++) {
  454. if (null != files[i]) {
  455. result[i] = files[i].getAbsolutePath();
  456. }
  457. }
  458. return result;
  459. }
  460. /**
  461. * Recursively delete the contents of dir, but not the dir itself
  462. *
  463. * @return the total number of files deleted
  464. */
  465. public static int deleteContents(File dir) {
  466. return deleteContents(dir, ALL);
  467. }
  468. /**
  469. * Recursively delete some contents of dir, but not the dir itself. This deletes any subdirectory which is empty after its files
  470. * are deleted.
  471. *
  472. * @return the total number of files deleted
  473. */
  474. public static int deleteContents(File dir, FileFilter filter) {
  475. return deleteContents(dir, filter, true);
  476. }
  477. /**
  478. * Recursively delete some contents of dir, but not the dir itself. If deleteEmptyDirs is true, this deletes any subdirectory
  479. * which is empty after its files are deleted.
  480. *
  481. * @param dir the File directory (if a file, the the file is deleted)
  482. * @return the total number of files deleted
  483. */
  484. public static int deleteContents(File dir, FileFilter filter,
  485. boolean deleteEmptyDirs) {
  486. if (null == dir) {
  487. throw new IllegalArgumentException("null dir");
  488. }
  489. if ((!dir.exists()) || (!dir.canWrite())) {
  490. return 0;
  491. }
  492. if (!dir.isDirectory()) {
  493. dir.delete();
  494. return 1;
  495. }
  496. String[] fromFiles = dir.list();
  497. if (fromFiles == null) {
  498. return 0;
  499. }
  500. int result = 0;
  501. for (int i = 0; i < fromFiles.length; i++) {
  502. String string = fromFiles[i];
  503. File file = new File(dir, string);
  504. if ((null == filter) || filter.accept(file)) {
  505. if (file.isDirectory()) {
  506. result += deleteContents(file, filter, deleteEmptyDirs);
  507. String[] fileContent = file.list();
  508. if (deleteEmptyDirs && fileContent != null
  509. && 0 == fileContent.length) {
  510. file.delete();
  511. }
  512. } else {
  513. /* boolean ret = */
  514. file.delete();
  515. result++;
  516. }
  517. }
  518. }
  519. return result;
  520. }
  521. /**
  522. * Copy contents of fromDir into toDir
  523. *
  524. * @param fromDir must exist and be readable
  525. * @param toDir must exist or be creatable and be writable
  526. * @return the total number of files copied
  527. */
  528. public static int copyDir(File fromDir, File toDir) throws IOException {
  529. return copyDir(fromDir, toDir, null, null);
  530. }
  531. /**
  532. * Recursively copy files in fromDir (with any fromSuffix) to toDir, replacing fromSuffix with toSuffix if any. This silently
  533. * ignores dirs and files that are not readable but throw IOException for directories that are not writable. This does not clean
  534. * out the original contents of toDir. (subdirectories are not renamed per directory rules)
  535. *
  536. * @param fromSuffix select files with this suffix - select all if null or empty
  537. * @param toSuffix replace fromSuffix with toSuffix in the destination file name - ignored if null or empty, appended to name if
  538. * fromSuffix is null or empty
  539. * @return the total number of files copied
  540. */
  541. public static int copyDir(File fromDir, File toDir, final String fromSuffix, String toSuffix) throws IOException {
  542. return copyDir(fromDir, toDir, fromSuffix, toSuffix, (FileFilter) null);
  543. }
  544. // /**
  545. // * Recursively copy files in fromDir (with any fromSuffix) to toDir,
  546. // * replacing fromSuffix with toSuffix if any, and adding the destination
  547. // * file to any collector. This silently ignores dirs and files that are
  548. // not
  549. // * readable but throw IOException for directories that are not writable.
  550. // * This does not clean out the original contents of toDir. (subdirectories
  551. // * are not renamed per directory rules) This calls any delegate
  552. // * FilenameFilter to collect any selected file.
  553. // *
  554. // * @param fromSuffix select files with this suffix - select all if null or
  555. // * empty
  556. // * @param toSuffix replace fromSuffix with toSuffix in the destination
  557. // file
  558. // * name - ignored if null or empty, appended to name if
  559. // * fromSuffix is null or empty
  560. // * @param collector the List sink for destination files - ignored if null
  561. // * @return the total number of files copied
  562. // */
  563. // public static int copyDir(File fromDir, File toDir, final String
  564. // fromSuffix, final String toSuffix, final List collector)
  565. // throws IOException {
  566. // // int before = collector.size();
  567. // if (null == collector) {
  568. // return copyDir(fromDir, toDir, fromSuffix, toSuffix);
  569. // } else {
  570. // FileFilter collect = new FileFilter() {
  571. // public boolean accept(File pathname) {
  572. // return collector.add(pathname);
  573. // }
  574. // };
  575. // return copyDir(fromDir, toDir, fromSuffix, toSuffix, collect);
  576. // }
  577. // }
  578. /**
  579. * Recursively copy files in fromDir (with any fromSuffix) to toDir, replacing fromSuffix with toSuffix if any. This silently
  580. * ignores dirs and files that are not readable but throw IOException for directories that are not writable. This does not clean
  581. * out the original contents of toDir. (subdirectories are not renamed per directory rules) This calls any delegate
  582. * FilenameFilter to collect any selected file.
  583. *
  584. * @param fromSuffix select files with this suffix - select all if null or empty
  585. * @param toSuffix replace fromSuffix with toSuffix in the destination file name - ignored if null or empty, appended to name if
  586. * fromSuffix is null or empty
  587. * @return the total number of files copied
  588. */
  589. public static int copyDir(File fromDir, File toDir, final String fromSuffix, final String toSuffix, final FileFilter delegate)
  590. throws IOException {
  591. if ((null == fromDir) || (!fromDir.canRead())) {
  592. return 0;
  593. }
  594. final boolean haveSuffix = ((null != fromSuffix) && (0 < fromSuffix.length()));
  595. final int slen = (!haveSuffix ? 0 : fromSuffix.length());
  596. if (!toDir.exists()) {
  597. toDir.mkdirs();
  598. }
  599. final String[] fromFiles;
  600. if (!haveSuffix) {
  601. fromFiles = fromDir.list();
  602. } else {
  603. FilenameFilter filter = new FilenameFilter() {
  604. public boolean accept(File dir, String name) {
  605. return (new File(dir, name).isDirectory() || (name.endsWith(fromSuffix)));
  606. }
  607. };
  608. fromFiles = fromDir.list(filter);
  609. }
  610. int result = 0;
  611. final int MAX = (null == fromFiles ? 0 : fromFiles.length);
  612. for (int i = 0; i < MAX; i++) {
  613. String filename = fromFiles[i];
  614. File fromFile = new File(fromDir, filename);
  615. if (fromFile.canRead()) {
  616. if (fromFile.isDirectory()) {
  617. result += copyDir(fromFile, new File(toDir, filename), fromSuffix, toSuffix, delegate);
  618. } else if (fromFile.isFile()) {
  619. if (haveSuffix) {
  620. filename = filename.substring(0, filename.length() - slen);
  621. }
  622. if (null != toSuffix) {
  623. filename = filename + toSuffix;
  624. }
  625. File targetFile = new File(toDir, filename);
  626. if ((null == delegate) || delegate.accept(targetFile)) {
  627. copyFile(fromFile, targetFile);
  628. }
  629. result++;
  630. }
  631. }
  632. }
  633. return result;
  634. }
  635. /**
  636. * Recursively list files in srcDir.
  637. *
  638. * @return ArrayList with String paths of File under srcDir (relative to srcDir)
  639. */
  640. public static String[] listFiles(File srcDir) {
  641. ArrayList<String> result = new ArrayList<String>();
  642. if ((null != srcDir) && srcDir.canRead()) {
  643. listFiles(srcDir, null, result);
  644. }
  645. return result.toArray(new String[0]);
  646. }
  647. public static final FileFilter aspectjSourceFileFilter = new FileFilter() {
  648. public boolean accept(File pathname) {
  649. String name = pathname.getName().toLowerCase();
  650. return name.endsWith(".java") || name.endsWith(".aj");
  651. }
  652. };
  653. /**
  654. * Recursively list files in srcDir.
  655. *
  656. * @return ArrayList with String paths of File under srcDir (relative to srcDir)
  657. */
  658. public static File[] listFiles(File srcDir, FileFilter fileFilter) {
  659. ArrayList<File> result = new ArrayList<File>();
  660. if ((null != srcDir) && srcDir.canRead()) {
  661. listFiles(srcDir, result, fileFilter);
  662. }
  663. return result.toArray(new File[result.size()]);
  664. }
  665. /**
  666. * Recursively list .class files in specified directory
  667. *
  668. * @return List of File objects
  669. */
  670. public static List<File> listClassFiles(File dir) {
  671. ArrayList<File> result = new ArrayList<File>();
  672. if ((null != dir) && dir.canRead()) {
  673. listClassFiles(dir, result);
  674. }
  675. return result;
  676. }
  677. /**
  678. * Convert String[] paths to File[] as offset of base directory
  679. *
  680. * @param basedir the non-null File base directory for File to create with paths
  681. * @param paths the String[] of paths to create
  682. * @return File[] with same length as paths
  683. */
  684. public static File[] getBaseDirFiles(File basedir, String[] paths) {
  685. return getBaseDirFiles(basedir, paths, (String[]) null);
  686. }
  687. /**
  688. * Convert String[] paths to File[] as offset of base directory
  689. *
  690. * @param basedir the non-null File base directory for File to create with paths
  691. * @param paths the String[] of paths to create
  692. * @param suffixes the String[] of suffixes to limit sources to - ignored if null
  693. * @return File[] with same length as paths
  694. */
  695. public static File[] getBaseDirFiles(File basedir, String[] paths, String[] suffixes) {
  696. LangUtil.throwIaxIfNull(basedir, "basedir");
  697. LangUtil.throwIaxIfNull(paths, "paths");
  698. File[] result = null;
  699. if (!LangUtil.isEmpty(suffixes)) {
  700. ArrayList<File> list = new ArrayList<File>();
  701. for (int i = 0; i < paths.length; i++) {
  702. String path = paths[i];
  703. for (int j = 0; j < suffixes.length; j++) {
  704. if (path.endsWith(suffixes[j])) {
  705. list.add(new File(basedir, paths[i]));
  706. break;
  707. }
  708. }
  709. }
  710. result = list.toArray(new File[0]);
  711. } else {
  712. result = new File[paths.length];
  713. for (int i = 0; i < result.length; i++) {
  714. result[i] = newFile(basedir, paths[i]);
  715. }
  716. }
  717. return result;
  718. }
  719. /**
  720. * Create a new File, resolving paths ".." and "." specially.
  721. *
  722. * @param dir the File for the parent directory of the file
  723. * @param path the path in the parent directory (filename only?)
  724. * @return File for the new file.
  725. */
  726. private static File newFile(File dir, String path) {
  727. if (".".equals(path)) {
  728. return dir;
  729. } else if ("..".equals(path)) {
  730. File parentDir = dir.getParentFile();
  731. if (null != parentDir) {
  732. return parentDir;
  733. } else {
  734. return new File(dir, "..");
  735. }
  736. } else {
  737. return new File(dir, path);
  738. }
  739. }
  740. /**
  741. * Copy files from source dir into destination directory, creating any needed directories. This differs from copyDir in not
  742. * being recursive; each input with the source dir creates a full path. However, if the source is a directory, it is copied as
  743. * such.
  744. *
  745. * @param srcDir an existing, readable directory containing relativePaths files
  746. * @param relativePaths a set of paths relative to srcDir to readable File to copy
  747. * @param destDir an existing, writable directory to copy files to
  748. * @throws IllegalArgumentException if input invalid, IOException if operations fail
  749. */
  750. public static File[] copyFiles(File srcDir, String[] relativePaths, File destDir) throws IllegalArgumentException, IOException {
  751. final String[] paths = relativePaths;
  752. throwIaxUnlessCanReadDir(srcDir, "srcDir");
  753. throwIaxUnlessCanWriteDir(destDir, "destDir");
  754. LangUtil.throwIaxIfNull(paths, "relativePaths");
  755. File[] result = new File[paths.length];
  756. for (int i = 0; i < paths.length; i++) {
  757. String path = paths[i];
  758. LangUtil.throwIaxIfNull(path, "relativePaths-entry");
  759. File src = newFile(srcDir, paths[i]);
  760. File dest = newFile(destDir, path);
  761. File destParent = dest.getParentFile();
  762. if (!destParent.exists()) {
  763. destParent.mkdirs();
  764. }
  765. LangUtil.throwIaxIfFalse(canWriteDir(destParent), "dest-entry-parent");
  766. copyFile(src, dest); // both file-dir and dir-dir copies
  767. result[i] = dest;
  768. }
  769. return result;
  770. }
  771. /**
  772. * Copy fromFile to toFile, handling file-file, dir-dir, and file-dir copies.
  773. *
  774. * @param fromFile the File path of the file or directory to copy - must be readable
  775. * @param toFile the File path of the target file or directory - must be writable (will be created if it does not exist)
  776. */
  777. public static void copyFile(File fromFile, File toFile) throws IOException {
  778. LangUtil.throwIaxIfNull(fromFile, "fromFile");
  779. LangUtil.throwIaxIfNull(toFile, "toFile");
  780. LangUtil.throwIaxIfFalse(!toFile.equals(fromFile), "same file");
  781. if (toFile.isDirectory()) { // existing directory
  782. throwIaxUnlessCanWriteDir(toFile, "toFile");
  783. if (fromFile.isFile()) { // file-dir
  784. File targFile = new File(toFile, fromFile.getName());
  785. copyValidFiles(fromFile, targFile);
  786. } else if (fromFile.isDirectory()) { // dir-dir
  787. copyDir(fromFile, toFile);
  788. } else {
  789. LangUtil.throwIaxIfFalse(false, "not dir or file: " + fromFile);
  790. }
  791. } else if (toFile.isFile()) { // target file exists
  792. if (fromFile.isDirectory()) {
  793. LangUtil.throwIaxIfFalse(false, "can't copy to file dir: " + fromFile);
  794. }
  795. copyValidFiles(fromFile, toFile); // file-file
  796. } else { // target file is a non-existent path -- could be file or dir
  797. /* File toFileParent = */ensureParentWritable(toFile);
  798. if (fromFile.isFile()) {
  799. copyValidFiles(fromFile, toFile);
  800. } else if (fromFile.isDirectory()) {
  801. toFile.mkdirs();
  802. throwIaxUnlessCanWriteDir(toFile, "toFile");
  803. copyDir(fromFile, toFile);
  804. } else {
  805. LangUtil.throwIaxIfFalse(false, "not dir or file: " + fromFile);
  806. }
  807. }
  808. }
  809. /**
  810. * Ensure that the parent directory to path can be written. If the path has a null parent, DEFAULT_PARENT is tested. If the path
  811. * parent does not exist, this tries to create it.
  812. *
  813. * @param path the File path whose parent should be writable
  814. * @return the File path of the writable parent directory
  815. * @throws IllegalArgumentException if parent cannot be written or path is null.
  816. */
  817. public static File ensureParentWritable(File path) {
  818. LangUtil.throwIaxIfNull(path, "path");
  819. File pathParent = path.getParentFile();
  820. if (null == pathParent) {
  821. pathParent = DEFAULT_PARENT;
  822. }
  823. if (!pathParent.canWrite()) {
  824. pathParent.mkdirs();
  825. }
  826. throwIaxUnlessCanWriteDir(pathParent, "pathParent");
  827. return pathParent;
  828. }
  829. /**
  830. * Copy file to file.
  831. *
  832. * @param fromFile the File to copy (readable, non-null file)
  833. * @param toFile the File to copy to (non-null, parent dir exists)
  834. * @throws IOException
  835. */
  836. public static void copyValidFiles(File fromFile, File toFile) throws IOException {
  837. FileInputStream in = null;
  838. FileOutputStream out = null;
  839. try {
  840. in = new FileInputStream(fromFile);
  841. out = new FileOutputStream(toFile);
  842. copyStream(in, out);
  843. } finally {
  844. if (out != null) {
  845. out.close();
  846. }
  847. if (in != null) {
  848. in.close();
  849. }
  850. }
  851. }
  852. /** do line-based copying */
  853. @SuppressWarnings("deprecation")
  854. public static void copyStream(DataInputStream in, PrintStream out) throws IOException {
  855. LangUtil.throwIaxIfNull(in, "in");
  856. LangUtil.throwIaxIfNull(in, "out");
  857. String s;
  858. while (null != (s = in.readLine())) {
  859. out.println(s);
  860. }
  861. }
  862. public static void copyStream(InputStream in, OutputStream out) throws IOException {
  863. final int MAX = 4096;
  864. byte[] buf = new byte[MAX];
  865. for (int bytesRead = in.read(buf, 0, MAX); bytesRead != -1; bytesRead = in.read(buf, 0, MAX)) {
  866. out.write(buf, 0, bytesRead);
  867. }
  868. }
  869. public static void copyStream(Reader in, Writer out) throws IOException {
  870. final int MAX = 4096;
  871. char[] buf = new char[MAX];
  872. for (int bytesRead = in.read(buf, 0, MAX); bytesRead != -1; bytesRead = in.read(buf, 0, MAX)) {
  873. out.write(buf, 0, bytesRead);
  874. }
  875. }
  876. /**
  877. * Make a new child directory of parent
  878. *
  879. * @param parent a File for the parent (writable)
  880. * @param child a prefix for the child directory
  881. * @return a File dir that exists with parentDir as the parent file or null
  882. */
  883. public static File makeNewChildDir(File parent, String child) {
  884. if (null == parent || !parent.canWrite() || !parent.isDirectory()) {
  885. throw new IllegalArgumentException("bad parent: " + parent);
  886. } else if (null == child) {
  887. child = "makeNewChildDir";
  888. } else if (!isValidFileName(child)) {
  889. throw new IllegalArgumentException("bad child: " + child);
  890. }
  891. File result = new File(parent, child);
  892. int safety = 1000;
  893. for (String suffix = FileUtil.randomFileString(); ((0 < --safety) && result.exists()); suffix = FileUtil.randomFileString()) {
  894. result = new File(parent, child + suffix);
  895. }
  896. if (result.exists()) {
  897. System.err.println("exhausted files for child dir in " + parent);
  898. return null;
  899. }
  900. return ((result.mkdirs() && result.exists()) ? result : null);
  901. }
  902. /**
  903. * Make a new temporary directory in the same directory that the system uses for temporary files, or if that files, in the
  904. * current directory.
  905. *
  906. * @param name the preferred (simple) name of the directory - may be null.
  907. * @return File of an existing new temp dir, or null if unable to create
  908. */
  909. public static File getTempDir(String name) {
  910. if (null == name) {
  911. name = "FileUtil_getTempDir";
  912. } else if (!isValidFileName(name)) {
  913. throw new IllegalArgumentException(" invalid: " + name);
  914. }
  915. File result = null;
  916. File tempFile = null;
  917. try {
  918. tempFile = File.createTempFile("ignoreMe", ".txt");
  919. File tempParent = tempFile.getParentFile();
  920. result = makeNewChildDir(tempParent, name);
  921. } catch (IOException t) {
  922. result = makeNewChildDir(new File("."), name);
  923. } finally {
  924. if (null != tempFile) {
  925. tempFile.delete();
  926. }
  927. }
  928. return result;
  929. }
  930. public static URL[] getFileURLs(File[] files) {
  931. if ((null == files) || (0 == files.length)) {
  932. return new URL[0];
  933. }
  934. URL[] result = new URL[files.length]; // XXX dangerous non-copy...
  935. for (int i = 0; i < result.length; i++) {
  936. result[i] = getFileURL(files[i]);
  937. }
  938. return result;
  939. }
  940. /**
  941. * Get URL for a File. This appends "/" for directories. prints errors to System.err
  942. *
  943. * @param file the File to convert to URL (not null)
  944. */
  945. @SuppressWarnings("deprecation")
  946. public static URL getFileURL(File file) {
  947. LangUtil.throwIaxIfNull(file, "file");
  948. URL result = null;
  949. try {
  950. result = file.toURL();// TODO AV - was toURI.toURL that does not
  951. // works on Java 1.3
  952. if (null != result) {
  953. return result;
  954. }
  955. String url = "file:" + file.getAbsolutePath().replace('\\', '/');
  956. result = new URL(url + (file.isDirectory() ? "/" : ""));
  957. } catch (MalformedURLException e) {
  958. String m = "Util.makeURL(\"" + file.getPath() + "\" MUE " + e.getMessage();
  959. System.err.println(m);
  960. }
  961. return result;
  962. }
  963. /**
  964. * Write contents to file, returning null on success or error message otherwise. This tries to make any necessary parent
  965. * directories first.
  966. *
  967. * @param file the File to write (not null)
  968. * @param contents the String to write (use "" if null)
  969. * @return String null on no error, error otherwise
  970. */
  971. public static String writeAsString(File file, String contents) {
  972. LangUtil.throwIaxIfNull(file, "file");
  973. if (null == contents) {
  974. contents = "";
  975. }
  976. Writer out = null;
  977. try {
  978. File parentDir = file.getParentFile();
  979. if (!parentDir.exists() && !parentDir.mkdirs()) {
  980. return "unable to make parent dir for " + file;
  981. }
  982. Reader in = new StringReader(contents);
  983. out = new FileWriter(file);
  984. FileUtil.copyStream(in, out);
  985. return null;
  986. } catch (IOException e) {
  987. return LangUtil.unqualifiedClassName(e) + " writing " + file + ": " + e.getMessage();
  988. } finally {
  989. if (null != out) {
  990. try {
  991. out.close();
  992. } catch (IOException e) {
  993. } // ignored
  994. }
  995. }
  996. }
  997. /**
  998. * Reads a boolean array with our encoding
  999. */
  1000. public static boolean[] readBooleanArray(DataInputStream s) throws IOException {
  1001. int len = s.readInt();
  1002. boolean[] ret = new boolean[len];
  1003. for (int i = 0; i < len; i++) {
  1004. ret[i] = s.readBoolean();
  1005. }
  1006. return ret;
  1007. }
  1008. /**
  1009. * Writes a boolean array with our encoding
  1010. */
  1011. public static void writeBooleanArray(boolean[] a, DataOutputStream s) throws IOException {
  1012. int len = a.length;
  1013. s.writeInt(len);
  1014. for (int i = 0; i < len; i++) {
  1015. s.writeBoolean(a[i]);
  1016. }
  1017. }
  1018. /**
  1019. * Reads an int array with our encoding
  1020. */
  1021. public static int[] readIntArray(DataInputStream s) throws IOException {
  1022. int len = s.readInt();
  1023. int[] ret = new int[len];
  1024. for (int i = 0; i < len; i++) {
  1025. ret[i] = s.readInt();
  1026. }
  1027. return ret;
  1028. }
  1029. /**
  1030. * Writes an int array with our encoding
  1031. */
  1032. public static void writeIntArray(int[] a, DataOutputStream s) throws IOException {
  1033. int len = a.length;
  1034. s.writeInt(len);
  1035. for (int i = 0; i < len; i++) {
  1036. s.writeInt(a[i]);
  1037. }
  1038. }
  1039. /**
  1040. * Reads an int array with our encoding
  1041. */
  1042. public static String[] readStringArray(DataInputStream s) throws IOException {
  1043. int len = s.readInt();
  1044. String[] ret = new String[len];
  1045. for (int i = 0; i < len; i++) {
  1046. ret[i] = s.readUTF();
  1047. }
  1048. return ret;
  1049. }
  1050. /**
  1051. * Writes an int array with our encoding
  1052. */
  1053. public static void writeStringArray(String[] a, DataOutputStream s) throws IOException {
  1054. if (a == null) {
  1055. s.writeInt(0);
  1056. return;
  1057. }
  1058. int len = a.length;
  1059. s.writeInt(len);
  1060. for (int i = 0; i < len; i++) {
  1061. s.writeUTF(a[i]);
  1062. }
  1063. }
  1064. /**
  1065. * Returns the contents of this file as a String
  1066. */
  1067. public static String readAsString(File file) throws IOException {
  1068. BufferedReader r = new BufferedReader(new FileReader(file));
  1069. StringBuffer b = new StringBuffer();
  1070. while (true) {
  1071. int ch = r.read();
  1072. if (ch == -1) {
  1073. break;
  1074. }
  1075. b.append((char) ch);
  1076. }
  1077. r.close();
  1078. return b.toString();
  1079. }
  1080. // /**
  1081. // * Returns the contents of this stream as a String
  1082. // */
  1083. // public static String readAsString(InputStream in) throws IOException {
  1084. // BufferedReader r = new BufferedReader(new InputStreamReader(in));
  1085. // StringBuffer b = new StringBuffer();
  1086. // while (true) {
  1087. // int ch = r.read();
  1088. // if (ch == -1)
  1089. // break;
  1090. // b.append((char) ch);
  1091. // }
  1092. // in.close();
  1093. // r.close();
  1094. // return b.toString();
  1095. // }
  1096. /**
  1097. * Returns the contents of this file as a byte[]
  1098. */
  1099. public static byte[] readAsByteArray(File file) throws IOException {
  1100. FileInputStream in = new FileInputStream(file);
  1101. byte[] ret = FileUtil.readAsByteArray(in);
  1102. in.close();
  1103. return ret;
  1104. }
  1105. /**
  1106. * Reads this input stream and returns contents as a byte[]
  1107. */
  1108. public static byte[] readAsByteArray(InputStream inStream) throws IOException {
  1109. int size = 1024;
  1110. byte[] ba = new byte[size];
  1111. int readSoFar = 0;
  1112. while (true) {
  1113. int nRead = inStream.read(ba, readSoFar, size - readSoFar);
  1114. if (nRead == -1) {
  1115. break;
  1116. }
  1117. readSoFar += nRead;
  1118. if (readSoFar == size) {
  1119. int newSize = size * 2;
  1120. byte[] newBa = new byte[newSize];
  1121. System.arraycopy(ba, 0, newBa, 0, size);
  1122. ba = newBa;
  1123. size = newSize;
  1124. }
  1125. }
  1126. byte[] newBa = new byte[readSoFar];
  1127. System.arraycopy(ba, 0, newBa, 0, readSoFar);
  1128. return newBa;
  1129. }
  1130. final static String FILECHARS = "abcdefghijklmnopqrstuvxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  1131. /** @return semi-random String of length 6 usable as filename suffix */
  1132. static String randomFileString() {
  1133. final double FILECHARS_length = FILECHARS.length();
  1134. final int LEN = 6;
  1135. final char[] result = new char[LEN];
  1136. int index = (int) (Math.random() * 6d);
  1137. for (int i = 0; i < LEN; i++) {
  1138. if (index >= LEN) {
  1139. index = 0;
  1140. }
  1141. result[index++] = FILECHARS.charAt((int) (Math.random() * FILECHARS_length));
  1142. }
  1143. return new String(result);
  1144. }
  1145. public static InputStream getStreamFromZip(String zipFile, String name) {
  1146. try {
  1147. ZipFile zf = new ZipFile(zipFile);
  1148. try {
  1149. ZipEntry entry = zf.getEntry(name);
  1150. return zf.getInputStream(entry);
  1151. } finally {
  1152. // ??? is it safe not to close this zf.close();
  1153. }
  1154. } catch (IOException ioe) {
  1155. return null;
  1156. }
  1157. }
  1158. //
  1159. // public static void extractJar(String zipFile, String outDir) throws
  1160. // IOException {
  1161. // ZipInputStream zs = new ZipInputStream(new FileInputStream(zipFile));
  1162. // ZipEntry entry;
  1163. // while ((entry = zs.getNextEntry()) != null) {
  1164. // if (entry.isDirectory())
  1165. // continue;
  1166. // byte[] in = readAsByteArray(zs);
  1167. //
  1168. // File outFile = new File(outDir + "/" + entry.getName());
  1169. // // if (!outFile.getParentFile().exists())
  1170. // // System.err.println("parent: " + outFile.getParentFile());
  1171. // // System.err.println("parent: " + outFile.getParentFile());
  1172. // outFile.getParentFile().mkdirs();
  1173. // FileOutputStream os = new FileOutputStream(outFile);
  1174. // os.write(in);
  1175. // os.close();
  1176. // zs.closeEntry();
  1177. // }
  1178. // zs.close();
  1179. // }
  1180. /**
  1181. * Do line-based search for literal text in source files, returning file:line where found.
  1182. *
  1183. * @param sought the String text to seek in the file
  1184. * @param sources the List of String paths to the source files
  1185. * @param listAll if false, only list first match in file
  1186. * @param errorSink the PrintStream to print any errors to (one per line) (use null to silently ignore errors)
  1187. * @return List of String of the form file:line for each found entry (never null, might be empty)
  1188. */
  1189. // OPTIMIZE only used by tests? move it out
  1190. public static List<String> lineSeek(String sought, List<String> sources, boolean listAll, PrintStream errorSink) {
  1191. if (LangUtil.isEmpty(sought) || LangUtil.isEmpty(sources)) {
  1192. return Collections.emptyList();
  1193. }
  1194. ArrayList<String> result = new ArrayList<String>();
  1195. for (Iterator<String> iter = sources.iterator(); iter.hasNext();) {
  1196. String path = iter.next();
  1197. String error = lineSeek(sought, path, listAll, result);
  1198. if ((null != error) && (null != errorSink)) {
  1199. errorSink.println(error);
  1200. }
  1201. }
  1202. return result;
  1203. }
  1204. /**
  1205. * Do line-based search for literal text in source file, returning line where found as a String in the form
  1206. * {sourcePath}:line:column submitted to the collecting parameter sink. Any error is rendered to String and returned as the
  1207. * result.
  1208. *
  1209. * @param sought the String text to seek in the file
  1210. * @param sources the List of String paths to the source files
  1211. * @param listAll if false, only list first match in file
  1212. * @param List sink the List for String entries of the form {sourcePath}:line:column
  1213. * @return String error if any, or add String entries to sink
  1214. */
  1215. public static String lineSeek(String sought, String sourcePath, boolean listAll, ArrayList<String> sink) {
  1216. if (LangUtil.isEmpty(sought) || LangUtil.isEmpty(sourcePath)) {
  1217. return "nothing sought";
  1218. }
  1219. if (LangUtil.isEmpty(sourcePath)) {
  1220. return "no sourcePath";
  1221. }
  1222. final File file = new File(sourcePath);
  1223. if (!file.canRead() || !file.isFile()) {
  1224. return "sourcePath not a readable file";
  1225. }
  1226. int lineNum = 0;
  1227. FileReader fin = null;
  1228. try {
  1229. fin = new FileReader(file);
  1230. BufferedReader reader = new BufferedReader(fin);
  1231. String line;
  1232. while (null != (line = reader.readLine())) {
  1233. lineNum++;
  1234. int loc = line.indexOf(sought);
  1235. if (-1 != loc) {
  1236. sink.add(sourcePath + ":" + lineNum + ":" + loc);
  1237. if (!listAll) {
  1238. break;
  1239. }
  1240. }
  1241. }
  1242. } catch (IOException e) {
  1243. return LangUtil.unqualifiedClassName(e) + " reading " + sourcePath + ":" + lineNum;
  1244. } finally {
  1245. try {
  1246. if (null != fin) {
  1247. fin.close();
  1248. }
  1249. } catch (IOException e) {
  1250. } // ignore
  1251. }
  1252. return null;
  1253. }
  1254. public static BufferedOutputStream makeOutputStream(File file) throws FileNotFoundException {
  1255. File parent = file.getParentFile();
  1256. if (parent != null) {
  1257. parent.mkdirs();
  1258. }
  1259. return new BufferedOutputStream(new FileOutputStream(file));
  1260. }
  1261. /**
  1262. * Sleep until after the last last-modified stamp from the files.
  1263. *
  1264. * @param files the File[] of files to inspect for last modified times (this ignores null or empty files array and null or
  1265. * non-existing components of files array)
  1266. * @return true if succeeded without 100 interrupts
  1267. */
  1268. public static boolean sleepPastFinalModifiedTime(File[] files) {
  1269. if ((null == files) || (0 == files.length)) {
  1270. return true;
  1271. }
  1272. long delayUntil = System.currentTimeMillis();
  1273. for (int i = 0; i < files.length; i++) {
  1274. File file = files[i];
  1275. if ((null == file) || !file.exists()) {
  1276. continue;
  1277. }
  1278. long nextModTime = file.lastModified();
  1279. if (nextModTime > delayUntil) {
  1280. delayUntil = nextModTime;
  1281. }
  1282. }
  1283. return LangUtil.sleepUntil(++delayUntil);
  1284. }
  1285. private static void listClassFiles(final File baseDir, ArrayList<File> result) {
  1286. File[] files = baseDir.listFiles();
  1287. for (int i = 0; i < files.length; i++) {
  1288. File f = files[i];
  1289. if (f.isDirectory()) {
  1290. listClassFiles(f, result);
  1291. } else {
  1292. if (f.getName().endsWith(".class")) {
  1293. result.add(f);
  1294. }
  1295. }
  1296. }
  1297. }
  1298. private static void listFiles(final File baseDir, ArrayList<File> result, FileFilter filter) {
  1299. File[] files = baseDir.listFiles();
  1300. // hack https://bugs.eclipse.org/bugs/show_bug.cgi?id=48650
  1301. final boolean skipCVS = (!PERMIT_CVS && (filter == aspectjSourceFileFilter));
  1302. for (int i = 0; i < files.length; i++) {
  1303. File f = files[i];
  1304. if (f.isDirectory()) {
  1305. if (skipCVS) {
  1306. String name = f.getName().toLowerCase();
  1307. if ("cvs".equals(name) || "sccs".equals(name)) {
  1308. continue;
  1309. }
  1310. }
  1311. listFiles(f, result, filter);
  1312. } else {
  1313. if (filter.accept(f)) {
  1314. result.add(f);
  1315. }
  1316. }
  1317. }
  1318. }
  1319. /** @return true if input is not null and contains no path separator */
  1320. private static boolean isValidFileName(String input) {
  1321. return ((null != input) && (-1 == input.indexOf(File.pathSeparator)));
  1322. }
  1323. private static void listFiles(final File baseDir, String dir, ArrayList<String> result) {
  1324. final String dirPrefix = (null == dir ? "" : dir + "/");
  1325. final File dirFile = (null == dir ? baseDir : new File(baseDir.getPath() + "/" + dir));
  1326. final String[] files = dirFile.list();
  1327. for (int i = 0; i < files.length; i++) {
  1328. File f = new File(dirFile, files[i]);
  1329. String path = dirPrefix + files[i];
  1330. if (f.isDirectory()) {
  1331. listFiles(baseDir, path, result);
  1332. } else {
  1333. result.add(path);
  1334. }
  1335. }
  1336. }
  1337. private FileUtil() {
  1338. }
  1339. public static List<String> makeClasspath(URL[] urls) {
  1340. List<String> ret = new LinkedList<String>();
  1341. if (urls != null) {
  1342. for (int i = 0; i < urls.length; i++) {
  1343. ret.add(toPathString(urls[i]));
  1344. }
  1345. }
  1346. return ret;
  1347. }
  1348. private static String toPathString(URL url) {
  1349. try {
  1350. return url.toURI().getPath();
  1351. } catch (URISyntaxException e) {
  1352. System.err.println("Warning!! Malformed URL may cause problems: "+url); // TODO: Better way to report this?
  1353. // In this case it was likely not using properly escaped
  1354. // characters so we just use the 'bad' method that doesn't decode
  1355. // special chars
  1356. return url.getPath();
  1357. }
  1358. }
  1359. /**
  1360. * A pipe when run reads from an input stream to an output stream, optionally sleeping between reads.
  1361. *
  1362. * @see #copyStream(InputStream, OutputStream)
  1363. */
  1364. public static class Pipe implements Runnable {
  1365. private final InputStream in;
  1366. private final OutputStream out;
  1367. private final long sleep;
  1368. private ByteArrayOutputStream snoop;
  1369. private long totalWritten;
  1370. private Throwable thrown;
  1371. private boolean halt;
  1372. /**
  1373. * Seem to be unable to detect erroroneous closing of System.out...
  1374. */
  1375. private final boolean closeInput;
  1376. private final boolean closeOutput;
  1377. /**
  1378. * If true, then continue processing stream until no characters are returned when halting.
  1379. */
  1380. private boolean finishStream;
  1381. private boolean done; // true after completing() completes
  1382. /**
  1383. * alias for <code>Pipe(in, out, 100l, false, false)</code>
  1384. *
  1385. * @param in the InputStream source to read
  1386. * @param out the OutputStream sink to write
  1387. */
  1388. Pipe(InputStream in, OutputStream out) {
  1389. this(in, out, 100l, false, false);
  1390. }
  1391. /**
  1392. * @param in the InputStream source to read
  1393. * @param out the OutputStream sink to write
  1394. * @param tryClosingStreams if true, then try closing both streams when done
  1395. * @param sleep milliseconds to delay between reads (pinned to 0..1 minute)
  1396. */
  1397. Pipe(InputStream in, OutputStream out, long sleep, boolean closeInput, boolean closeOutput) {
  1398. LangUtil.throwIaxIfNull(in, "in");
  1399. LangUtil.throwIaxIfNull(out, "out");
  1400. this.in = in;
  1401. this.out = out;
  1402. this.closeInput = closeInput;
  1403. this.closeOutput = closeOutput;
  1404. this.sleep = Math.min(0l, Math.max(60l * 1000l, sleep));
  1405. }
  1406. public void setSnoop(ByteArrayOutputStream snoop) {
  1407. this.snoop = snoop;
  1408. }
  1409. /**
  1410. * Run the pipe. This halts on the first Throwable thrown or when a read returns -1 (for end-of-file) or on demand.
  1411. */
  1412. public void run() {
  1413. totalWritten = 0;
  1414. if (halt) {
  1415. return;
  1416. }
  1417. try {
  1418. final int MAX = 4096;
  1419. byte[] buf = new byte[MAX];
  1420. // TODO this blocks, hanging the harness
  1421. int count = in.read(buf, 0, MAX);
  1422. ByteArrayOutputStream mySnoop;
  1423. while ((halt && finishStream && (0 < count)) || (!halt && (-1 != count))) {
  1424. out.write(buf, 0, count);
  1425. mySnoop = snoop;
  1426. if (null != mySnoop) {
  1427. mySnoop.write(buf, 0, count);
  1428. }
  1429. totalWritten += count;
  1430. if (halt && !finishStream) {
  1431. break;
  1432. }
  1433. if (!halt && (0 < sleep)) {
  1434. Thread.sleep(sleep);
  1435. }
  1436. if (halt && !finishStream) {
  1437. break;
  1438. }
  1439. count = in.read(buf, 0, MAX);
  1440. }
  1441. } catch (Throwable e) {
  1442. thrown = e;
  1443. } finally {
  1444. halt = true;
  1445. if (closeInput) {
  1446. try {
  1447. in.close();
  1448. } catch (IOException e) {
  1449. // ignore
  1450. }
  1451. }
  1452. if (closeOutput) {
  1453. try {
  1454. out.close();
  1455. } catch (IOException e) {
  1456. // ignore
  1457. }
  1458. }
  1459. done = true;
  1460. completing(totalWritten, thrown);
  1461. }
  1462. }
  1463. /**
  1464. * Tell the pipe to halt the next time it gains control.
  1465. *
  1466. * @param wait if true, this waits synchronously until pipe is done
  1467. * @param finishStream if true, then continue until a read from the input stream returns no bytes, then halt.
  1468. * @return true if <code>run()</code> will return the next time it gains control
  1469. */
  1470. public boolean halt(boolean wait, boolean finishStream) {
  1471. if (!halt) {
  1472. halt = true;
  1473. }
  1474. if (wait) {
  1475. while (!done) {
  1476. synchronized (this) {
  1477. notifyAll();
  1478. }
  1479. if (!done) {
  1480. try {
  1481. Thread.sleep(5l);
  1482. } catch (InterruptedException e) {
  1483. break;
  1484. }
  1485. }
  1486. }
  1487. }
  1488. return halt;
  1489. }
  1490. /** @return the total number of bytes written */
  1491. public long totalWritten() {
  1492. return totalWritten;
  1493. }
  1494. /** @return any exception thrown when reading/writing */
  1495. public Throwable getThrown() {
  1496. return thrown;
  1497. }
  1498. /**
  1499. * This is called when the pipe is completing. This implementation does nothing. Subclasses implement this to get notice.
  1500. * Note that halt(true, true) might or might not have completed before this method is called.
  1501. */
  1502. protected void completing(long totalWritten, Throwable thrown) {
  1503. }
  1504. }
  1505. }