From 11a0bc2918fa71472dc6bff0185a52d4ec77af32 Mon Sep 17 00:00:00 2001 From: aclement Date: Thu, 15 Jul 2010 15:47:56 +0000 Subject: [PATCH] generics --- util/src/org/aspectj/util/FileUtil.java | 279 ++-- util/src/org/aspectj/util/PartialOrder.java | 2 +- .../org/aspectj/util/FileUtilTest.java | 1296 ++++++++--------- 3 files changed, 767 insertions(+), 810 deletions(-) diff --git a/util/src/org/aspectj/util/FileUtil.java b/util/src/org/aspectj/util/FileUtil.java index b5e1df401..75951361f 100644 --- a/util/src/org/aspectj/util/FileUtil.java +++ b/util/src/org/aspectj/util/FileUtil.java @@ -52,7 +52,7 @@ public class FileUtil { public static final File DEFAULT_PARENT = new File("."); // XXX user.dir? /** unmodifiable List of String source file suffixes (including leading ".") */ - public static final List SOURCE_SUFFIXES = Collections.unmodifiableList(Arrays.asList(new String[] { ".java", ".aj" })); + public static final List SOURCE_SUFFIXES = Collections.unmodifiableList(Arrays.asList(new String[] { ".java", ".aj" })); public static final FileFilter ZIP_FILTER = new FileFilter() { public boolean accept(File file) { @@ -133,8 +133,7 @@ public class FileUtil { } /** - * @return 0 if file has no source suffix or the length of the suffix - * otherwise + * @return 0 if file has no source suffix or the length of the suffix otherwise */ public static int sourceSuffixLength(File file) { return (null == file ? 0 : sourceSuffixLength(file.getPath())); @@ -146,8 +145,8 @@ public class FileUtil { return 0; } - for (Iterator iter = SOURCE_SUFFIXES.iterator(); iter.hasNext();) { - String suffix = (String) iter.next(); + for (Iterator iter = SOURCE_SUFFIXES.iterator(); iter.hasNext();) { + String suffix = iter.next(); if (path.endsWith(suffix) || path.toLowerCase().endsWith(suffix)) { return suffix.length(); } @@ -196,8 +195,7 @@ public class FileUtil { } /** - * @throws IllegalArgumentException unless file is readable and not a - * directory + * @throws IllegalArgumentException unless file is readable and not a directory */ public static void throwIaxUnlessCanWriteFile(File file, String label) { if (!canWriteFile(file)) { @@ -227,14 +225,14 @@ public class FileUtil { } /** @return array same length as input, with String paths */ - public static String[] getPaths(List files) { + public static String[] getPaths(List files) { final int size = (null == files ? 0 : files.size()); if (0 == size) { return new String[0]; } String[] result = new String[size]; for (int i = 0; i < size; i++) { - File file = (File) files.get(i); + File file = files.get(i); if (null != file) { result[i] = file.getPath(); } @@ -243,16 +241,13 @@ public class FileUtil { } /** - * 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 package unless the - * classFile has one of the top-level suffixes { com, org, java, javax } as - * a parent directory. + * 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 + * package unless the classFile has one of the top-level suffixes { com, org, java, javax } as a parent directory. * * @param basedir the File of the base directory (prefix of classFile) * @param classFile the File of the class to extract the name for - * @throws IllegalArgumentException if classFile is null or does not end - * with ".class" or a non-null basedir is not a prefix of - * classFile + * @throws IllegalArgumentException if classFile is null or does not end with ".class" or a non-null basedir is not a prefix of + * classFile */ public static String fileToClassName(File basedir, File classFile) { LangUtil.throwIaxIfNull(classFile, "classFile"); @@ -290,12 +285,10 @@ public class FileUtil { } /** - * Normalize path for comparisons by rendering absolute, clipping basedir - * prefix, trimming and changing '\\' to '/' + * Normalize path for comparisons by rendering absolute, clipping basedir prefix, trimming and changing '\\' to '/' * * @param file the File with the path to normalize - * @param basedir the File for the prefix of the file to normalize - ignored - * if null + * @param basedir the File for the prefix of the file to normalize - ignored if null * @return "" if null or normalized path otherwise * @throws IllegalArgumentException if basedir is not a prefix of file */ @@ -314,15 +307,12 @@ public class FileUtil { } /** - * Render a set of files to String as a path by getting absolute paths of - * each and delimiting with infix. + * Render a set of files to String as a path by getting absolute paths of each and delimiting with infix. * * @param files the File[] to flatten - may be null or empty - * @param infix the String delimiter internally between entries (if null, - * then use File.pathSeparator). (alias to - * flatten(getAbsolutePaths(files), infix) - * @return String with absolute paths to entries in order, delimited with - * infix + * @param infix the String delimiter internally between entries (if null, then use File.pathSeparator). (alias to + * flatten(getAbsolutePaths(files), infix) + * @return String with absolute paths to entries in order, delimited with infix */ public static String flatten(File[] files, String infix) { if (LangUtil.isEmpty(files)) { @@ -359,8 +349,7 @@ public class FileUtil { } /** - * Normalize path for comparisons by rendering absolute trimming and - * changing '\\' to '/' + * Normalize path for comparisons by rendering absolute trimming and changing '\\' to '/' * * @return "" if null or normalized path otherwise */ @@ -369,8 +358,7 @@ public class FileUtil { } /** - * Weakly normalize path for comparisons by trimming and changing '\\' to - * '/' + * Weakly normalize path for comparisons by trimming and changing '\\' to '/' */ public static String weakNormalize(String path) { if (null != path) { @@ -380,9 +368,8 @@ public class FileUtil { } /** - * Get best File for the first-readable path in input paths, treating - * entries prefixed "sp:" as system property keys. Safe to call in static - * initializers. + * Get best File for the first-readable path in input paths, treating entries prefixed "sp:" as system property keys. Safe to + * call in static initializers. * * @param paths the String[] of paths to check. * @return null if not found, or valid File otherwise @@ -483,8 +470,8 @@ public class FileUtil { } /** - * Recursively delete some contents of dir, but not the dir itself. This - * deletes any subdirectory which is empty after its files are deleted. + * Recursively delete some contents of dir, but not the dir itself. This deletes any subdirectory which is empty after its files + * are deleted. * * @return the total number of files deleted */ @@ -493,9 +480,8 @@ public class FileUtil { } /** - * Recursively delete some contents of dir, but not the dir itself. If - * deleteEmptyDirs is true, this deletes any subdirectory which is empty - * after its files are deleted. + * Recursively delete some contents of dir, but not the dir itself. If deleteEmptyDirs is true, this deletes any subdirectory + * which is empty after its files are deleted. * * @param dir the File directory (if a file, the the file is deleted) * @return the total number of files deleted @@ -543,17 +529,13 @@ public class FileUtil { } /** - * Recursively copy files in fromDir (with any fromSuffix) to toDir, - * replacing fromSuffix with toSuffix if any. This silently ignores dirs and - * files that are not readable but throw IOException for directories that - * are not writable. This does not clean out the original contents of toDir. - * (subdirectories are not renamed per directory rules) + * Recursively copy files in fromDir (with any fromSuffix) to toDir, replacing fromSuffix with toSuffix if any. This silently + * ignores dirs and files that are not readable but throw IOException for directories that are not writable. This does not clean + * out the original contents of toDir. (subdirectories are not renamed per directory rules) * - * @param fromSuffix select files with this suffix - select all if null or - * empty - * @param toSuffix replace fromSuffix with toSuffix in the destination file - * name - ignored if null or empty, appended to name if - * fromSuffix is null or empty + * @param fromSuffix select files with this suffix - select all if null or empty + * @param toSuffix replace fromSuffix with toSuffix in the destination file name - ignored if null or empty, appended to name if + * fromSuffix is null or empty * @return the total number of files copied */ public static int copyDir(File fromDir, File toDir, final String fromSuffix, String toSuffix) throws IOException { @@ -596,18 +578,14 @@ public class FileUtil { // } /** - * Recursively copy files in fromDir (with any fromSuffix) to toDir, - * replacing fromSuffix with toSuffix if any. This silently ignores dirs and - * files that are not readable but throw IOException for directories that - * are not writable. This does not clean out the original contents of toDir. - * (subdirectories are not renamed per directory rules) This calls any - * delegate FilenameFilter to collect any selected file. + * Recursively copy files in fromDir (with any fromSuffix) to toDir, replacing fromSuffix with toSuffix if any. This silently + * ignores dirs and files that are not readable but throw IOException for directories that are not writable. This does not clean + * out the original contents of toDir. (subdirectories are not renamed per directory rules) This calls any delegate + * FilenameFilter to collect any selected file. * - * @param fromSuffix select files with this suffix - select all if null or - * empty - * @param toSuffix replace fromSuffix with toSuffix in the destination file - * name - ignored if null or empty, appended to name if - * fromSuffix is null or empty + * @param fromSuffix select files with this suffix - select all if null or empty + * @param toSuffix replace fromSuffix with toSuffix in the destination file name - ignored if null or empty, appended to name if + * fromSuffix is null or empty * @return the total number of files copied */ public static int copyDir(File fromDir, File toDir, final String fromSuffix, final String toSuffix, final FileFilter delegate) @@ -662,15 +640,14 @@ public class FileUtil { /** * Recursively list files in srcDir. * - * @return ArrayList with String paths of File under srcDir (relative to - * srcDir) + * @return ArrayList with String paths of File under srcDir (relative to srcDir) */ public static String[] listFiles(File srcDir) { - ArrayList result = new ArrayList(); + ArrayList result = new ArrayList(); if ((null != srcDir) && srcDir.canRead()) { listFiles(srcDir, null, result); } - return (String[]) result.toArray(new String[0]); + return result.toArray(new String[0]); } public static final FileFilter aspectjSourceFileFilter = new FileFilter() { @@ -683,15 +660,14 @@ public class FileUtil { /** * Recursively list files in srcDir. * - * @return ArrayList with String paths of File under srcDir (relative to - * srcDir) + * @return ArrayList with String paths of File under srcDir (relative to srcDir) */ public static File[] listFiles(File srcDir, FileFilter fileFilter) { - ArrayList result = new ArrayList(); + ArrayList result = new ArrayList(); if ((null != srcDir) && srcDir.canRead()) { listFiles(srcDir, result, fileFilter); } - return (File[]) result.toArray(new File[result.size()]); + return result.toArray(new File[result.size()]); } /** @@ -699,8 +675,8 @@ public class FileUtil { * * @return List of File objects */ - public static List listClassFiles(File dir) { - ArrayList result = new ArrayList(); + public static List listClassFiles(File dir) { + ArrayList result = new ArrayList(); if ((null != dir) && dir.canRead()) { listClassFiles(dir, result); } @@ -710,8 +686,7 @@ public class FileUtil { /** * Convert String[] paths to File[] as offset of base directory * - * @param basedir the non-null File base directory for File to create with - * paths + * @param basedir the non-null File base directory for File to create with paths * @param paths the String[] of paths to create * @return File[] with same length as paths */ @@ -722,11 +697,9 @@ public class FileUtil { /** * Convert String[] paths to File[] as offset of base directory * - * @param basedir the non-null File base directory for File to create with - * paths + * @param basedir the non-null File base directory for File to create with paths * @param paths the String[] of paths to create - * @param suffixes the String[] of suffixes to limit sources to - ignored if - * null + * @param suffixes the String[] of suffixes to limit sources to - ignored if null * @return File[] with same length as paths */ public static File[] getBaseDirFiles(File basedir, String[] paths, String[] suffixes) { @@ -734,7 +707,7 @@ public class FileUtil { LangUtil.throwIaxIfNull(paths, "paths"); File[] result = null; if (!LangUtil.isEmpty(suffixes)) { - ArrayList list = new ArrayList(); + ArrayList list = new ArrayList(); for (int i = 0; i < paths.length; i++) { String path = paths[i]; for (int j = 0; j < suffixes.length; j++) { @@ -744,7 +717,7 @@ public class FileUtil { } } } - result = (File[]) list.toArray(new File[0]); + result = list.toArray(new File[0]); } else { result = new File[paths.length]; for (int i = 0; i < result.length; i++) { @@ -777,18 +750,14 @@ public class FileUtil { } /** - * Copy files from source dir into destination directory, creating any - * needed directories. This differs from copyDir in not being recursive; - * each input with the source dir creates a full path. However, if the - * source is a directory, it is copied as such. + * Copy files from source dir into destination directory, creating any needed directories. This differs from copyDir in not + * being recursive; each input with the source dir creates a full path. However, if the source is a directory, it is copied as + * such. * - * @param srcDir an existing, readable directory containing relativePaths - * files - * @param relativePaths a set of paths relative to srcDir to readable File - * to copy + * @param srcDir an existing, readable directory containing relativePaths files + * @param relativePaths a set of paths relative to srcDir to readable File to copy * @param destDir an existing, writable directory to copy files to - * @throws IllegalArgumentException if input invalid, IOException if - * operations fail + * @throws IllegalArgumentException if input invalid, IOException if operations fail */ public static File[] copyFiles(File srcDir, String[] relativePaths, File destDir) throws IllegalArgumentException, IOException { final String[] paths = relativePaths; @@ -813,13 +782,10 @@ public class FileUtil { } /** - * Copy fromFile to toFile, handling file-file, dir-dir, and file-dir - * copies. + * Copy fromFile to toFile, handling file-file, dir-dir, and file-dir copies. * - * @param fromFile the File path of the file or directory to copy - must be - * readable - * @param toFile the File path of the target file or directory - must be - * writable (will be created if it does not exist) + * @param fromFile the File path of the file or directory to copy - must be readable + * @param toFile the File path of the target file or directory - must be writable (will be created if it does not exist) */ public static void copyFile(File fromFile, File toFile) throws IOException { LangUtil.throwIaxIfNull(fromFile, "fromFile"); @@ -855,14 +821,12 @@ public class FileUtil { } /** - * Ensure that the parent directory to path can be written. If the path has - * a null parent, DEFAULT_PARENT is tested. If the path parent does not - * exist, this tries to create it. + * Ensure that the parent directory to path can be written. If the path has a null parent, DEFAULT_PARENT is tested. If the path + * parent does not exist, this tries to create it. * * @param path the File path whose parent should be writable * @return the File path of the writable parent directory - * @throws IllegalArgumentException if parent cannot be written or path is - * null. + * @throws IllegalArgumentException if parent cannot be written or path is null. */ public static File ensureParentWritable(File path) { LangUtil.throwIaxIfNull(path, "path"); @@ -955,8 +919,8 @@ public class FileUtil { } /** - * Make a new temporary directory in the same directory that the system uses - * for temporary files, or if that files, in the current directory. + * Make a new temporary directory in the same directory that the system uses for temporary files, or if that files, in the + * current directory. * * @param name the preferred (simple) name of the directory - may be null. * @return File of an existing new temp dir, or null if unable to create @@ -995,8 +959,7 @@ public class FileUtil { } /** - * Get URL for a File. This appends "/" for directories. prints errors to - * System.err + * Get URL for a File. This appends "/" for directories. prints errors to System.err * * @param file the File to convert to URL (not null) */ @@ -1019,8 +982,8 @@ public class FileUtil { } /** - * Write contents to file, returning null on success or error message - * otherwise. This tries to make any necessary parent directories first. + * Write contents to file, returning null on success or error message otherwise. This tries to make any necessary parent + * directories first. * * @param file the File to write (not null) * @param contents the String to write (use "" if null) @@ -1059,8 +1022,9 @@ public class FileUtil { public static boolean[] readBooleanArray(DataInputStream s) throws IOException { int len = s.readInt(); boolean[] ret = new boolean[len]; - for (int i = 0; i < len; i++) + for (int i = 0; i < len; i++) { ret[i] = s.readBoolean(); + } return ret; } @@ -1070,8 +1034,9 @@ public class FileUtil { public static void writeBooleanArray(boolean[] a, DataOutputStream s) throws IOException { int len = a.length; s.writeInt(len); - for (int i = 0; i < len; i++) + for (int i = 0; i < len; i++) { s.writeBoolean(a[i]); + } } /** @@ -1080,8 +1045,9 @@ public class FileUtil { public static int[] readIntArray(DataInputStream s) throws IOException { int len = s.readInt(); int[] ret = new int[len]; - for (int i = 0; i < len; i++) + for (int i = 0; i < len; i++) { ret[i] = s.readInt(); + } return ret; } @@ -1091,8 +1057,9 @@ public class FileUtil { public static void writeIntArray(int[] a, DataOutputStream s) throws IOException { int len = a.length; s.writeInt(len); - for (int i = 0; i < len; i++) + for (int i = 0; i < len; i++) { s.writeInt(a[i]); + } } /** @@ -1101,8 +1068,9 @@ public class FileUtil { public static String[] readStringArray(DataInputStream s) throws IOException { int len = s.readInt(); String[] ret = new String[len]; - for (int i = 0; i < len; i++) + for (int i = 0; i < len; i++) { ret[i] = s.readUTF(); + } return ret; } @@ -1116,8 +1084,9 @@ public class FileUtil { } int len = a.length; s.writeInt(len); - for (int i = 0; i < len; i++) + for (int i = 0; i < len; i++) { s.writeUTF(a[i]); + } } /** @@ -1128,8 +1097,9 @@ public class FileUtil { StringBuffer b = new StringBuffer(); while (true) { int ch = r.read(); - if (ch == -1) + if (ch == -1) { break; + } b.append((char) ch); } r.close(); @@ -1173,8 +1143,9 @@ public class FileUtil { while (true) { int nRead = inStream.read(ba, readSoFar, size - readSoFar); - if (nRead == -1) + if (nRead == -1) { break; + } readSoFar += nRead; if (readSoFar == size) { int newSize = size * 2; @@ -1245,25 +1216,22 @@ public class FileUtil { // } /** - * Do line-based search for literal text in source files, returning - * file:line where found. + * Do line-based search for literal text in source files, returning file:line where found. * * @param sought the String text to seek in the file * @param sources the List of String paths to the source files * @param listAll if false, only list first match in file - * @param errorSink the PrintStream to print any errors to (one per line) - * (use null to silently ignore errors) - * @return List of String of the form file:line for each found entry (never - * null, might be empty) + * @param errorSink the PrintStream to print any errors to (one per line) (use null to silently ignore errors) + * @return List of String of the form file:line for each found entry (never null, might be empty) */ // OPTIMIZE only used by tests? move it out - public static List lineSeek(String sought, List sources, boolean listAll, PrintStream errorSink) { + public static List lineSeek(String sought, List sources, boolean listAll, PrintStream errorSink) { if (LangUtil.isEmpty(sought) || LangUtil.isEmpty(sources)) { - return Collections.EMPTY_LIST; + return Collections.emptyList(); } - ArrayList result = new ArrayList(); - for (Iterator iter = sources.iterator(); iter.hasNext();) { - String path = (String) iter.next(); + ArrayList result = new ArrayList(); + for (Iterator iter = sources.iterator(); iter.hasNext();) { + String path = iter.next(); String error = lineSeek(sought, path, listAll, result); if ((null != error) && (null != errorSink)) { errorSink.println(error); @@ -1273,19 +1241,17 @@ public class FileUtil { } /** - * Do line-based search for literal text in source file, returning line - * where found as a String in the form {sourcePath}:line:column submitted to - * the collecting parameter sink. Any error is rendered to String and - * returned as the result. + * Do line-based search for literal text in source file, returning line where found as a String in the form + * {sourcePath}:line:column submitted to the collecting parameter sink. Any error is rendered to String and returned as the + * result. * * @param sought the String text to seek in the file * @param sources the List of String paths to the source files * @param listAll if false, only list first match in file - * @param List sink the List for String entries of the form - * {sourcePath}:line:column + * @param List sink the List for String entries of the form {sourcePath}:line:column * @return String error if any, or add String entries to sink */ - public static String lineSeek(String sought, String sourcePath, boolean listAll, ArrayList sink) { + public static String lineSeek(String sought, String sourcePath, boolean listAll, ArrayList sink) { if (LangUtil.isEmpty(sought) || LangUtil.isEmpty(sourcePath)) { return "nothing sought"; } @@ -1316,8 +1282,9 @@ public class FileUtil { return LangUtil.unqualifiedClassName(e) + " reading " + sourcePath + ":" + lineNum; } finally { try { - if (null != fin) + if (null != fin) { fin.close(); + } } catch (IOException e) { } // ignore } @@ -1326,17 +1293,17 @@ public class FileUtil { public static BufferedOutputStream makeOutputStream(File file) throws FileNotFoundException { File parent = file.getParentFile(); - if (parent != null) + if (parent != null) { parent.mkdirs(); + } return new BufferedOutputStream(new FileOutputStream(file)); } /** * Sleep until after the last last-modified stamp from the files. * - * @param files the File[] of files to inspect for last modified times (this - * ignores null or empty files array and null or non-existing - * components of files array) + * @param files the File[] of files to inspect for last modified times (this ignores null or empty files array and null or + * non-existing components of files array) * @return true if succeeded without 100 interrupts */ public static boolean sleepPastFinalModifiedTime(File[] files) { @@ -1357,7 +1324,7 @@ public class FileUtil { return LangUtil.sleepUntil(++delayUntil); } - private static void listClassFiles(final File baseDir, ArrayList result) { + private static void listClassFiles(final File baseDir, ArrayList result) { File[] files = baseDir.listFiles(); for (int i = 0; i < files.length; i++) { File f = files[i]; @@ -1371,7 +1338,7 @@ public class FileUtil { } } - private static void listFiles(final File baseDir, ArrayList result, FileFilter filter) { + private static void listFiles(final File baseDir, ArrayList result, FileFilter filter) { File[] files = baseDir.listFiles(); // hack https://bugs.eclipse.org/bugs/show_bug.cgi?id=48650 final boolean skipCVS = (!PERMIT_CVS && (filter == aspectjSourceFileFilter)); @@ -1386,8 +1353,9 @@ public class FileUtil { } listFiles(f, result, filter); } else { - if (filter.accept(f)) + if (filter.accept(f)) { result.add(f); + } } } } @@ -1397,7 +1365,7 @@ public class FileUtil { return ((null != input) && (-1 == input.indexOf(File.pathSeparator))); } - private static void listFiles(final File baseDir, String dir, ArrayList result) { + private static void listFiles(final File baseDir, String dir, ArrayList result) { final String dirPrefix = (null == dir ? "" : dir + "/"); final File dirFile = (null == dir ? baseDir : new File(baseDir.getPath() + "/" + dir)); final String[] files = dirFile.list(); @@ -1415,8 +1383,8 @@ public class FileUtil { private FileUtil() { } - public static List makeClasspath(URL[] urls) { - List ret = new LinkedList(); + public static List makeClasspath(URL[] urls) { + List ret = new LinkedList(); if (urls != null) { for (int i = 0; i < urls.length; i++) { ret.add(urls[i].getPath()); @@ -1426,8 +1394,7 @@ public class FileUtil { } /** - * A pipe when run reads from an input stream to an output stream, - * optionally sleeping between reads. + * A pipe when run reads from an input stream to an output stream, optionally sleeping between reads. * * @see #copyStream(InputStream, OutputStream) */ @@ -1446,8 +1413,7 @@ public class FileUtil { private final boolean closeOutput; /** - * If true, then continue processing stream until no characters are - * returned when halting. + * If true, then continue processing stream until no characters are returned when halting. */ private boolean finishStream; @@ -1466,10 +1432,8 @@ public class FileUtil { /** * @param in the InputStream source to read * @param out the OutputStream sink to write - * @param tryClosingStreams if true, then try closing both streams when - * done - * @param sleep milliseconds to delay between reads (pinned to 0..1 - * minute) + * @param tryClosingStreams if true, then try closing both streams when done + * @param sleep milliseconds to delay between reads (pinned to 0..1 minute) */ Pipe(InputStream in, OutputStream out, long sleep, boolean closeInput, boolean closeOutput) { LangUtil.throwIaxIfNull(in, "in"); @@ -1486,8 +1450,7 @@ public class FileUtil { } /** - * Run the pipe. This halts on the first Throwable thrown or when a read - * returns -1 (for end-of-file) or on demand. + * Run the pipe. This halts on the first Throwable thrown or when a read returns -1 (for end-of-file) or on demand. */ public void run() { totalWritten = 0; @@ -1546,10 +1509,8 @@ public class FileUtil { * Tell the pipe to halt the next time it gains control. * * @param wait if true, this waits synchronously until pipe is done - * @param finishStream if true, then continue until a read from the - * input stream returns no bytes, then halt. - * @return true if run() will return the next time it gains - * control + * @param finishStream if true, then continue until a read from the input stream returns no bytes, then halt. + * @return true if run() will return the next time it gains control */ public boolean halt(boolean wait, boolean finishStream) { if (!halt) { @@ -1583,10 +1544,8 @@ public class FileUtil { } /** - * This is called when the pipe is completing. This implementation does - * nothing. Subclasses implement this to get notice. Note that - * halt(true, true) might or might not have completed before this method - * is called. + * This is called when the pipe is completing. This implementation does nothing. Subclasses implement this to get notice. + * Note that halt(true, true) might or might not have completed before this method is called. */ protected void completing(long totalWritten, Throwable thrown) { } diff --git a/util/src/org/aspectj/util/PartialOrder.java b/util/src/org/aspectj/util/PartialOrder.java index 067589ad3..5dd870205 100644 --- a/util/src/org/aspectj/util/PartialOrder.java +++ b/util/src/org/aspectj/util/PartialOrder.java @@ -124,7 +124,7 @@ public class PartialOrder { // ??? I don't like creating this data structure, but it does give good // ??? separation of concerns. - List sortList = new LinkedList(); // objects.size()); + List sortList = new LinkedList(); // objects.size()); for (Iterator i = objects.iterator(); i.hasNext();) { addNewPartialComparable(sortList, (PartialComparable) i.next()); } diff --git a/util/testsrc/org/aspectj/util/FileUtilTest.java b/util/testsrc/org/aspectj/util/FileUtilTest.java index f767cb5a3..3f065278b 100644 --- a/util/testsrc/org/aspectj/util/FileUtilTest.java +++ b/util/testsrc/org/aspectj/util/FileUtilTest.java @@ -30,6 +30,7 @@ import java.util.Iterator; import java.util.List; import java.util.ListIterator; +import junit.framework.AssertionFailedError; import junit.framework.TestCase; import junit.textui.TestRunner; @@ -37,673 +38,670 @@ import junit.textui.TestRunner; * */ public class FileUtilTest extends TestCase { - public static final String[] NONE = new String[0]; - public static boolean log = false; - - public static void main(String[] args) { - TestRunner.main(new String[] {"org.aspectj.util.FileUtilTest"}); - } - - public static void assertSame(String prefix, String[] lhs, String[] rhs) { // XXX cheap diff - String srcPaths = LangUtil.arrayAsList(lhs).toString(); - String destPaths = LangUtil.arrayAsList(rhs).toString(); - if (!srcPaths.equals(destPaths)) { - log("expected: " + srcPaths); - log(" actual: " + destPaths); - assertTrue(prefix + " expected=" + srcPaths - + " != actual=" + destPaths, false); - } - } - - /** - * Verify that dir contains files with names, - * and return the names of other files in dir. - * @return the contents of dir after excluding files - * or NONE if none - * @throws AssertionFailedError if any names are not in dir - */ - public static String[] dirContains(File dir, final String[] filenames) { - final ArrayList sought - = new ArrayList(LangUtil.arrayAsList(filenames)); - FilenameFilter filter = new FilenameFilter() { - public boolean accept(File d, String name) { - return !sought.remove(name); - } - }; - // remove any found from sought and return remainder - String[] found = dir.list(filter); - if (0 < sought.size()) { - assertTrue("found "+ LangUtil.arrayAsList(dir.list()).toString() - + " expected " + sought, false); - } - return (found.length == 0 ? NONE : found); - } - - /** @return sorted String[] of all paths to all files/dirs under dir */ - public static String[] dirPaths(File dir) { - return dirPaths(dir, new String[0]); - } - - /** - * Get a sorted String[] of all paths to all files/dirs under dir. - * Files with names starting with "." are ignored, - * as are directory paths containing "CVS". - * The directory prefix of the path is stripped. - * Thus, given directory: - *
path/to
-     *   .cvsignore
-     *   CVS/
-     *     Root
-     *     Repository
-     *   Base.java
-     *   com/
-     *     parc/
-     *       messages.properties
-     *   org/
-     *     aspectj/
-     *       Version.java
-     * 
- * a call - *
-     *   dirPaths(new File("path/to"), new String[0]);
-     * 
- * returns - *
-     *   { "Base.java", "com/parc/messages.properties", 
-     *     "org/aspectj/Version.java" }
-     * 
- * while the call - *
-     *   dirPaths(new File("path/to"), new String[] { ".java"});
-     * 
- * returns - *
-     *   { "Base.java", "org/aspectj/Version.java" }
-     * 
- * @param dir the File path to the directory to inspect - * @param suffixes if not empty, require files returned to have this suffix - * @return sorted String[] of all paths to all files under dir - * ending with one of the listed suffixes - * but not starting with "." - */ - public static String[] dirPaths(File dir, String[] suffixes) { - ArrayList result = new ArrayList(); - doDirPaths(dir, result); - // if suffixes required, remove those without suffixes - if (!LangUtil.isEmpty(suffixes)) { - for (ListIterator iter = result.listIterator(); iter.hasNext();) { - String path = iter.next().toString(); - boolean hasSuffix = false; - for (int i = 0; !hasSuffix && (i < suffixes.length); i++) { + public static final String[] NONE = new String[0]; + public static boolean log = false; + + public static void main(String[] args) { + TestRunner.main(new String[] { "org.aspectj.util.FileUtilTest" }); + } + + public static void assertSame(String prefix, String[] lhs, String[] rhs) { // XXX cheap diff + String srcPaths = LangUtil.arrayAsList(lhs).toString(); + String destPaths = LangUtil.arrayAsList(rhs).toString(); + if (!srcPaths.equals(destPaths)) { + log("expected: " + srcPaths); + log(" actual: " + destPaths); + assertTrue(prefix + " expected=" + srcPaths + " != actual=" + destPaths, false); + } + } + + /** + * Verify that dir contains files with names, and return the names of other files in dir. + * + * @return the contents of dir after excluding files or NONE if none + * @throws AssertionFailedError if any names are not in dir + */ + public static String[] dirContains(File dir, final String[] filenames) { + final ArrayList sought = new ArrayList(LangUtil.arrayAsList(filenames)); + FilenameFilter filter = new FilenameFilter() { + public boolean accept(File d, String name) { + return !sought.remove(name); + } + }; + // remove any found from sought and return remainder + String[] found = dir.list(filter); + if (0 < sought.size()) { + assertTrue("found " + LangUtil.arrayAsList(dir.list()).toString() + " expected " + sought, false); + } + return (found.length == 0 ? NONE : found); + } + + /** @return sorted String[] of all paths to all files/dirs under dir */ + public static String[] dirPaths(File dir) { + return dirPaths(dir, new String[0]); + } + + /** + * Get a sorted String[] of all paths to all files/dirs under dir. Files with names starting with "." are ignored, as are + * directory paths containing "CVS". The directory prefix of the path is stripped. Thus, given directory: + * + *
+	 * path/to
+	 *   .cvsignore
+	 *   CVS/
+	 *     Root
+	 *     Repository
+	 *   Base.java
+	 *   com/
+	 *     parc/
+	 *       messages.properties
+	 *   org/
+	 *     aspectj/
+	 *       Version.java
+	 * 
+ * + * a call + * + *
+	 * dirPaths(new File("path/to"), new String[0]);
+	 * 
+ * + * returns + * + *
+	 * { "Base.java", "com/parc/messages.properties", "org/aspectj/Version.java" }
+	 * 
+ * + * while the call + * + *
+	 * dirPaths(new File("path/to"), new String[] { ".java" });
+	 * 
+ * + * returns + * + *
+	 * { "Base.java", "org/aspectj/Version.java" }
+	 * 
+ * + * @param dir the File path to the directory to inspect + * @param suffixes if not empty, require files returned to have this suffix + * @return sorted String[] of all paths to all files under dir ending with one of the listed suffixes but not starting with "." + */ + public static String[] dirPaths(File dir, String[] suffixes) { + ArrayList result = new ArrayList(); + doDirPaths(dir, result); + // if suffixes required, remove those without suffixes + if (!LangUtil.isEmpty(suffixes)) { + for (ListIterator iter = result.listIterator(); iter.hasNext();) { + String path = iter.next().toString(); + boolean hasSuffix = false; + for (int i = 0; !hasSuffix && (i < suffixes.length); i++) { hasSuffix = path.endsWith(suffixes[i]); } - if (!hasSuffix) { - iter.remove(); - } + if (!hasSuffix) { + iter.remove(); + } } - } - Collections.sort(result); - // trim prefix - final String prefix = dir.getPath(); - final int len = prefix.length() + 1; // plus directory separator - String[] ra = (String[]) result.toArray(new String[0]); - for (int i = 0; i < ra.length; i++) { - // assertTrue(ra[i].startsWith(prefix)); - assertTrue(ra[i], ra[i].length() > len); - ra[i] = ra[i].substring(len); } - return ra; - } + Collections.sort(result); + // trim prefix + final String prefix = dir.getPath(); + final int len = prefix.length() + 1; // plus directory separator + String[] ra = (String[]) result.toArray(new String[0]); + for (int i = 0; i < ra.length; i++) { + // assertTrue(ra[i].startsWith(prefix)); + assertTrue(ra[i], ra[i].length() > len); + ra[i] = ra[i].substring(len); + } + return ra; + } /** - * @param dir the File to read - ignored if null, not a directory, - * or has "CVS" in its path - * @param useSuffix if true, then use dir as suffix to path - */ - private static void doDirPaths(File dir, ArrayList paths) { - if ((null == dir) || !dir.canRead() - || (-1 != dir.getPath().indexOf("CVS"))) { - return; - } - File[] files = dir.listFiles(); - for (int i = 0; i < files.length; i++) { - String path = files[i].getPath(); - if (!files[i].getName().startsWith(".")) { - if (files[i].isFile()) { - paths.add(path); - } else if (files[i].isDirectory()) { - doDirPaths(files[i], paths); - } else { - log("not file or dir: " - + dir + "/" + path); - } - } + * @param dir the File to read - ignored if null, not a directory, or has "CVS" in its path + * @param useSuffix if true, then use dir as suffix to path + */ + private static void doDirPaths(File dir, ArrayList paths) { + if ((null == dir) || !dir.canRead() || (-1 != dir.getPath().indexOf("CVS"))) { + return; + } + File[] files = dir.listFiles(); + for (int i = 0; i < files.length; i++) { + String path = files[i].getPath(); + if (!files[i].getName().startsWith(".")) { + if (files[i].isFile()) { + paths.add(path); + } else if (files[i].isDirectory()) { + doDirPaths(files[i], paths); + } else { + log("not file or dir: " + dir + "/" + path); + } + } + } + } + + /** Print s if logging is enabled */ + private static void log(String s) { + if (log) { + System.err.println(s); } - } - - /** Print s if logging is enabled */ - private static void log(String s) { - if (log) { - System.err.println(s); - } - } - - /** List of File files or directories to delete when exiting */ - final ArrayList tempFiles; - - public FileUtilTest(String s) { - super(s); - tempFiles = new ArrayList(); - } - - public void tearDown() { - for (ListIterator iter = tempFiles.listIterator(); iter.hasNext();) { + } + + /** List of File files or directories to delete when exiting */ + final ArrayList tempFiles; + + public FileUtilTest(String s) { + super(s); + tempFiles = new ArrayList(); + } + + public void tearDown() { + for (ListIterator iter = tempFiles.listIterator(); iter.hasNext();) { File dir = (File) iter.next(); - log("removing " + dir); + log("removing " + dir); FileUtil.deleteContents(dir); - dir.delete(); - iter.remove(); + dir.delete(); + iter.remove(); + } + } + + public void testNotIsFileIsDirectory() { + File noSuchFile = new File("foo"); + assertTrue(!noSuchFile.isFile()); + assertTrue(!noSuchFile.isDirectory()); + } + + public void testGetBestFile() { + assertNull(FileUtil.getBestFile((String[]) null)); + assertNull(FileUtil.getBestFile(new String[0])); + assertNull(FileUtil.getBestFile(new String[] { "!" })); + File f = FileUtil.getBestFile(new String[] { "." }); + assertNotNull(f); + f = FileUtil.getBestFile(new String[] { "!", "." }); + assertNotNull(f); + assertTrue(f.canRead()); + boolean setProperty = false; + try { + System.setProperty("bestfile", "."); + setProperty = true; + } catch (Throwable t) { + // ignore Security, etc. + } + if (setProperty) { + f = FileUtil.getBestFile(new String[] { "sp:bestfile" }); + assertNotNull(f); + assertTrue(f.canRead()); + } + } + + public void testCopyFiles() { + // bad input + Class iaxClass = IllegalArgumentException.class; + + checkCopyFiles(null, null, iaxClass, false); + + File noSuchFile = new File("foo"); + checkCopyFiles(noSuchFile, null, iaxClass, false); + checkCopyFiles(noSuchFile, noSuchFile, iaxClass, false); + + File tempDir = FileUtil.getTempDir("testCopyFiles"); + tempFiles.add(tempDir); + File fromFile = new File(tempDir, "fromFile"); + String err = FileUtil.writeAsString(fromFile, "contents of from file"); + assertTrue(err, null == err); + checkCopyFiles(fromFile, null, iaxClass, false); + checkCopyFiles(fromFile, fromFile, iaxClass, false); + + // file-file + File toFile = new File(tempDir, "toFile"); + checkCopyFiles(fromFile, toFile, null, true); + + // file-dir + File toDir = new File(tempDir, "toDir"); + assertTrue(toDir.mkdirs()); + checkCopyFiles(fromFile, toDir, null, true); + + // dir-dir + File fromDir = new File(tempDir, "fromDir"); + assertTrue(fromDir.mkdirs()); + checkCopyFiles(fromFile, fromDir, null, false); + File toFile2 = new File(fromDir, "toFile2"); + checkCopyFiles(fromFile, toFile2, null, false); + checkCopyFiles(fromDir, toDir, null, true); + } + + void checkCopyFiles(File from, File to, Class exceptionClass, boolean clean) { + try { + FileUtil.copyFile(from, to); + assertTrue(null == exceptionClass); + if (to.isFile()) { + assertTrue(from.length() == to.length()); // XXX cheap test + } else if (!from.isDirectory()) { + File toFile = new File(to, from.getName()); + assertTrue(from.length() == toFile.length()); + } else { + // from is a dir and to is a dir, toDir should be created, and have the + // same contents as fromDir. + assertTrue(to.exists()); + assertTrue(from.listFiles().length == to.listFiles().length); + } + } catch (Throwable t) { + assertTrue(null != exceptionClass); + assertTrue(exceptionClass.isAssignableFrom(t.getClass())); + } finally { + if (clean && (null != to) && (to.exists())) { + if (to.isDirectory()) { + FileUtil.deleteContents(to); + } + to.delete(); + } + } + } + + public void testDirCopySubdirs() throws IOException { + File srcDir = new File("src"); + File destDir = FileUtil.getTempDir("testDirCopySubdirs"); + tempFiles.add(destDir); + FileUtil.copyDir(srcDir, destDir); + assertSame("testDirCopySubdirs", dirPaths(srcDir), dirPaths(destDir)); + } + + public void testDirCopySubdirsSuffix() throws IOException { + File srcDir = new File("src"); + File destDir = FileUtil.getTempDir("testDirCopySubdirsSuffix"); + tempFiles.add(destDir); + FileUtil.copyDir(srcDir, destDir, ".java", ".aj"); + + String[] sources = dirPaths(srcDir, new String[] { ".java" }); + for (int i = 0; i < sources.length; i++) { + sources[i] = sources[i].substring(0, sources[i].length() - 4); + } + String[] sinks = dirPaths(destDir, new String[] { ".aj" }); + for (int i = 0; i < sinks.length; i++) { + sinks[i] = sinks[i].substring(0, sinks[i].length() - 2); + } + assertSame("testDirCopySubdirs", sources, sinks); + } + + public void testGetURL() { + String[] args = new String[] { ".", "../util/testdata", "../lib/test/aspectjrt.jar" }; + for (int i = 0; i < args.length; i++) { + checkGetURL(args[i]); } - } - - public void testNotIsFileIsDirectory() { - File noSuchFile = new File("foo"); - assertTrue(!noSuchFile.isFile()); - assertTrue(!noSuchFile.isDirectory()); - } - - public void testGetBestFile() { - assertNull(FileUtil.getBestFile((String[]) null)); - assertNull(FileUtil.getBestFile(new String[0])); - assertNull(FileUtil.getBestFile(new String[] {"!"})); - File f = FileUtil.getBestFile(new String[] {"."}); - assertNotNull(f); - f = FileUtil.getBestFile(new String[] {"!", "."}); - assertNotNull(f); - assertTrue(f.canRead()); - boolean setProperty = false; - try { - System.setProperty("bestfile", "."); - setProperty = true; - } catch (Throwable t) { - // ignore Security, etc. - } - if (setProperty) { - f = FileUtil.getBestFile(new String[] {"sp:bestfile"}); - assertNotNull(f); - assertTrue(f.canRead()); - } - } - - public void testCopyFiles() { - // bad input - Class iaxClass = IllegalArgumentException.class; - - checkCopyFiles(null, null, iaxClass, false); - - File noSuchFile = new File("foo"); - checkCopyFiles(noSuchFile, null, iaxClass, false); - checkCopyFiles(noSuchFile, noSuchFile, iaxClass, false); - - File tempDir = FileUtil.getTempDir("testCopyFiles"); - tempFiles.add(tempDir); - File fromFile = new File(tempDir, "fromFile"); - String err = FileUtil.writeAsString(fromFile, "contents of from file"); - assertTrue(err, null == err); - checkCopyFiles(fromFile, null, iaxClass, false); - checkCopyFiles(fromFile, fromFile, iaxClass, false); - - // file-file - File toFile = new File(tempDir, "toFile"); - checkCopyFiles(fromFile, toFile, null, true); - - // file-dir - File toDir= new File(tempDir, "toDir"); - assertTrue(toDir.mkdirs()); - checkCopyFiles(fromFile, toDir, null, true); - - // dir-dir - File fromDir= new File(tempDir, "fromDir"); - assertTrue(fromDir.mkdirs()); - checkCopyFiles(fromFile, fromDir, null, false); - File toFile2 = new File(fromDir, "toFile2"); - checkCopyFiles(fromFile, toFile2, null, false); - checkCopyFiles(fromDir, toDir, null, true); - } - - void checkCopyFiles(File from, File to, Class exceptionClass, boolean clean) { - try { - FileUtil.copyFile(from, to); - assertTrue(null == exceptionClass); - if (to.isFile()) { - assertTrue(from.length() == to.length()); // XXX cheap test - } else if (!from.isDirectory()){ - File toFile = new File(to, from.getName()); - assertTrue(from.length() == toFile.length()); - } else { - // from is a dir and to is a dir, toDir should be created, and have the - // same contents as fromDir. - assertTrue(to.exists()); - assertTrue(from.listFiles().length == to.listFiles().length); - } - } catch (Throwable t) { - assertTrue(null != exceptionClass); - assertTrue(exceptionClass.isAssignableFrom(t.getClass())); - } finally { - if (clean && (null != to) && (to.exists())) { - if (to.isDirectory()) { - FileUtil.deleteContents(to); - } - to.delete(); - } - } - } - - public void testDirCopySubdirs() throws IOException { - File srcDir = new File("src"); - File destDir = FileUtil.getTempDir("testDirCopySubdirs"); - tempFiles.add(destDir); - FileUtil.copyDir(srcDir, destDir); - assertSame("testDirCopySubdirs", dirPaths(srcDir), dirPaths(destDir)); - } - - public void testDirCopySubdirsSuffix() throws IOException { - File srcDir = new File("src"); - File destDir = FileUtil.getTempDir("testDirCopySubdirsSuffix"); - tempFiles.add(destDir); - FileUtil.copyDir(srcDir, destDir, ".java", ".aj"); - - String[] sources = dirPaths(srcDir, new String[] { ".java" }); - for (int i = 0; i < sources.length; i++) { - sources[i] = sources[i].substring(0, sources[i].length()-4); + } + + /** + * Method checkGetURL. + * + * @param string + * @param uRL + */ + private void checkGetURL(String arg) { + assertTrue(null != arg); + File f = new File(arg); + URL url = FileUtil.getFileURL(f); + assertTrue(null != url); + log("url " + url); + if (!f.exists()) { + log("not exist " + f); + } else if (f.isDirectory()) { + log("directory " + f); + } else { + log(" file " + f); + InputStream in = null; + try { + in = url.openStream(); + } catch (IOException e) { + assertTrue("IOException: " + e, false); + } finally { + if (null != in) { + try { + in.close(); + } catch (IOException e) { + } + } + } + } + } + + public void testGetTempDir() { + boolean pass = true; + boolean delete = true; + checkGetTempDir("parent", null, pass, delete); + checkGetTempDir(null, "child", pass, delete); + tempFiles.add(checkGetTempDir("parent", "child", pass, !delete).getParentFile()); + tempFiles.add(checkGetTempDir("parent", "child", pass, !delete).getParentFile()); + tempFiles.add(checkGetTempDir("parent", "child", pass, !delete).getParentFile()); + } + + File checkGetTempDir(String parent, String child, boolean ok, boolean delete) { + File parentDir = FileUtil.getTempDir(parent); + assertTrue("unable to create " + parent, null != parentDir); + File dir = FileUtil.makeNewChildDir(parentDir, child); + log("parent=" + parent + " child=" + child + " -> " + dir); + assertTrue("dir: " + dir, ok == (dir.canWrite() && dir.isDirectory())); + if (delete) { + dir.delete(); + parentDir.delete(); + } + return dir; + } + + public void testRandomFileString() { + ArrayList results = new ArrayList(); + for (int i = 0; i < 1000; i++) { + String s = FileUtil.randomFileString(); + if (results.contains(s)) { + log("warning: got duplicate at iteration " + i); + } + results.add(s); + // System.err.print(" " + s); + // if (0 == (i % 5)) { + // System.err.println(""); + // } } - String[] sinks = dirPaths(destDir, new String[] { ".aj" }); - for (int i = 0; i < sinks.length; i++) { - sinks[i] = sinks[i].substring(0, sinks[i].length()-2); - } - assertSame("testDirCopySubdirs", sources, sinks); - } - - public void testGetURL() { - String[] args = new String[] - {".", "../util/testdata", "../lib/test/aspectjrt.jar" }; - for (int i = 0; i < args.length; i++) { - checkGetURL(args[i]); + } + + public void testNormalizedPath() { + File tempFile = null; + try { + tempFile = File.createTempFile("FileUtilTest_testNormalizedPath", "tmp"); + tempFiles.add(tempFile); + } catch (IOException e) { + log("aborting test - unable to create temp file"); + return; } - } - - /** - * Method checkGetURL. - * @param string - * @param uRL - */ - private void checkGetURL(String arg) { - assertTrue(null != arg); - File f = new File(arg); - URL url = FileUtil.getFileURL(f); - assertTrue(null != url); - log("url " + url); - if (!f.exists()) { - log("not exist " + f); - } else if (f.isDirectory()) { - log("directory " + f); - } else { - log(" file " + f); - InputStream in = null; - try { - in = url.openStream(); - } catch (IOException e) { - assertTrue("IOException: " + e, false); - } finally { - if (null != in) { - try { in.close(); } - catch (IOException e) {} - } - } - } - } - - - public void testGetTempDir() { - boolean pass = true; - boolean delete = true; - checkGetTempDir("parent", null, pass, delete); - checkGetTempDir(null, "child", pass, delete); - tempFiles.add(checkGetTempDir("parent", "child", pass, !delete).getParentFile()); - tempFiles.add(checkGetTempDir("parent", "child", pass, !delete).getParentFile()); - tempFiles.add(checkGetTempDir("parent", "child", pass, !delete).getParentFile()); - } - - File checkGetTempDir(String parent, String child, boolean ok, boolean delete) { - File parentDir = FileUtil.getTempDir(parent); - assertTrue("unable to create " + parent, null != parentDir); - File dir = FileUtil.makeNewChildDir(parentDir, child); - log("parent=" + parent + " child=" + child + " -> " + dir); - assertTrue("dir: " + dir, ok == (dir.canWrite() && dir.isDirectory())); - if (delete) { - dir.delete(); - parentDir.delete(); - } - return dir; - } - - public void testRandomFileString() { - ArrayList results = new ArrayList(); - for (int i = 0; i < 1000; i++) { - String s = FileUtil.randomFileString(); - if (results.contains(s)) { - log("warning: got duplicate at iteration " + i); - } - results.add(s); -// System.err.print(" " + s); -// if (0 == (i % 5)) { -// System.err.println(""); -// } + File parentDir = tempFile.getParentFile(); + String tempFilePath = FileUtil.normalizedPath(tempFile, parentDir); + assertEquals(tempFile.getName(), tempFilePath); + } + + public void testFileToClassName() { + + File basedir = new File("/base/dir"); // never created + File classFile = new File(basedir, "foo/Bar.class"); + assertEquals("foo.Bar", FileUtil.fileToClassName(basedir, classFile)); + + classFile = new File(basedir, "foo\\Bar.class"); + assertEquals("foo.Bar", FileUtil.fileToClassName(basedir, classFile)); + + assertEquals("Bar", FileUtil.fileToClassName(null, classFile)); + + classFile = new File("/home/classes/org/aspectj/lang/JoinPoint.class"); + assertEquals("org.aspectj.lang.JoinPoint", FileUtil.fileToClassName(null, classFile)); + + classFile = new File("/home/classes/com/sun/tools/Javac.class"); + assertEquals("com.sun.tools.Javac", FileUtil.fileToClassName(null, classFile)); + } + + public void testDeleteContents() { + File tempDir = FileUtil.getTempDir("testDeleteContents"); + tempFiles.add(tempDir); + File f = new File(tempDir, "foo"); + f.mkdirs(); + File g = new File(f, "bar"); + g.mkdirs(); + File h = new File(g, "bash"); + h.mkdirs(); + int d = FileUtil.deleteContents(f); + assertTrue(0 == d); + assertTrue(0 == f.list().length); + f.delete(); + assertTrue(!f.exists()); + } + + public void testLineSeek() { + File tempDir = FileUtil.getTempDir("testLineSeek"); + tempFiles.add(tempDir); + File file = new File(tempDir, "testLineSeek"); + String path = file.getPath(); + String contents = "0123456789" + LangUtil.EOL; + contents += contents; + FileUtil.writeAsString(file, contents); + tempFiles.add(file); + List sourceList = new ArrayList(); + sourceList.add(file.getPath()); + + final ArrayList errors = new ArrayList(); + final PrintStream errorSink = new PrintStream(System.err, true) { + public void println(String error) { + errors.add(error); + } + }; + for (int i = 0; i < 10; i++) { + List result = FileUtil.lineSeek("" + i, sourceList, true, errorSink); + assertEquals(2, result.size()); + assertEquals(path + ":1:" + i, result.get(0)); + assertEquals(path + ":2:" + i, result.get(1)); + if (!LangUtil.isEmpty(errors)) { // XXX prefer fast-fail? + assertTrue("errors: " + errors, false); + } } - } - - public void testNormalizedPath() { - File tempFile = null; - try { - tempFile = File.createTempFile("FileUtilTest_testNormalizedPath", "tmp"); - tempFiles.add(tempFile); - } catch (IOException e) { - log("aborting test - unable to create temp file"); - return; - } - File parentDir = tempFile.getParentFile(); - String tempFilePath = FileUtil.normalizedPath(tempFile, parentDir); - assertEquals(tempFile.getName(), tempFilePath); - } - - public void testFileToClassName() { - - File basedir = new File("/base/dir"); // never created - File classFile = new File(basedir, "foo/Bar.class"); - assertEquals("foo.Bar", FileUtil.fileToClassName(basedir, classFile)); - - classFile = new File(basedir, "foo\\Bar.class"); - assertEquals("foo.Bar", FileUtil.fileToClassName(basedir, classFile)); - - assertEquals("Bar", FileUtil.fileToClassName(null, classFile)); - - classFile = new File("/home/classes/org/aspectj/lang/JoinPoint.class"); - assertEquals("org.aspectj.lang.JoinPoint", FileUtil.fileToClassName(null, classFile)); - - classFile = new File("/home/classes/com/sun/tools/Javac.class"); - assertEquals("com.sun.tools.Javac", FileUtil.fileToClassName(null, classFile)); - } - - public void testDeleteContents() { - File tempDir = FileUtil.getTempDir("testDeleteContents"); - tempFiles.add(tempDir); - File f = new File(tempDir, "foo"); - f.mkdirs(); - File g = new File(f, "bar"); - g.mkdirs(); - File h = new File(g, "bash"); - h.mkdirs(); - int d = FileUtil.deleteContents(f); - assertTrue(0 == d); - assertTrue(0 == f.list().length); - f.delete(); - assertTrue(!f.exists()); - } - - public void testLineSeek() { - File tempDir = FileUtil.getTempDir("testLineSeek"); - tempFiles.add(tempDir); - File file = new File(tempDir, "testLineSeek"); - String path = file.getPath(); - String contents = "0123456789" + LangUtil.EOL; - contents += contents; - FileUtil.writeAsString(file, contents); - tempFiles.add(file); - List sourceList = new ArrayList(); - sourceList.add(file.getPath()); - - final ArrayList errors = new ArrayList(); - final PrintStream errorSink = new PrintStream(System.err, true) { - public void println(String error) { - errors.add(error); - } - }; - for (int i = 0; i < 10; i++) { - List result = FileUtil.lineSeek(""+i, sourceList, true, errorSink); - assertEquals(2, result.size()); - assertEquals(path + ":1:" + i, result.get(0)); - assertEquals(path + ":2:" + i, result.get(1)); - if (!LangUtil.isEmpty(errors)) { // XXX prefer fast-fail? - assertTrue("errors: " + errors, false); - } + + } + + public void testLineSeekMore() { + final int MAX = 3; // 1..10 + File tempDir = FileUtil.getTempDir("testLineSeekMore"); + tempFiles.add(tempDir); + final String prefix = new File(tempDir, "testLineSeek").getPath(); + // setup files 0..MAX with 2*MAX lines + String[] sources = new String[MAX]; + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < sources.length; i++) { + sources[i] = new File(prefix + i).getPath(); + sb.append("not matched"); + sb.append(LangUtil.EOL); + sb.append("0123456789"); + sb.append(LangUtil.EOL); } - - } - public void testLineSeekMore() { - final int MAX = 3; // 1..10 - File tempDir = FileUtil.getTempDir("testLineSeekMore"); - tempFiles.add(tempDir); - final String prefix = new File(tempDir, "testLineSeek").getPath(); - // setup files 0..MAX with 2*MAX lines - String[] sources = new String[MAX]; - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < sources.length; i++) { - sources[i] = new File(prefix + i).getPath(); - sb.append("not matched"); - sb.append(LangUtil.EOL); - sb.append("0123456789"); - sb.append(LangUtil.EOL); - } - final String contents = sb.toString(); - for (int i = 0; i < sources.length; i++) { - File file = new File(sources[i]); - FileUtil.writeAsString(file, contents); - tempFiles.add(file); + final String contents = sb.toString(); + for (int i = 0; i < sources.length; i++) { + File file = new File(sources[i]); + FileUtil.writeAsString(file, contents); + tempFiles.add(file); } - // now test - final ArrayList errors = new ArrayList(); - final PrintStream errorSink = new PrintStream(System.err, true) { + // now test + final ArrayList errors = new ArrayList(); + final PrintStream errorSink = new PrintStream(System.err, true) { public void println(String error) { - errors.add(error); + errors.add(error); } - }; - List sourceList = new ArrayList(); - sourceList.addAll(Arrays.asList(sources)); - sourceList = Collections.unmodifiableList(sourceList); - for (int k = 0; k < sources.length; k++) { - List result = FileUtil.lineSeek(""+k, sourceList, true, errorSink); - // number k found in every other line of every file at index k - Iterator iter = result.iterator(); - for (int i = 0; i < MAX; i++) { // for each file - for (int j = 1; j < (MAX+1); j++) { // for every other line - assertTrue(iter.hasNext()); - assertEquals(prefix + i + ":" + 2*j + ":" + k, iter.next()); - } - } - if (!LangUtil.isEmpty(errors)) { // XXX prefer fast-fail? - assertTrue("errors: " + errors, false); - } - } - } - - public void testDirCopyNoSubdirs() throws IOException { - String[] srcFiles = new String[] { "one.java", "two.java", "three.java"}; - String[] destFiles = new String[] { "three.java", "four.java", "five.java" }; - String[] allFiles = new String[] - { "one.java", "two.java", "three.java", "four.java", "five.java" }; - File srcDir = makeTempDir("FileUtilUT_srcDir", srcFiles); - File destDir = makeTempDir("FileUtilUT_destDir", destFiles); - assertTrue(null != srcDir); - assertTrue(null != destDir); - assertTrue(NONE == dirContains(srcDir, srcFiles)); - assertTrue(NONE == dirContains(destDir, destFiles)); - - FileUtil.copyDir(srcDir, destDir); - String[] resultOne = dirContains(destDir, allFiles); - FileUtil.copyDir(srcDir, destDir); - String[] resultTwo = dirContains(destDir, allFiles); - - assertTrue(NONE == resultOne); - assertTrue(NONE == resultTwo); - } - - public void testDirCopyNoSubdirsWithSuffixes() throws IOException { - String[] srcFiles = new String[] { "one.java", "two.java", "three.java"}; - String[] destFiles = new String[] { "three.java", "four.java", "five.java" }; - String[] allFiles = new String[] - { "one.aj", "two.aj", "three.aj", "three.java", "four.java", "five.java" }; - File srcDir = makeTempDir("FileUtilUT_srcDir", srcFiles); - File destDir = makeTempDir("FileUtilUT_destDir", destFiles); - assertTrue(null != srcDir); - assertTrue(null != destDir); - assertTrue(NONE == dirContains(srcDir, srcFiles)); - assertTrue(NONE == dirContains(destDir, destFiles)); - - FileUtil.copyDir(srcDir, destDir, ".java", ".aj"); - FileUtil.copyDir(srcDir, destDir, ".java", ".aj"); - - assertTrue(NONE == dirContains(destDir, allFiles)); - assertTrue(NONE == dirContains(destDir, allFiles)); - } - - public void testDirCopySubdirsSuffixRoundTrip() throws IOException { - final File srcDir = new File("src"); - final File one = FileUtil.getTempDir("testDirCopySubdirsSuffixRoundTrip_1"); - final File two = FileUtil.getTempDir("testDirCopySubdirsSuffixRoundTrip_2"); - FileUtil.copyDir(srcDir, one); // no selection - FileUtil.copyDir(two, one, ".java", ".aj"); // only .java files - FileUtil.copyDir(one, two, ".aj", ".java"); - - FileUtil.deleteContents(one); - one.delete(); - FileUtil.deleteContents(two); - two.delete(); - } - - /** - * Create temp dir at loc containing temp files files. - * Result is registered for deletion on cleanup. - */ - File makeTempDir(String loc, String[] filenames) throws IOException { - File d = new File(loc); - d.mkdirs(); - assertTrue(d.exists()); - tempFiles.add(d); - assertTrue(d.canWrite()); - for (int i = 0; i < filenames.length; i++) { + }; + List sourceList = new ArrayList(); + sourceList.addAll(Arrays.asList(sources)); + sourceList = Collections.unmodifiableList(sourceList); + for (int k = 0; k < sources.length; k++) { + List result = FileUtil.lineSeek("" + k, sourceList, true, errorSink); + // number k found in every other line of every file at index k + Iterator iter = result.iterator(); + for (int i = 0; i < MAX; i++) { // for each file + for (int j = 1; j < (MAX + 1); j++) { // for every other line + assertTrue(iter.hasNext()); + assertEquals(prefix + i + ":" + 2 * j + ":" + k, iter.next()); + } + } + if (!LangUtil.isEmpty(errors)) { // XXX prefer fast-fail? + assertTrue("errors: " + errors, false); + } + } + } + + public void testDirCopyNoSubdirs() throws IOException { + String[] srcFiles = new String[] { "one.java", "two.java", "three.java" }; + String[] destFiles = new String[] { "three.java", "four.java", "five.java" }; + String[] allFiles = new String[] { "one.java", "two.java", "three.java", "four.java", "five.java" }; + File srcDir = makeTempDir("FileUtilUT_srcDir", srcFiles); + File destDir = makeTempDir("FileUtilUT_destDir", destFiles); + assertTrue(null != srcDir); + assertTrue(null != destDir); + assertTrue(NONE == dirContains(srcDir, srcFiles)); + assertTrue(NONE == dirContains(destDir, destFiles)); + + FileUtil.copyDir(srcDir, destDir); + String[] resultOne = dirContains(destDir, allFiles); + FileUtil.copyDir(srcDir, destDir); + String[] resultTwo = dirContains(destDir, allFiles); + + assertTrue(NONE == resultOne); + assertTrue(NONE == resultTwo); + } + + public void testDirCopyNoSubdirsWithSuffixes() throws IOException { + String[] srcFiles = new String[] { "one.java", "two.java", "three.java" }; + String[] destFiles = new String[] { "three.java", "four.java", "five.java" }; + String[] allFiles = new String[] { "one.aj", "two.aj", "three.aj", "three.java", "four.java", "five.java" }; + File srcDir = makeTempDir("FileUtilUT_srcDir", srcFiles); + File destDir = makeTempDir("FileUtilUT_destDir", destFiles); + assertTrue(null != srcDir); + assertTrue(null != destDir); + assertTrue(NONE == dirContains(srcDir, srcFiles)); + assertTrue(NONE == dirContains(destDir, destFiles)); + + FileUtil.copyDir(srcDir, destDir, ".java", ".aj"); + FileUtil.copyDir(srcDir, destDir, ".java", ".aj"); + + assertTrue(NONE == dirContains(destDir, allFiles)); + assertTrue(NONE == dirContains(destDir, allFiles)); + } + + public void testDirCopySubdirsSuffixRoundTrip() throws IOException { + final File srcDir = new File("src"); + final File one = FileUtil.getTempDir("testDirCopySubdirsSuffixRoundTrip_1"); + final File two = FileUtil.getTempDir("testDirCopySubdirsSuffixRoundTrip_2"); + FileUtil.copyDir(srcDir, one); // no selection + FileUtil.copyDir(two, one, ".java", ".aj"); // only .java files + FileUtil.copyDir(one, two, ".aj", ".java"); + + FileUtil.deleteContents(one); + one.delete(); + FileUtil.deleteContents(two); + two.delete(); + } + + /** + * Create temp dir at loc containing temp files files. Result is registered for deletion on cleanup. + */ + File makeTempDir(String loc, String[] filenames) throws IOException { + File d = new File(loc); + d.mkdirs(); + assertTrue(d.exists()); + tempFiles.add(d); + assertTrue(d.canWrite()); + for (int i = 0; i < filenames.length; i++) { File f = new File(d, filenames[i]); - assertTrue(filenames[i], f.createNewFile()); + assertTrue(filenames[i], f.createNewFile()); + } + return d; + } + + public void testPipeEmpty() { + checkPipe(""); + } + + public void testPipeMin() { + checkPipe("0"); + } + + public void testPipe() { + String str = "The quick brown fox jumped over the lazy dog"; + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < 4096; i++) { + sb.append(str); + } + checkPipe(sb.toString()); + } + + void checkPipe(String data) { + StringBufferInputStream in = new StringBufferInputStream(data); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + FileUtil.Pipe pipe = new FileUtil.Pipe(in, out, 100l, true, true); + pipe.run(); + assertTrue(data.equals(out.toString())); + assertTrue(null == pipe.getThrown()); + assertEquals("totalWritten", data.length(), pipe.totalWritten()); + } + + public void testPipeThrown() { + final String data = "The quick brown fox jumped over the lazy dog"; + final IOException thrown = new IOException("test"); + StringBufferInputStream in = new StringBufferInputStream(data); + OutputStream out = new OutputStream() { + public void write(int b) throws IOException { + throw thrown; + } + }; + + FileUtil.Pipe pipe = new FileUtil.Pipe(in, out, 100l, true, true); + pipe.run(); + assertEquals("totalWritten", 0, pipe.totalWritten()); + assertTrue(thrown == pipe.getThrown()); + } + + public void xtestPipeHalt() { // this test periodically fails on the build machine - + // disabling till we have time to figure out why + final long MAX = 1000000; + InputStream in = new InputStream() { + long max = 0; + + public int read() throws IOException { + if (max++ > MAX) { + throw new IOException("test failed"); + } + return 1; + } + + }; + final int minWritten = 20; + class Flag { + boolean hit; + } + final Flag flag = new Flag(); + OutputStream out = new OutputStream() { + long max = 0; + + public void write(int b) throws IOException { + if (max++ > MAX) { + throw new IOException("test failed"); + } else if (max > minWritten) { + if (!flag.hit) { + flag.hit = true; + } + } + } + }; + class Result { + long totalWritten; + Throwable thrown; + boolean set; + } + final Result result = new Result(); + FileUtil.Pipe pipe = new FileUtil.Pipe(in, out, 100l, true, true) { + protected void completing(long totalWritten, Throwable thrown) { + result.totalWritten = totalWritten; + result.thrown = thrown; + result.set = true; + } + }; + // start it up + new Thread(pipe).start(); + // wait for minWritten input + while (!flag.hit) { + try { + Thread.sleep(5l); + } catch (InterruptedException e) { + // ignore + } + } + // halt + assertTrue(pipe.halt(true, true)); + assertTrue(result.set); + assertTrue("Expected null but result.thrown = " + result.thrown, null == result.thrown); + assertTrue(null == pipe.getThrown()); + assertEquals("total written", result.totalWritten, pipe.totalWritten()); + if (minWritten > pipe.totalWritten()) { + assertTrue("written: " + pipe.totalWritten(), false); } - return d; - } - - public void testPipeEmpty() { - checkPipe(""); - } - - public void testPipeMin() { - checkPipe("0"); - } - - public void testPipe() { - String str = "The quick brown fox jumped over the lazy dog"; - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < 4096; i++) { - sb.append(str); - } - checkPipe(sb.toString()); - } - - void checkPipe(String data) { - StringBufferInputStream in = new StringBufferInputStream(data); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - FileUtil.Pipe pipe = new FileUtil.Pipe(in, out, 100l, true, true); - pipe.run(); - assertTrue(data.equals(out.toString())); - assertTrue(null == pipe.getThrown()); - assertEquals("totalWritten", data.length(), pipe.totalWritten()); - } - - public void testPipeThrown() { - final String data = "The quick brown fox jumped over the lazy dog"; - final IOException thrown = new IOException("test"); - StringBufferInputStream in = new StringBufferInputStream(data); - OutputStream out = new OutputStream() { - public void write(int b) throws IOException { - throw thrown; - } - }; - - FileUtil.Pipe pipe = new FileUtil.Pipe(in, out, 100l, true, true); - pipe.run(); - assertEquals("totalWritten", 0, pipe.totalWritten()); - assertTrue(thrown == pipe.getThrown()); - } - - public void xtestPipeHalt() { // this test periodically fails on the build machine - - // disabling till we have time to figure out why - final long MAX = 1000000; - InputStream in = new InputStream() { - long max = 0; - public int read() throws IOException { - if (max++ > MAX) { - throw new IOException("test failed"); - } - return 1; - } - - }; - final int minWritten = 20; - class Flag { - boolean hit; - } - final Flag flag = new Flag(); - OutputStream out = new OutputStream() { - long max = 0; - public void write(int b) throws IOException { - if (max++ > MAX) { - throw new IOException("test failed"); - } else if (max > minWritten) { - if (!flag.hit) { - flag.hit = true; - } - } - } - }; - class Result { - long totalWritten; - Throwable thrown; - boolean set; - } - final Result result = new Result(); - FileUtil.Pipe pipe = new FileUtil.Pipe(in, out, 100l, true, true) { - protected void completing( - long totalWritten, - Throwable thrown) { - result.totalWritten = totalWritten; - result.thrown = thrown; - result.set = true; - } - }; - // start it up - new Thread(pipe).start(); - // wait for minWritten input - while (!flag.hit) { - try { - Thread.sleep(5l); - } catch (InterruptedException e) { - // ignore - } - } - // halt - assertTrue(pipe.halt(true, true)); - assertTrue(result.set); - assertTrue("Expected null but result.thrown = "+result.thrown,null == result.thrown); - assertTrue(null == pipe.getThrown()); - assertEquals("total written", result.totalWritten, pipe.totalWritten()); - if (minWritten > pipe.totalWritten()) { - assertTrue("written: " + pipe.totalWritten(), false); - } - } + } } -- 2.39.5