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

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