libcommons-io-java-2.4.orig/0000755000175000017500000000000012125050425015330 5ustar ebourgebourglibcommons-io-java-2.4.orig/build.xml0000644000175000017500000003222712125050425017157 0ustar ebourgebourg libcommons-io-java-2.4.orig/checkstyle.xml0000644000175000017500000000375412125050425020221 0ustar ebourgebourg libcommons-io-java-2.4.orig/NOTICE.txt0000644000175000017500000000025412125050425017053 0ustar ebourgebourgApache Commons IO Copyright 2002-2012 The Apache Software Foundation This product includes software developed by The Apache Software Foundation (http://www.apache.org/). libcommons-io-java-2.4.orig/pom.xml0000644000175000017500000002316312125050425016652 0ustar ebourgebourg org.apache.commons commons-parent 25 4.0.0 commons-io commons-io 2.4 Commons IO 2002 The Commons IO library contains utility classes, stream implementations, file filters, file comparators, endian transformation classes, and much more. http://commons.apache.org/io/ jira http://issues.apache.org/jira/browse/IO apache.website Apache Commons IO Site ${commons.deployment.protocol}://people.apache.org/www/commons.apache.org/${commons.componentid} scm:svn:http://svn.apache.org/repos/asf/commons/proper/io/trunk scm:svn:https://svn.apache.org/repos/asf/commons/proper/io/trunk http://svn.apache.org/viewvc/commons/proper/io/trunk Scott Sanders sanders sanders@apache.org Java Developer dIon Gillard dion dion@apache.org Java Developer Nicola Ken Barozzi nicolaken nicolaken@apache.org Java Developer Henri Yandell bayard bayard@apache.org Java Developer Stephen Colebourne scolebourne Java Developer 0 Jeremias Maerki jeremias jeremias@apache.org Java Developer +1 Matthew Hawthorne matth matth@apache.org Java Developer Martin Cooper martinc martinc@apache.org Java Developer Rob Oxspring roxspring roxspring@apache.org Java Developer Jochen Wiedmann jochen jochen.wiedmann@gmail.com Niall Pemberton niallp Java Developer Jukka Zitting jukka Java Developer Gary Gregory ggregory ggregory@apache.org http://www.garygregory.com -5 Rahul Akolkar Jason Anderson Nathan Beyer Emmanuel Bourg Chris Eldredge Magnus Grimsell Jim Harrington Thomas Ledoux Andy Lehane Marcelo Liberato Alban Peignier alban.peignier at free.fr Ian Springer Masato Tezuka James Urie Frank W. Zammetti junit junit 4.10 test 1.6 1.6 io RC1 2.4 (requires JDK 1.6+) 2.2 (requires JDK 1.5+) IO 12310477 org.apache.commons.io; org.apache.commons.io.comparator; org.apache.commons.io.filefilter; org.apache.commons.io.input; org.apache.commons.io.output;version=1.4.9999;-noimport:=true, org.apache.commons.io; org.apache.commons.io.comparator; org.apache.commons.io.filefilter; org.apache.commons.io.input; org.apache.commons.io.output; org.apache.commons.io.*;version=${project.version};-noimport:=true org.apache.maven.plugins maven-surefire-plugin pertest -Xmx25M **/*Test*.class **/*AbstractTestCase* **/testtools/** **/*$* maven-assembly-plugin src/main/assembly/bin.xml src/main/assembly/src.xml gnu org.apache.maven.plugins maven-checkstyle-plugin 2.9.1 ${basedir}/checkstyle.xml false org.codehaus.mojo findbugs-maven-plugin 2.4.0 Normal Default ${basedir}/findbugs-exclude-filter.xml org.apache.rat apache-rat-plugin src/test/resources/**/*.bin .pmd libcommons-io-java-2.4.orig/PROPOSAL.html0000644000175000017500000000575312125050425017467 0ustar ebourgebourg Proposal for IO Package

Proposal for IO Package

(0) Rationale

Many software projects have a need to perform I/O in various ways, and the JDK class libraries provide a lot of functionality, but sometimes you need just a little bit more. The io package seeks to encapsulate some of the most popular i/o base classes into one easy to use package.

(1) Scope of the Package

This proposal is to create a package of Java utility classes for various types of i/o related activity.

(1.5) Interaction With Other Packages

IO relies only on standard JDK 1.2 (or later) APIs for production deployment. It utilizes the JUnit unit testing framework for developing and executing unit tests, but this is of interest only to developers of the component. IO will be a dependency for several existing components in the open source world.

No external configuration files are utilized.

(2) Initial Source of the Package

The original Java classes are splashed around various Apache subprojects. We intend to seek them out and integrate them.

The proposed package name for the new component is org.apache.commons.io.

(3) Required Jakarta-Commons Resources

  • CVS Repository - New directory io in the jakarta-commons CVS repository.
  • Mailing List - Discussions will take place on the general dev@commons.apache.org mailing list. To help list subscribers identify messages of interest, it is suggested that the message subject of messages about this component be prefixed with [IO].
  • Bugzilla - New component "IO" under the "Commons" product category, with appropriate version identifiers as needed.
  • Jyve FAQ - New category "commons-io" (when available).

(4) Initial Committers

The initial committers on the IO component shall be Scott Sanders and Nicola Ken Barozzi and Henri Yandell


libcommons-io-java-2.4.orig/RELEASE-NOTES.txt0000644000175000017500000010574512125050425020053 0ustar ebourgebourg Apache Commons IO Version 2.4 Release Notes INTRODUCTION: Commons IO is a package of Java utility classes like java.io. Classes in this package are considered to be so standard and of such high reuse as to justify existence in java.io. The Commons IO library contains utility classes, stream implementations, file filters, file comparators, endian transformation classes, and much more. ============================================================================== Apache Commons IO Version 2.4 ============================================================================== New features and bug fixes. Changes in this version include: New features: o IO-269: Tailer locks file from deletion/rename on Windows. Thanks to sebb. o IO-333: Export OSGi packages at version 1.x in addition to 2.x. Thanks to fmeschbe. o IO-320: Add XmlStreamReader support for UTF-32. Thanks to ggregory. o IO-331: BOMInputStream wrongly detects UTF-32LE_BOM files as UTF-16LE_BOM files in method getBOM(). Thanks to ggregory. o IO-327: Add byteCountToDisplaySize(BigInteger). Thanks to ggregory. o IO-326: Add new FileUtils.sizeOf[Directory] APIs to return BigInteger. Thanks to ggregory, kinow. o IO-325: Add IOUtils.toByteArray methods to work with URL and URI. Thanks to raviprak. o IO-324: Add missing Charset sister APIs to method that take a String charset name. Thanks to raviprak. Fixed Bugs: o IO-336: Yottabyte (YB) incorrectly defined in FileUtils. Thanks to rleavelle. o IO-279: Tailer erroneously considers file as new. Thanks to Sergio Bossa, Chris Baron. o IO-335: Tailer#readLines - incorrect CR handling. o IO-334: FileUtils.toURLs throws NPE for null parameter; document the behavior. o IO-332: Improve tailer's reading performance. Thanks to liangly. o IO-279: Improve Tailer performance with buffered reads (see IO-332). o IO-329: FileUtils.writeLines uses unbuffered IO. Thanks to tivv. o IO-319: FileUtils.sizeOfDirectory follows symbolic links. Thanks to raviprak. Compatibility with 2.3: Binary compatible: Yes. Source compatible: Yes. Semantic compatible: Yes. Compatibility with 2.2 and 1.4: Binary compatible: Yes. Source compatible: No, see the rare case in https://issues.apache.org/jira/browse/IO-318. Semantic compatible: No, see the rare case in https://issues.apache.org/jira/browse/IO-318. Commons IO 2.4 requires JDK 1.6 or later. Commons IO 2.3 requires JDK 1.6 or later. Commons IO 2.2 requires JDK 1.5 or later. Commons IO 1.4 requires JDK 1.3 or later. ============================================================================== Apache Commons IO Version 2.3 ============================================================================== Changes in this version include: New features: o IO-322: Add and use class Charsets. Thanks to ggregory. o IO-321: ByteOrderMark UTF_32LE is incorrect. Thanks to ggregory. o IO-318: Add Charset sister APIs to method that take a String charset name. Thanks to ggregory. Compatibility with 2.2 and 1.4: Binary compatible: Yes. Source compatible: No, see the rare case in https://issues.apache.org/jira/browse/IO-318. Semantic compatible: No, see the rare case in https://issues.apache.org/jira/browse/IO-318. Commons IO 2.3 requires JDK 1.6 or later. Commons IO 2.2 requires JDK 1.5 or later. Commons IO 1.4 requires JDK 1.3 or later. ============================================================================== Apache Commons IO Version 2.2 ============================================================================== Changes in this version include: New features: o Add IOUTils.toBufferedReader(Reader) Issue: IO-313. Thanks to ggregory. o Allow applications to provide buffer (or size) for copyLarge methods. Issue: IO-308. Thanks to Manoj Mokashi. o New copyLarge() method in IOUtils that takes additional offset, length arguments Issue: IO-305. Thanks to Manoj Mokashi. o Use terabyte (TB), petabyte (PB) and exabyte (EB) in FileUtils.byteCountToDisplaySize(long size) Issue: IO-287. Thanks to Ron Kuris, Gary Gregory. o FileUtils.listFiles() doesn't return directories Issue: IO-173. Thanks to Marcos Vinícius da Silva. o CharSequenceInputStream to efficiently stream content of a CharSequence Issue: IO-297. Thanks to Oleg Kalnichevski. o The second constructor of Tailer class does not pass 'delay' to the third one Issue: IO-304. Thanks to liangly. o TeeOutputStream does not call branch.close() when main.close() throws an exception Issue: IO-303. Thanks to fabian.barney. o ArrayIndexOutOfBoundsException in BOMInputStream when reading a file without BOM multiple times Issue: IO-302. Thanks to jsteuerwald, detinho. o Add IOUtils.closeQuietly(Selector) necessary Issue: IO-301. Thanks to kaykay.unique. o IOUtils.closeQuietly() should take a ServerSocket as a parameter Issue: IO-292. Thanks to sebb. o Add read/readFully methods to IOUtils Issue: IO-290. Thanks to sebb. o Supply a ReversedLinesFileReader Issue: IO-288. Thanks to Georg Henzler. o Add new function FileUtils.directoryContains. Issue: IO-291. Thanks to ggregory. o FileUtils.contentEquals and IOUtils.contentEquals - Add option to ignore "line endings" Added contentEqualsIgnoreEOL methods to both classes Issue: IO-275. Thanks to CJ Aspromgos. Fixed Bugs: o IOUtils.read(InputStream/Reader) ignores the offset parameter Issue: IO-311. Thanks to Robert Muir. o CharSequenceInputStream(CharSequence s, Charset charset, int bufferSize) ignores bufferSize Issue: IO-312. o FileUtils.moveDirectoryToDirectory removes source directory if destination is a subdirectory Issue: IO-300. o ReaderInputStream#read(byte[] b, int off, int len) should check for valid parameters Issue: IO-307. o ReaderInputStream#read(byte[] b, int off, int len) should always return 0 for length == 0 Issue: IO-306. o "FileUtils#deleteDirectoryOnExit(File)" does not work Issue: IO-276. Thanks to nkami. o BoundedInputStream.read() treats max differently from BoundedInputStream.read(byte[]...) Issue: IO-273. Thanks to sebb. o Various methods of class 'org.apache.commons.io.FileUtils' incorrectly suppress 'java.io.IOException' Issue: IO-298. Thanks to Christian Schulte. Changes: o ReaderInputStream optimization: more efficient reading of small chunks of data Issue: IO-296. Thanks to Oleg Kalnichevski. Compatibility with 2.1 and 1.4: Binary compatible: Yes Source compatible: Yes Semantic compatible: Yes. Check the bug fixes section for semantic bug fixes Commons IO 2.2 requires a minimum of JDK 1.5. Commons IO 1.4 requires a minimum of JDK 1.3. ============================================================================== Apache Commons IO Version 2.1 ============================================================================== New features: o Use standard Maven directory layout Issue: IO-285. Thanks to ggregory. o Add IOUtils API toString for URL and URI to get contents Issue: IO-284. Thanks to ggregory. o Add API FileUtils.copyFile(File input, OutputStream output) Issue: IO-282. Thanks to ggregory. o FileAlterationObserver has no getter for FileFilter Issue: IO-262. o Add FileUtils.getFile API with varargs parameter Issue: IO-261. o Add new APPEND parameter for writing string into files Issue: IO-182. o Add new read method "toByteArray" to handle InputStream with known size. Issue: IO-251. Thanks to Marco Albini. Fixed Bugs: o Dubious use of mkdirs() return code Issue: IO-280. Thanks to sebb. o ReaderInputStream enters infinite loop when it encounters an unmappable character Issue: IO-277. o FileUtils.moveFile() JavaDoc should specify FileExistsException thrown Issue: IO-264. o ClassLoaderObjectInputStream does not handle Proxy classes Issue: IO-260. o Tailer returning partial lines when reaching EOF before EOL Issue: IO-274. Thanks to Frank Grimes. o FileUtils.copyFile() throws IOException when copying large files to a shared directory (on Windows) Issue: IO-266. Thanks to Igor Smereka. o FileSystemUtils.freeSpaceKb throws exception for Windows volumes with no visible files. Improve coverage by also looking for hidden files. Issue: IO-263. Thanks to Gil Adam. Changes: o FileAlterationMonitor.stop(boolean allowIntervalToFinish) Issue: IO-259. ============================================================================== Apache Commons IO Package 2.0.1 ============================================================================== Compatibility with 2.0 and 1.4 ------------------------------ Binary compatible - Yes Source compatible - Yes Semantic compatible - Yes Check the bug fixes section for semantic bug fixes Commons IO 2.0.1 requires a minimum of JDK 1.5 (Commons IO 1.4 had a minimum of JDK 1.3) Enhancements from 2.0 --------------------- * [IO-256] - Provide thread factory for FileAlternationMonitor Bug fixes from 2.0 ------------------ * [IO-257] - BOMInputStream.read(byte[]) can return 0 which it should not * [IO-258] - XmlStreamReader consumes the stream during encoding detection ============================================================================== Apache Commons IO Package 2.0 ============================================================================== Compatibility with 1.4 ---------------------- Binary compatible - Yes Source compatible - Yes Semantic compatible - Yes Check the bug fixes section for semantic bug fixes Commons IO 2.0 requires a minimum of JDK 1.5 (Commons IO 1.4 had a minimum of JDK 1.3) Deprecations from 1.4 --------------------- - IOUtils - write(StringBuffer, Writer) in favour of write(CharSequence, Writer) - write(StringBuffer, OutputStream) in favour of write(CharSequence, OutputStream) - write(StringBuffer, OutputStream, String) in favour of write(CharSequence, OutputStream, String) - FileFilterUtils - andFileFilter(IOFileFilter, IOFileFilter) in favour of and(IOFileFilter...) - orFileFilter(IOFileFilter, IOFileFilter) in favour of or(IOFileFilter...) Enhancements from 1.4 --------------------- * [IO-140] Move minimum Java requirement from JDK 1.3 to JDK 1.5 - use Generics - add new CharSequence write() flavour methods to IOUtils and FileUtils - replace StringBuffer with StringBuilder, where appropriate - add new Reader/Writer methods to ProxyReader and ProxyWriter - Annotate with @Override and @Deprecated * [IO-178] New BOMInputStream and ByteOrderMark implementations - to detect and optionally exclude an initial Byte Order mark (BOM) * [IO-197] New BoundedInputStream (copied from from Apache JackRabbit) * [IO-193] New Broken Input and Output streams * [IO-132] New File Listener/Monitor facility * [IO-158] New ReaderInputStream and WriterOutputStream implementations * [IO-139] New StringBuilder Writer implementation * [IO-192] New Tagged Input and Output streams * [IO-177] New Tailer class - simple implementation of the Unix "tail -f" functionality * [IO-162] New XML Stream Reader/Writer implementations (from ROME via plexus-utils) * [IO-142] Comparators - add facility to sort file lists/arrays * [IO-186] Comparators - new Composite and Directory File Comparator implementations * [IO-176] DirectoryWalker - add filterDirectoryContents() callback method for filtering directory contents * [IO-210] FileFilter - new Magic Number FileFilter * [IO-221] FileFilterUtils - add methods for suffix and prefix filters which take an IOCase object * [IO-232] FileFilterUtils - add method for name filters which take an IOCase object * [IO-229] FileFilterUtils - add varargs and() and or() methods * [IO-198] FileFilterUtils - add ability to apply file filters to collections and arrays * [IO-156] FilenameUtils - add normalize() and normalizeNoEndSeparator() methods which allow the separator character to be specified * [IO-194] FileSystemUtils - add freeSpaceKb() method with no input arguments * [IO-185] FileSystemUtils - add freeSpaceKb() methods that take a timeout parameter - fixes freeSpaceWindows() blocks * [IO-155] FileUtils - use NIO to copy files * [IO-168] FileUtils - add new isSymlink() method * [IO-219] FileUtils - throw FileExistsException when moving a file or directory if the destination already exists * [IO-234] FileUtils - add Methods for retrieving System User/Temp directories/paths * [IO-208] FileUtils - add timeout (connection and read) support for copyURLToFile() method * [IO-238] FileUtils - add sizeOf(File) method * [IO-181] LineIterator now implements Iterable * [IO-224] IOUtils - add closeQuietly(Closeable) and closeQuietly(Socket) methods * [IO-203] IOUtils - add skipFully() method for InputStreams * [IO-137] IOUtils and ByteArrayOutputStream - add toBufferedInputStream() method to avoid unnecessary array allocation/copy * [IO-195] Proxy streams/Reader/Writer - provide exception handling methods * [IO-211] Proxy Input/Output streams - add pre/post processing support * [IO-242] Proxy Reader/Writer - add pre/post processing support Bug fixes from 1.4 ------------------ * [IO-214] ByteArrayOutputStream - fix inconsistent synchronization of fields * [IO-201] Counting Input/Output streams - fix inconsistent synchronization * [IO-159] FileCleaningTracker - fix remove() never returns null * [IO-220] FileCleaningTracker - fix Vector performs badly under load * [IO-167] FilenameUtils - fix case-insensitive string handling in FilenameUtils and FilesystemUtils * [IO-179] FilenameUtils - fix StringIndexOutOfBounds exception in getPathNoEndSeparator() * [IO-248] FilenameUtils - fix getFullPathNoEndSeparator() returns empty while path is a one level directory * [IO-246] FilenameUtils - fix wildcardMatch gives incorrect results * [IO-187] FileSystemUtils - fix freeSpaceKb() doesn't work with relative paths on Linux * [IO-160] FileSystemUtils - fix freeSpace() fails on solaris * [IO-209] FileSystemUtils - fix freeSpaceKb() fails to return correct size for a windows mount point * [IO-163] FileUtils - fix toURLs() using deprecated method of conversion to URL * [IO-168] FileUtils - fix Symbolic links followed when deleting directory * [IO-231] FileUtils - fix wrong exception message generated in isFileNewer() method * [IO-207] FileUtils - fix race condition in forceMkdir() method * [IO-217] FileUtils - fix copyDirectoryToDirectory() makes infinite loops * [IO-166] FileUtils - fix URL decoding in toFile(URL) * [IO-190] FileUtils - fix copyDirectory not preserving lastmodified date on sub-directories * [IO-240] FileFilterUtils - ensure cvsFilter and svnFilter are only created once. * [IO-175] IOUtils - fix copyFile() issues with very large files * [IO-191] Improvements from static analysis * [IO-216] LockableFileWriter - delete files quietly when an exception is thrown during initialization * [IO-243] SwappedDataInputStream - fix readBoolean is inverted * [IO-235] Tests - remove unused YellOnFlushAndCloseOutputStream from CopyUtilsTest * [IO-161] Tests - fix FileCleaningTrackerTestCase hanging Documentation changes from 1.4 ------------------------------ * [IO-183 FilenameUtils.getExtension() method documentation improvements * [IO-226 FileUtils.byteCountToDisplaySize() documentation corrections * [IO-205 FileUtils.forceMkdir() documentation improvements * [IO-215 FileUtils copy file/directory improve documentation regarding preserving the last modified date * [IO-189 HexDump.dump() method documentation improvements * [IO-171 IOCase document that it assumes there are only two OSes: Windows and Unix * [IO-223 IOUtils.copy() documentation corrections * [IO-247 IOUtils.closeQuietly() improve documentation with examples * [IO-202 NotFileFilter documentation corrections * [IO-206 ProxyInputStream - fix misleading parameter names * [IO-212 ProxyInputStream.skip() documentation corrections ============================================================================== Apache Commons IO Version 1.4 ============================================================================== Compatibility with 1.3.2 ------------------------ Binary compatible - Yes Source compatible - Yes Semantic compatible - Yes Check the bug fixes section for semantic bug fixes Commons IO 1.4 introduces four new implementations which depend on JDK 1.4 features (CharSequenceReader, FileWriterWithEncoding, IOExceptionWithCause and RegexFileFilter). It has been built with the JDK source and target options set to JDK 1.3 and, except for those implementations, can be used with JDK 1.3 (see IO IO-127). Deprecations from 1.3.2 ----------------------- - FileCleaner deprecated in favour of FileCleaningTracker [see IO-116] Bug fixes from 1.3.2 -------------------- - FileUtils - forceDelete of orphaned Softlinks does not work [IO-147] - Infinite loop on FileUtils.copyDirectory when the destination directory is within the source directory [IO-141] - Add a copyDirectory() method that makes use of FileFilter [IO-105] - Add moveDirectory() and moveFile() methods [IO-77] - HexDump - HexDump's use of static StringBuffers isn't thread-safe [IO-136] Enhancements from 1.3.2 ----------------------- - FileUtils - Add a deleteQuietly method [IO-135] - FilenameUtils - Add file name extension separator constants[IO-149] - IOExceptionWithCause [IO-148] - Add a new IOException implementation with constructors which take a cause - TeeInputStream [IO-129] - Add new Tee input stream implementation - FileWriterWithEncoding [IO-153] - Add new File Writer implementation that accepts an encoding - CharSequenceReader [IO-138] - Add new Reader implementation that handles any CharSequence (String, StringBuffer, StringBuilder or CharBuffer) - ThesholdingOuputStream [IO-121] - Add a reset() method which sets the count of the bytes written back to zero. - DeferredFileOutputStream [IO-130] - Add support for temporary files - ByteArrayOutputStream - Add a new write(InputStream) method [IO-152] - New Closed Input/Output stream implementations [IO-122] - AutoCloseInputStream - automatically closes and discards the underlying input stream - ClosedInputStream - returns -1 for any read attempts - ClosedOutputStream - throws an IOException for any write attempts - CloseShieldInputStream - prevents the underlying input stream from being closed. - CloseShieldOutputStream - prevents the underlying output stream from being closed. - Add Singleton Constants to several stream classes [IO-143] - PrefixFileFilter [IO-126] - Add faciltiy to specify case sensitivity on prefix matching - SuffixFileFilter [IO-126] - Add faciltiy to specify case sensitivity on suffix matching - RegexFileFilter [IO-74] - Add new regular expression file filter implementation - Make IOFileFilter implementations Serializable [IO-131] - Improve IOFileFilter toString() methods [IO-120] - Make fields final so classes are immutable/threadsafe [IO-133] - changes to Age, Delegate, Name, Not, Prefix, Regex, Size, Suffix and Wildcard IOFileFilter implementations. - IOCase - Add a compare method to IOCase [IO-144] - Add a package of java.util.Comparator implementations for files [IO-145] - DefaultFileComparator - compare files using the default File.compareTo(File) method. - ExtensionFileComparator - compares files using file name extensions. - LastModifiedFileComparator - compares files using the last modified date/time. - NameFileComparator - compares files using file names. - PathFileComparator - compares files using file paths. - SizeFileComparator - compares files using file sizes. ============================================================================== Apache Commons IO Version 1.3.2 ============================================================================== Compatibility with 1.3.1 ---------------------- Binary compatible - Yes Source compatible - Yes Semantic compatible - Yes Compatibility with 1.3 ---------------------- Binary compatible - No See [IO-113] Source compatible - No See [IO-113] Semantic compatible - Yes Enhancements since 1.3.1 ------------------------ - Created the FileCleaningTracker, basically a non-static version of the FileCleaner, which can be controlled by the user. [IO-116] - The FileCleaner is deprecated. Bug fixes from 1.3.1 -------------------- - Some tests, which are implicitly assuming a Unix-like file system, are now skipped on Windows. [IO-115] - EndianUtils - Both readSwappedUnsignedInteger(...) methods could return negative numbers due to int/long casting. [IO-117] Bug fixes from 1.3 ------------------ - FileUtils - NPE in openOutputStream(File) when file has no parent in path [IO-112] - readFileToString(File) is not static [IO-113] ============================================================================== Apache Commons IO Version 1.3.1 ============================================================================== Compatibility with 1.3 ---------------------- Binary compatible - No See [IO-113] Source compatible - No See [IO-113] Semantic compatible - Yes Bug fixes from 1.3 ------------------ - FileUtils - NPE in openOutputStream(File) when file has no parent in path [IO-112] - readFileToString(File) is not static [IO-113] ============================================================================== Apache Commons IO Version 1.3 ============================================================================== Compatibility with 1.2 ---------------------- Binary compatible - Yes Source compatible - Yes Semantic compatible - Yes Check the bug fixes section for semantic bug fixes Deprecations from 1.2 --------------------- - WildcardFilter deprecated, replaced by WildcardFileFilter - old class only accepted files, thus had a confusing dual purpose - FileSystemUtils.freeSpace deprecated, replaced by freeSpaceKb - freeSpace returns a result that varies by operating system and thus isn't that useful - freeSpaceKb returns much better and more consistent results - freeSpaceKb existed in v1.2, so this is a gentle cutover Bug fixes from 1.2 ------------------ - LineIterator now implements Iterator - It was always supposed to... - FileSystemUtils.freeSpace/freeSpaceKb [IO-83] - These should now work on AIX and HP-UX - FileSystemUtils.freeSpace/freeSpaceKb [IO-90] - Avoid infinite looping in Windows - Catch more errors with nice messages - FileSystemUtils.freeSpace [IO-91] - This is now documented not to work on SunOS 5 - FileSystemUtils [IO-93] - Fixed resource leak leading to 'Too many open files' error - Previously did not destroy Process instances (as JDK Javadoc is so poor) - http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4801027 - FileUtils.touch [IO-100] - The touch method previously gave no indication when the file could not be touched successfully (such as due to access restrictions) - it now throws an IOException if the last modified date cannot be changed - FileCleaner - This now handles the situation where an error occurs when deleting the file - IOUtils.copy [IO-84] - Copy methods could return inaccurate byte/char count for large streams - The copy(InputStream, OutputStream) method now returns -1 if the count is greater than an int - The copy(Reader, Writer) method now throws now returns -1 if the count is greater than an int - Added a new copyLarge(InputStream, OutputStream) method that returns a long - Added a new copyLarge(Reader, Writer) method that returns a long - CountingInputStream/CountingOutputStream [IO-84] - Methods were declared as int thus the count was innacurate for large streams - new long based methods getByteCount()/resetByteCount() added - existing methods changed to throw an exception if the count is greater than an int - FileBasedTestCase - Fixed bug in compare content methods identified by GNU classpath - EndianUtils.writeSwappedLong(byte[], int) [IO-101] - An int overrun in the bit shifting when it should have been a long - EndianUtils.writeSwappedLong(InputStream) [IO-102] - The return of input.read(byte[]) was not being checked to ensure all 8 bytes were read Enhancements from 1.2 --------------------- - DirectoryWalker [IO-86] - New class designed for subclassing to walk through a set of files. DirectoryWalker provides the walk of the directories, filtering of directories and files, and cancellation support. The subclass must provide the specific behaviour, such as text searching or image processing. - IOCase - New class/enumeration for case-sensitivity control - FilenameUtils - New methods to handle case-sensitivity - wildcardMatch - new method that has IOCase as a parameter - equals - new method that has IOCase as a parameter - FileUtils [IO-108] - new default encoding methods for: - readFileToString(File) - readLines(File) - lineIterator(File) - writeStringToFile(File, String) - writeLines(File, Collection) - writeLines(File, Collection, String) - FileUtils.openOutputStream [IO-107] - new method to open a FileOutputStream, creating parent directories if required - FileUtils.touch - FileUtils.copyURLToFile - FileUtils.writeStringToFile - FileUtils.writeByteArrayToFile - FileUtils.writeLines - enhanced to create parent directories if required - FileUtils.openInputStream [IO-107] - new method to open a FileInputStream, providing better error messages than the JDK - FileUtils.isFileOlder - new methods to check if a file is older (i.e. isFileOlder()) - counterparts to the existing isFileNewer() methods. - FileUtils.checksum, FileUtils.checksumCRC32 - new methods to create a checksum of a file - FileUtils.copyFileToDirectory [IO-104] - new variant that optionally retains the file date - FileDeleteStrategy - FileCleaner [IO-56,IO-70] - FileDeleteStrategy is a strategy for handling file deletion - This can be used as a calback in FileCleaner - Together these allow FileCleaner to do a forceDelete to kill directories - FileCleaner.exitWhenFinished [IO-99] - A new method that allows the internal cleaner thread to be cleanly terminated - WildcardFileFilter - Replacement for WildcardFilter - Accepts both files and directories - Ability to control case-sensitivity - NameFileFilter - Ability to control case-sensitivity - FileFileFilter - New IOFileFilter implementation - Accepts files where File.isFile() is true - In other words it filters out directories - Singleton instance provided (FILE) - CanReadFileFilter - New IOFileFilter implementation - Accepts files where File.canRead() is true - Singleton instances provided (CAN_READ/CANNOT_READ/READ_ONLY) - CanWriteFileFilter - New IOFileFilter implementation - Accepts files where File.canWrite() is true - Singleton instances provided (CAN_WRITE/CANNOT_WRITE) - HiddenFileFilter - New IOFileFilter implementation - Accepts files where File.isHidden() is true - Singleton instances provided (HIDDEN/VISIBLE) - EmptyFileFilter - New IOFileFilter implementation - Accepts files or directories that are empty - Singleton instances provided (EMPTY/NOT_EMPTY) - TrueFileFilter/FalseFileFilter/DirectoryFileFilter - New singleton instance constants (TRUE/FALSE/DIRECTORY) - The new constants are more JDK 1.5 friendly with regards to static imports (whereas if everything uses INSTANCE, then they just clash) - The old INSTANCE constants are still present and have not been deprecated - FileFilterUtils.sizeRangeFileFilter - new sizeRangeFileFilter(long minimumSize, long maximumSize) method which creates a filter that accepts files within the specified size range. - FileFilterUtils.makeDirectoryOnly/makeFileOnly - two new methods that decorate a file filter to make it apply to directories only or files only - NullWriter - New writer that acts as a sink for all data, as per /dev/null - NullInputStream - New input stream that emulates a stream of a specified size - NullReader - New reader that emulates a reader of a specified size - ByteArrayOutputStream [IO-97] - Performance enhancements ============================================================================== Apache Commons IO Version 1.2 ============================================================================== Compatibility with 1.1 ---------------------- Binary compatible - Yes Source compatible - Yes Semantic compatible - Yes Deprecations from 1.1 --------------------- Bug fixes from 1.1 ------------------ - FileSystemUtils.freeSpace(drive) Fix to allow Windows based command to function in French locale - FileUtils.read* Increase certainty that files are closed in case of error - LockableFileWriter Locking mechanism was broken and only provided limited protection [38942] File deletion and locking in case of constructor error was broken Enhancements from 1.1 --------------------- - AgeFileFilter/SizeFileFilter New file filters that compares against the age and size of the file - FileSystemUtils.freeSpaceKb(drive) New method that unifies result to be in kilobytes [38574] - FileUtils.contentEquals(File,File) Performance improved by adding length and file location checking - FileUtils.iterateFiles Two new method to provide direct access to iterators over files - FileUtils.lineIterator IOUtils.lineIterator New methods to provide an iterator over the lines in a file [38083] - FileUtils.copyDirectoryToDirectory New method to copy a directory to within another directory [36315] ============================================================================== Apache Commons IO Version 1.1 ============================================================================== Incompatible changes from 1.0 ----------------------------- Binary compatible - Yes Source compatible - Yes Semantic compatible - Yes, except: - FileUtils.writeStringToFile() A null encoding previously used 'ISO-8859-1', now it uses the platform default Generally this will make no difference - LockableFileWriter Improved validation and now create directories if necesssary plus these bug fixes may affect you semantically: - FileUtils.touch() (Bug fix 29821) Now creates the file if it did not previously exist - FileUtils.toFile(URL) (Bug fix 32575) Now handles escape syntax such as %20 - FileUtils.sizeOfDirectory() (Bug fix 36801) May now return a size of 0 if the directory is security restricted Deprecations from 1.0 --------------------- - CopyUtils has been deprecated. Its methods have been moved to IOUtils. The new IOUtils methods handle nulls better, and have clearer names. - IOUtils.toByteArray(String) - Use {@link String#getBytes()} - IOUtils.toString(byte[]) - Use {@link String#String(byte[])} - IOUtils.toString(byte[],String) - Use {@link String#String(byte[],String)} Bug fixes from 1.0 ------------------ - FileUtils - touch() [29821] Now creates the file if it did not previously exist - FileUtils - toFile(URL) [32575] Now handles escape syntax such as %20 - FileFilterUtils - makeCVSAware(IOFileFilter) [33023] Fixed bug that caused method to be completely broken - CountingInputStream [33336] Fixed bug that caused the count to reduce by one at the end of the stream - CountingInputStream - skip(long) [34311] Bytes from calls to this method were not previously counted - NullOutputStream [33481] Remove unecessary synchronization - AbstractFileFilter - accept(File, String) [30992] Fixed broken implementation - FileUtils [36801] Previously threw NPE when listing files in a security restricted directory Now throw IOException with a better message - FileUtils - writeStringToFile() Null encoding now correctly uses the platform default Enhancements from 1.0 --------------------- - FilenameUtils - new class [33303,29351] A static utility class for working with filenames Seeks to ease the pain of developing on Windows and deploying on Unix - FileSystemUtils - new class [32982,36325] A static utility class for working with file systems Provides one method at present, to get the free space on the filing system - IOUtils - new public constants Constants for directory and line separators on Windows and Unix - IOUtils - toByteArray(Reader,encoding) Handles encodings when reading to a byte array - IOUtils - toCharArray(InputStream) [28979] - toCharArray(InputStream,encoding) - toCharArray(Reader) Reads a stream/reader into a charatcter array - IOUtils - readLines(InputStream) [36214] - readLines(InputStream,encoding) - readLines(Reader) Reads a stream/reader line by line into a List of Strings - IOUtils - toInputStream(String) [32958] - toInputStream(String,encoding) Creates an input stream that uses the string as a source of data - IOUtils - writeLines(Collection,lineEnding,OutputStream) [36214] - writeLines(Collection,lineEnding,OutputStream,encoding) - writeLines(Collection,lineEnding,Writer) Writes a collection to a stream/writer line by line - IOUtils - write(...) Write data to a stream/writer (moved from CopyUtils with better null handling) - IOUtils - copy(...) Copy data between streams (moved from CopyUtils with better null handling) - IOUtils - contentEquals(Reader,Reader) Method to compare the contents of two readers - FileUtils - toFiles(URL[]) Converts an array of URLs to an array of Files - FileUtils - copyDirectory() [32944] New methods to copy a directory - FileUtils - readFileToByteArray(File) Reads an entire file into a byte array - FileUtils - writeByteArrayToFile(File,byte[]) Writes a byte array to a file - FileUtils - readLines(File,encoding) [36214] Reads a file line by line into a List of Strings - FileUtils - writeLines(File,encoding,List) writeLines(File,encoding,List,lineEnding) Writes a collection to a file line by line - FileUtils - EMPTY_FILE_ARRAY Constant for an empty array of File objects - ConditionalFileFilter - new interface [30705] Defines the behaviour of list based filters - AndFileFilter, OrFileFilter [30705] Now support a list of filters to and/or - WildcardFilter [31115] New filter that can match using wildcard file names - FileFilterUtils - makeSVNAware(IOFileFilter) New method, like makeCVSAware, that ignores Subversion source control directories - ClassLoaderObjectInputStream An ObjectInputStream that supports a ClassLoader - CountingInputStream,CountingOutputStream - resetCount() [28976] Adds the ability to reset the count part way through reading/writing the stream - DeferredFileOutputStream - writeTo(OutputStream) [34173] New method to allow current contents to be written to a stream - DeferredFileOutputStream [34142] Performance optimizations avoiding double buffering - LockableFileWriter - encoding support [36825] Add support for character encodings to LockableFileWriter Improve the validation Create directories if necesssary - IOUtils and EndianUtils are no longer final [28978] Allows developers to have subclasses if desired ============================================================================== Feedback ============================================================================== Open source works best when you give feedback: http://commons.apache.org/io/ Please direct all bug reports to JIRA http://issues.apache.org/jira/browse/IO Or subscribe to the commons-user mailing list (prefix emails by [io]) http://commons.apache.org/mail-lists.html The Commons-IO Team libcommons-io-java-2.4.orig/src/0000755000175000017500000000000011765740036016134 5ustar ebourgebourglibcommons-io-java-2.4.orig/src/changes/0000755000175000017500000000000012125050425017527 5ustar ebourgebourglibcommons-io-java-2.4.orig/src/changes/release-notes.vm0000644000175000017500000011204112125050425022640 0ustar ebourgebourg## Licensed to the Apache Software Foundation (ASF) under one ## or more contributor license agreements. See the NOTICE file ## distributed with this work for additional information ## regarding copyright ownership. The ASF licenses this file ## to you under the Apache License, Version 2.0 (the ## "License"); you may not use this file except in compliance ## with the License. You may obtain a copy of the License at ## ## http://www.apache.org/licenses/LICENSE-2.0 ## ## Unless required by applicable law or agreed to in writing, ## software distributed under the License is distributed on an ## "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ## KIND, either express or implied. See the License for the ## specific language governing permissions and limitations ## under the License. Apache Commons IO Version ${version} Release Notes INTRODUCTION: Commons IO is a package of Java utility classes like java.io. Classes in this package are considered to be so standard and of such high reuse as to justify existence in java.io. $introduction.replaceAll("(? Release Notes Yottabyte (YB) incorrectly defined in FileUtils. Tailer locks file from deletion/rename on Windows. Tailer erroneously considers file as new. Tailer#readLines - incorrect CR handling. FileUtils.toURLs throws NPE for null parameter; document the behavior. Export OSGi packages at version 1.x in addition to 2.x. Add XmlStreamReader support for UTF-32. BOMInputStream wrongly detects UTF-32LE_BOM files as UTF-16LE_BOM files in method getBOM(). Improve tailer's reading performance. Improve Tailer performance with buffered reads (see IO-332). FileUtils.writeLines uses unbuffered IO. Add byteCountToDisplaySize(BigInteger). Add new FileUtils.sizeOf[Directory] APIs to return BigInteger. Add IOUtils.toByteArray methods to work with URL and URI. Add missing Charset sister APIs to method that take a String charset name. FileUtils.sizeOfDirectory follows symbolic links. Add and use class Charsets. ByteOrderMark UTF_32LE is incorrect. Add Charset sister APIs to method that take a String charset name. Add IOUTils.toBufferedReader(Reader) Allow applications to provide buffer (or size) for copyLarge methods. IOUtils.read(InputStream/Reader) ignores the offset parameter CharSequenceInputStream(CharSequence s, Charset charset, int bufferSize) ignores bufferSize New copyLarge() method in IOUtils that takes additional offset, length arguments FileUtils.moveDirectoryToDirectory removes source directory if destination is a sub-directory ReaderInputStream#read(byte[] b, int off, int len) should check for valid parameters Use terabyte (TB), petabyte (PB) and exabyte (EB) in FileUtils.byteCountToDisplaySize(long size) ReaderInputStream#read(byte[] b, int off, int len) should always return 0 for length == 0 FileUtils.listFiles() doesn't return directories "FileUtils#deleteDirectoryOnExit(File)" does not work BoundedInputStream.read() treats max differently from BoundedInputStream.read(byte[]...) CharSequenceInputStream to efficiently stream content of a CharSequence ReaderInputStream optimization: more efficient reading of small chunks of data Various methods of class 'org.apache.commons.io.FileUtils' incorrectly suppress 'java.io.IOException' The second constructor of Tailer class does not pass 'delay' to the third one TeeOutputStream does not call branch.close() when main.close() throws an exception ArrayIndexOutOfBoundsException in BOMInputStream when reading a file without BOM multiple times Add IOUtils.closeQuietly(Selector) necessary IOUtils.closeQuietly() should take a ServerSocket as a parameter Add read/readFully methods to IOUtils Supply a ReversedLinesFileReader Add new function FileUtils.directoryContains. FileUtils.contentEquals and IOUtils.contentEquals - Add option to ignore "line endings" Added contentEqualsIgnoreEOL methods to both classes Use standard Maven directory layout Add IOUtils API toString for URL and URI to get contents Add API FileUtils.copyFile(File input, OutputStream output) Dubious use of mkdirs() return code ReaderInputStream enters infinite loop when it encounters an unmappable character FileUtils.moveFile() JavaDoc should specify FileExistsException thrown FileAlterationObserver has no getter for FileFilter Add FileUtils.getFile API with varargs parameter ClassLoaderObjectInputStream does not handle Proxy classes FileAlterationMonitor.stop(boolean allowIntervalToFinish) Add new APPEND parameter for writing string into files Tailer returning partial lines when reaching EOF before EOL FileUtils.copyFile() throws IOException when copying large files to a shared directory (on Windows) FileSystemUtils.freeSpaceKb throws exception for Windows volumes with no visible files. Improve coverage by also looking for hidden files. Add new read method "toByteArray" to handle InputStream with known size. TODO: Convert RELEASE-NOTES.txt from 2.0.1? TODO: Convert RELEASE-NOTES.txt from 2.0? TODO: Convert RELEASE-NOTES.txt from 1.4? Some tests, which are implicitly assuming a Unix-like file system, are now skipped on Windows. Created the FileCleaningTracker, basically a non-static version of the FileCleaner, which can be controlled by the user. EndianUtils - both readSwappedUnsignedInteger(...) methods could return negative numbers due to int/long casting. libcommons-io-java-2.4.orig/src/site/0000755000175000017500000000000012125050425017063 5ustar ebourgebourglibcommons-io-java-2.4.orig/src/site/xdoc/0000755000175000017500000000000012125050425020020 5ustar ebourgebourglibcommons-io-java-2.4.orig/src/site/xdoc/issue-tracking.xml0000644000175000017500000001317512125050425023501 0ustar ebourgebourg Commons IO Issue tracking Commons Documentation Team

Commons IO uses ASF JIRA for tracking issues. See the Commons IO JIRA project page.

To use JIRA you may need to create an account (if you have previously created/updated Commons issues using Bugzilla an account will have been automatically created and you can use the Forgot Password page to get a new password).

If you would like to report a bug, or raise an enhancement request with Commons IO please do the following:

  1. Search existing open bugs. If you find your issue listed then please add a comment with your details.
  2. Search the mailing list archive(s). You may find your issue or idea has already been discussed.
  3. Decide if your issue is a bug or an enhancement.
  4. Submit either a bug report or enhancement request.

Please also remember these points:

  • the more information you provide, the better we can help you
  • test cases are vital, particularly for any proposed enhancements
  • the developers of Commons IO are all unpaid volunteers

For more information on subversion and creating patches see the Apache Contributors Guide.

You may also find these links useful:

libcommons-io-java-2.4.orig/src/site/xdoc/upgradeto1_3_2.xml0000644000175000017500000000466312125050425023271 0ustar ebourgebourg Upgrade from 1.3, or 1.3.1, to 1.3.2 Commons Documentation Team

These are the release notes and advice for upgrading Commons-IO from version 1.3, or 1.3.1, to version 1.3.2. Commons IO is a package of Java utility classes for java.io's hierarchy. Classes in this package are considered to be so standard and of such high reuse as to justify existence in java.io. Commons IO contains utility classes, stream implementations, file filters, and endian transformation classes. Compatibility with 1.3.1 ------------------------ Binary compatible - Yes Source compatible - Yes Semantic compatible - Yes Check the bug fixes section for semantic bug fixes Compatibility with 1.3 ---------------------- Binary compatible - No See [IO-113] Source compatible - No See [IO-113] Semantic compatible - Yes Enhancements since 1.3.1 ------------------------ - Created the FileCleaningTracker, basically a non-static version of the FileCleaner, which can be controlled by the user. [IO-116] - The FileCleaner is deprecated. (For reasons of compatibility, the deprecation warnings are hidden within the 1.3 branch. They'll be visible, as of version 1.4.) Bug fixes from 1.3.1 -------------------- - Some tests, which are implicitly assuming a Unix-like file system, are now skipped on Windows. [IO-115] Bug fixes from 1.3 ------------------ - FileUtils - NPE in openOutputStream(File) when file has no parent in path [IO-112] - readFileToString(File) is not static [IO-113]

libcommons-io-java-2.4.orig/src/site/xdoc/upgradeto2_0_1.xml0000644000175000017500000000400512125050425023254 0ustar ebourgebourg Upgrade from 2.0 to 2.0.1 Commons Documentation Team

These are the release notes and advice for upgrading Commons-IO from version 2.0 to version 2.0.1 Commons IO is a package of Java utility classes for java.io's hierarchy. Classes in this package are considered to be so standard and of such high reuse as to justify existence in java.io. Commons IO contains utility classes, stream implementations, file filters, file comparators and endian transformation classes. Compatibility with 2.0 and 1.4 ------------------------------ Binary compatible - Yes Source compatible - Yes Semantic compatible - Yes Check the bug fixes section for semantic bug fixes Commons IO 2.0.1 requires a minimum of JDK 1.5 (Commons IO 1.4 had a minimum of JDK 1.3) Enhancements from 2.0 --------------------- * [IO-256] - Provide thread factory for FileAlternationMonitor Bug fixes from 2.0 ------------------ * [IO-257] - BOMInputStream.read(byte[]) can return 0 which it should not * [IO-258] - XmlStreamReader consumes the stream during encoding detection

libcommons-io-java-2.4.orig/src/site/xdoc/upgradeto1_1.xml0000644000175000017500000001545512125050425023047 0ustar ebourgebourg Upgrade from 1.0 to 1.1 Commons Documentation Team

These are the release notes and advice for upgrading Commons-IO from version 1.0 to version 1.1. Commons IO is a package of Java utility classes for java.io's hierarchy. Classes in this package are considered to be so standard and of such high reuse as to justify existence in java.io. Commons IO contains utility classes, stream implementations, file filters, and endian transformation classes. Incompatible changes from 1.0 ----------------------------- Binary compatible - Yes Source compatible - Yes Semantic compatible - Yes, except: - FileUtils.writeStringToFile() A null encoding previously used 'ISO-8859-1', now it uses the platform default Generally this will make no difference - LockableFileWriter Improved validation and now create directories if necesssary plus these bug fixes may affect you semantically: - FileUtils.touch() (Bug fix 29821) Now creates the file if it did not previously exist - FileUtils.toFile(URL) (Bug fix 32575) Now handles escape syntax such as %20 - FileUtils.sizeOfDirectory() (Bug fix 36801) May now return a size of 0 if the directory is security restricted Deprecations from 1.0 --------------------- - CopyUtils has been deprecated. Its methods have been moved to IOUtils. The new IOUtils methods handle nulls better, and have clearer names. - IOUtils.toByteArray(String) - Use {@link String#getBytes()} - IOUtils.toString(byte[]) - Use {@link String#String(byte[])} - IOUtils.toString(byte[],String) - Use {@link String#String(byte[],String)} Bug fixes from 1.0 ------------------ - FileUtils - touch() [29821] Now creates the file if it did not previously exist - FileUtils - toFile(URL) [32575] Now handles escape syntax such as %20 - FileFilterUtils - makeCVSAware(IOFileFilter) [33023] Fixed bug that caused method to be completely broken - CountingInputStream [33336] Fixed bug that caused the count to reduce by one at the end of the stream - CountingInputStream - skip(long) [34311] Bytes from calls to this method were not previously counted - NullOutputStream [33481] Remove unecessary synchronization - AbstractFileFilter - accept(File, String) [30992] Fixed broken implementation - FileUtils [36801] Previously threw NPE when listing files in a security restricted directory Now throw IOException with a better message - FileUtils - writeStringToFile() Null encoding now correctly uses the platform default Enhancements from 1.0 --------------------- - FilenameUtils - new class [33303,29351] A static utility class for working with filenames Seeks to ease the pain of developing on Windows and deploying on Unix - FileSystemUtils - new class [32982,36325] A static utility class for working with file systems Provides one method at present, to get the free space on the filing system - IOUtils - new public constants Constants for directory and line separators on Windows and Unix - IOUtils - toByteArray(Reader,encoding) Handles encodings when reading to a byte array - IOUtils - toCharArray(InputStream) [28979] - toCharArray(InputStream,encoding) - toCharArray(Reader) Reads a stream/reader into a charatcter array - IOUtils - readLines(InputStream) [36214] - readLines(InputStream,encoding) - readLines(Reader) Reads a stream/reader line by line into a List of Strings - IOUtils - toInputStream(String) [32958] - toInputStream(String,encoding) Creates an input stream that uses the string as a source of data - IOUtils - writeLines(Collection,lineEnding,OutputStream) [36214] - writeLines(Collection,lineEnding,OutputStream,encoding) - writeLines(Collection,lineEnding,Writer) Writes a collection to a stream/writer line by line - IOUtils - write(...) Write data to a stream/writer (moved from CopyUtils with better null handling) - IOUtils - copy(...) Copy data between streams (moved from CopyUtils with better null handling) - IOUtils - contentEquals(Reader,Reader) Method to compare the contents of two readers - FileUtils - toFiles(URL[]) Converts an array of URLs to an array of Files - FileUtils - copyDirectory() [32944] New methods to copy a directory - FileUtils - readFileToByteArray(File) Reads an entire file into a byte array - FileUtils - writeByteArrayToFile(File,byte[]) Writes a byte array to a file - FileUtils - readLines(File,encoding) [36214] Reads a file line by line into a List of Strings - FileUtils - writeLines(File,encoding,List) writeLines(File,encoding,List,lineEnding) Writes a collection to a file line by line - FileUtils - EMPTY_FILE_ARRAY Constant for an empty array of File objects - ConditionalFileFilter - new interface [30705] Defines the behaviour of list based filters - AndFileFilter, OrFileFilter [30705] Now support a list of filters to and/or - WildcardFilter [31115] New filter that can match using wildcard file names - FileFilterUtils - makeSVNAware(IOFileFilter) New method, like makeCVSAware, that ignores Subversion source control directories - ClassLoaderObjectInputStream An ObjectInputStream that supports a ClassLoader - CountingInputStream,CountingOutputStream - resetCount() [28976] Adds the ability to reset the count part way through reading/writing the stream - DeferredFileOutputStream - writeTo(OutputStream) [34173] New method to allow current contents to be written to a stream - DeferredFileOutputStream [34142] Performance optimizations avoiding double buffering - LockableFileWriter - encoding support [36825] Add support for character encodings to LockableFileWriter Improve the validation Create directories if necesssary - IOUtils and EndianUtils are no longer final [28978] Allows developers to have subclasses if desired

libcommons-io-java-2.4.orig/src/site/xdoc/bestpractices.xml0000644000175000017500000001233112125050425023375 0ustar ebourgebourg Best practices Commons Documentation Team

This document presents a number of 'best practices' in the IO area.

Often, you have to deal with files and filenames. There are many things that can go wrong:

  • A class works in Unix but doesn't on Windows (or vice versa)
  • Invalid filenames due to double or missing path separators
  • UNC filenames (on Windows) don't work with my home-grown filename utility function
  • etc. etc.

These are good reasons not to work with filenames as Strings. Using java.io.File instead handles many of the above cases nicely. Thus, our best practice recommendation is to use java.io.File instead of String for filenames to avoid platform dependencies.

Version 1.1 of commons-io now includes a dedicated filename handling class - FilenameUtils. This does handle many of these filename issues, however we still recommend, wherever possible, that you use java.io.File objects.

Let's look at an example.

public static String getExtension(String filename) { int index = filename.lastIndexOf('.'); if (index == -1) { return ""; } else { return filename.substring(index + 1); } }

Easy enough? Right, but what happens if someone passes in a full path instead of only a filename? Consider the following, perfectly legal path: "C:\Temp\documentation.new\README". The method as defined above would return "new\README" - definitely not what you wanted.

Please use java.io.File for filenames instead of Strings. The functionality that the class provides is well tested. In FileUtils you will find other useful utility functions around java.io.File.

Instead of:

String tmpdir = "/var/tmp"; String tmpfile = tmpdir + System.getProperty("file.separator") + "test.tmp"; InputStream in = new java.io.FileInputStream(tmpfile);

...write:

File tmpdir = new File("/var/tmp"); File tmpfile = new File(tmpdir, "test.tmp"); InputStream in = new java.io.FileInputStream(tmpfile);

IO performance depends a lot from the buffering strategy. Usually, it's quite fast to read packets with the size of 512 or 1024 bytes because these sizes match well with the packet sizes used on harddisks in file systems or file system caches. But as soon as you have to read only a few bytes and that many times performance drops significantly.

Make sure you're properly buffering streams when reading or writing streams, especially when working with files. Just decorate your FileInputStream with a BufferedInputStream:

InputStream in = new java.io.FileInputStream(myfile); try { in = new java.io.BufferedInputStream(in); in.read(..... } finally { IOUtils.closeQuietly(in); }

Pay attention that you're not buffering an already buffered stream. Some components like XML parsers may do their own buffering so decorating the InputStream you pass to the XML parser does nothing but slowing down your code. If you use our CopyUtils or IOUtils you don't need to additionally buffer the streams you use as the code in there already buffers the copy process. Always check the Javadocs for information. Another case where buffering is unnecessary is when you write to a ByteArrayOutputStream since you're writing to memory only.

libcommons-io-java-2.4.orig/src/site/xdoc/upgradeto2_0.xml0000644000175000017500000001774212125050425023050 0ustar ebourgebourg Upgrade from 1.4 to 2.0 Commons Documentation Team

These are the release notes and advice for upgrading Commons-IO from version 1.4 to version 2.0. Commons IO is a package of Java utility classes for java.io's hierarchy. Classes in this package are considered to be so standard and of such high reuse as to justify existence in java.io. Commons IO contains utility classes, stream implementations, file filters, file comparators and endian transformation classes. Compatibility with 1.4 ---------------------- Binary compatible - Yes Source compatible - Yes Semantic compatible - Yes Check the bug fixes section for semantic bug fixes Commons IO 2.0 requires a minimum of JDK 1.5 (Commons IO 1.4 had a minimum of JDK 1.3) Deprecations from 1.4 --------------------- - IOUtils - write(StringBuffer, Writer) in favour of write(CharSequence, Writer) - write(StringBuffer, OutputStream) in favour of write(CharSequence, OutputStream) - write(StringBuffer, OutputStream, String) in favour of write(CharSequence, OutputStream, String) - FileFilterUtils - andFileFilter(IOFileFilter, IOFileFilter) in favour of and(IOFileFilter...) - orFileFilter(IOFileFilter, IOFileFilter) in favour of or(IOFileFilter...) Enhancements from 1.4 --------------------- * [IO-140] Move minimum Java requirement from JDK 1.3 to JDK 1.5 - use Generics - add new CharSequence write() flavour methods to IOUtils and FileUtils - replace StringBuffer with StringBuilder, where appropriate - add new Reader/Writer methods to ProxyReader and ProxyWriter - Annotate with @Override and @Deprecated * [IO-178] New BOMInputStream and ByteOrderMark implementations - to detect and optionally exclude an initial Byte Order mark (BOM) * [IO-197] New BoundedInputStream (copied from from Apache JackRabbit) * [IO-193] New Broken Input and Output streams * [IO-132] New File Listener/Monitor facility * [IO-158] New ReaderInputStream and WriterOutputStream implementations * [IO-139] New StringBuilder Writer implementation * [IO-192] New Tagged Input and Output streams * [IO-177] New Tailer class - simple implementation of the Unix "tail -f" functionality * [IO-162] New XML Stream Reader/Writer implementations (from ROME via plexus-utils) * [IO-142] Comparators - add facility to sort file lists/arrays * [IO-186] Comparators - new Composite and Directory File Comparator implementations * [IO-176] DirectoryWalker - add filterDirectoryContents() callback method for filtering directory contents * [IO-210] FileFilter - new Magic Number FileFilter * [IO-221] FileFilterUtils - add methods for suffix and prefix filters which take an IOCase object * [IO-232] FileFilterUtils - add method for name filters which take an IOCase object * [IO-229] FileFilterUtils - add varargs and() and or() methods * [IO-198] FileFilterUtils - add ability to apply file filters to collections and arrays * [IO-156] FilenameUtils - add normalize() and normalizeNoEndSeparator() methods which allow the separator character to be specified * [IO-194] FileSystemUtils - add freeSpaceKb() method with no input arguments * [IO-185] FileSystemUtils - add freeSpaceKb() methods that take a timeout parameter - fixes freeSpaceWindows() blocks * [IO-155] FileUtils - use NIO to copy files * [IO-168] FileUtils - add new isSymlink() method * [IO-219] FileUtils - throw FileExistsException when moving a file or directory if the destination already exists * [IO-234] FileUtils - add Methods for retrieving System User/Temp directories/paths * [IO-208] FileUtils - add timeout (connection and read) support for copyURLToFile() method * [IO-238] FileUtils - add sizeOf(File) method * [IO-181] LineIterator now implements Iterable * [IO-224] IOUtils - add closeQuietly(Closeable) and closeQuietly(Socket) methods * [IO-203] IOUtils - add skipFully() method for InputStreams * [IO-137] IOUtils and ByteArrayOutputStream - add toBufferedInputStream() method to avoid unnecessary array allocation/copy * [IO-195] Proxy streams/Reader/Writer - provide exception handling methods * [IO-211] Proxy Input/Output streams - add pre/post processing support * [IO-242] Proxy Reader/Writer - add pre/post processing support Bug fixes from 1.4 ------------------ * [IO-214] ByteArrayOutputStream - fix inconsistent synchronization of fields * [IO-201] Counting Input/Output streams - fix inconsistent synchronization * [IO-159] FileCleaningTracker - fix remove() never returns null * [IO-220] FileCleaningTracker - fix Vector performs badly under load * [IO-167] FilenameUtils - fix case-insensitive string handling in FilenameUtils and FilesystemUtils * [IO-179] FilenameUtils - fix StringIndexOutOfBounds exception in getPathNoEndSeparator() * [IO-248] FilenameUtils - fix getFullPathNoEndSeparator() returns empty while path is a one level directory * [IO-246] FilenameUtils - fix wildcardMatch gives incorrect results * [IO-187] FileSystemUtils - fix freeSpaceKb() doesn't work with relative paths on Linux * [IO-160] FileSystemUtils - fix freeSpace() fails on solaris * [IO-209] FileSystemUtils - fix freeSpaceKb() fails to return correct size for a windows mount point * [IO-163] FileUtils - fix toURLs() using deprecated method of conversion to URL * [IO-168] FileUtils - fix Symbolic links followed when deleting directory * [IO-231] FileUtils - fix wrong exception message generated in isFileNewer() method * [IO-207] FileUtils - fix race condition in forceMkdir() method * [IO-217] FileUtils - fix copyDirectoryToDirectory() makes infinite loops * [IO-166] FileUtils - fix URL decoding in toFile(URL) * [IO-190] FileUtils - fix copyDirectory not preserving lastmodified date on sub-directories * [IO-240] FileFilterUtils - ensure cvsFilter and svnFilter are only created once. * [IO-175] IOUtils - fix copyFile() issues with very large files * [IO-191] Improvements from static analysis * [IO-216] LockableFileWriter - delete files quietly when an exception is thrown during initialization * [IO-243] SwappedDataInputStream - fix readBoolean is inverted * [IO-235] Tests - remove unused YellOnFlushAndCloseOutputStream from CopyUtilsTest * [IO-161] Tests - fix FileCleaningTrackerTestCase hanging Documentation changes from 1.4 ------------------------------ * [IO-183 FilenameUtils.getExtension() method documentation improvements * [IO-226 FileUtils.byteCountToDisplaySize() documentation corrections * [IO-205 FileUtils.forceMkdir() documentation improvements * [IO-215 FileUtils copy file/directory improve documentation regarding preserving the last modified date * [IO-189 HexDump.dump() method documentation improvements * [IO-171 IOCase document that it assumes there are only two OSes: Windows and Unix * [IO-223 IOUtils.copy() documentation corrections * [IO-247 IOUtils.closeQuietly() improve documentation with examples * [IO-202 NotFileFilter documentation corrections * [IO-206 ProxyInputStream - fix misleading parameter names * [IO-212 ProxyInputStream.skip() documentation corrections

libcommons-io-java-2.4.orig/src/site/xdoc/tasks.xml0000644000175000017500000000344712125050425021677 0ustar ebourgebourg Tasks Commons Documentation Team

The following are some of the proposed ideas and tasks for commons-io:

  • A proper user guide
  • A URLUtils class that has many of the FileUtils operations, but for a URL
  • FilePoller for telling when a file changes. Look in Tomcat, or GenJava[bayard] (One implemented in bugzilla awaiting investigation)
  • A "hot folder" handler which triggers an action when a new file has been uploaded to an FTP directory, for example.
  • JoinReader/ConcatReader. One in GenJava, one submitted to Bayard
  • FormattedWriter, when it writes out values it uses Format objects to output them.
  • FixedWidthReader. Reads in files with a known width, ie) mainframe like.
libcommons-io-java-2.4.orig/src/site/xdoc/proposal.xml0000644000175000017500000000623012125050425022402 0ustar ebourgebourg Proposal Commons Documentation Team

Many software projects have a need to perform I/O in various ways, and the JDK class libraries provide a lot of functionality, but sometimes you need just a little bit more. The io package seeks to encapsulate some of the most popular i/o base classes into one easy to use package.

This proposal is to create a package of Java utility classes for various types of i/o related activity.

IO relies only on standard JDK 1.2 (or later) APIs for production deployment. It utilizes the JUnit unit testing framework for developing and executing unit tests, but this is of interest only to developers of the component. IO will be a dependency for several existing components in the open source world.

No external configuration files are utilized.

The original Java classes are splashed around various Apache subprojects. We intend to seek them out and integrate them.

The proposed package name for the new component is org.apache.commons.io.

  • CVS Repository - New directory io in the jakarta-commons CVS repository.
  • Mailing List - Discussions will take place on the general dev@commons.apache.org mailing list. To help list subscribers identify messages of interest, it is suggested that the message subject of messages about this component be prefixed with [IO].
  • Bugzilla - New component "IO" under the "Commons" product category, with appropriate version identifiers as needed.
  • Jyve FAQ - New category "commons-io" (when available).

The initial committers on the IO component shall be Scott Sanders and Nicola Ken Barozzi and Henri Yandell

libcommons-io-java-2.4.orig/src/site/xdoc/upgradeto1_4.xml0000644000175000017500000001164012125050425023042 0ustar ebourgebourg Upgrade from 1.3.2 to 1.4 Commons Documentation Team

These are the release notes and advice for upgrading Commons-IO from version 1.3.2 to version 1.4. Commons IO is a package of Java utility classes for java.io's hierarchy. Classes in this package are considered to be so standard and of such high reuse as to justify existence in java.io. Commons IO contains utility classes, stream implementations, file filters, file comparators and endian transformation classes. Compatibility with 1.3.2 ------------------------ Binary compatible - Yes Source compatible - Yes Semantic compatible - Yes Check the bug fixes section for semantic bug fixes Commons IO 1.4 introduces four new implementations which depend on JDK 1.4 features (CharSequenceReader, FileWriterWithEncoding, IOExceptionWithCause and RegexFileFilter). It has been built with the JDK source and target options set to JDK 1.3 and, except for those implementations, can be used with JDK 1.3 (see IO IO-127). Deprecations from 1.3.2 ----------------------- - FileCleaner deprecated in favour of FileCleaningTracker [see IO-116] Bug fixes from 1.3.2 -------------------- - FileUtils - forceDelete of orphaned Softlinks does not work [IO-147] - Infinite loop on FileUtils.copyDirectory when the destination directory is within the source directory [IO-141] - HexDump - HexDump's use of static StringBuffers isn't thread-safe [IO-136] Enhancements from 1.3.2 ----------------------- - FileUtils - Add a deleteQuietly method [IO-135] - Add a copyDirectory() method that makes use of FileFilter [IO-105] - Add moveDirectory() and moveFile() methods [IO-77] - FilenameUtils - Add file name extension separator constants[IO-149] - IOExceptionWithCause [IO-148] - Add a new IOException implementation with constructors which take a cause - TeeInputStream [IO-129] - Add new Tee input stream implementation - FileWriterWithEncoding [IO-153] - Add new File Writer implementation that accepts an encoding - CharSequenceReader [IO-138] - Add new Reader implementation that handles any CharSequence (String, StringBuffer, StringBuilder or CharBuffer) - ThesholdingOuputStream [IO-121] - Add a reset() method which sets the count of the bytes written back to zero. - DeferredFileOutputStream [IO-130] - Add support for temporary files - ByteArrayOutputStream - Add a new write(InputStream) method [IO-152] - New Closed Input/Output stream implementations [IO-122] - AutoCloseInputStream - automatically closes and discards the underlying input stream - ClosedInputStream - returns -1 for any read attempts - ClosedOutputStream - throws an IOException for any write attempts - CloseShieldInputStream - prevents the underlying input stream from being closed. - CloseShieldOutputStream - prevents the underlying output stream from being closed. - Add Singleton Constants to several stream classes [IO-143] - PrefixFileFilter [IO-126] - Add faciltiy to specify case sensitivity on prefix matching - SuffixFileFilter [IO-126] - Add faciltiy to specify case sensitivity on suffix matching - RegexFileFilter [IO-74] - Add new regular expression file filter implementation - Make IOFileFilter implementations Serializable [IO-131] - Improve IOFileFilter toString() methods [IO-120] - Make fields final so classes are immutable/threadsafe [IO-133] - changes to Age, Delegate, Name, Not, Prefix, Regex, Size, Suffix and Wildcard IOFileFilter implementations. - IOCase - Add a compare method to IOCase [IO-144] - Add a package of java.util.Comparator implementations for files [IO-145] - DefaultFileComparator - compare files using the default File.compareTo(File) method. - ExtensionFileComparator - compares files using file name extensions. - LastModifiedFileComparator - compares files using the last modified date/time. - NameFileComparator - compares files using file names. - PathFileComparator - compares files using file paths. - SizeFileComparator - compares files using file sizes.

libcommons-io-java-2.4.orig/src/site/xdoc/upgradeto1_3_1.xml0000644000175000017500000000335512125050425023265 0ustar ebourgebourg Upgrade from 1.3 to 1.3.1 Commons Documentation Team

These are the release notes and advice for upgrading Commons-IO from version 1.3 to version 1.3.1. Commons IO is a package of Java utility classes for java.io's hierarchy. Classes in this package are considered to be so standard and of such high reuse as to justify existence in java.io. Commons IO contains utility classes, stream implementations, file filters, and endian transformation classes. Compatibility with 1.3 ---------------------- Binary compatible - No See [IO-113] Source compatible - No See [IO-113] Semantic compatible - Yes Bug fixes from 1.3 ------------------ - FileUtils - NPE in openOutputStream(File) when file has no parent in path [IO-112] - readFileToString(File) is not static [IO-113]

libcommons-io-java-2.4.orig/src/site/xdoc/building.xml0000644000175000017500000000605612125050425022346 0ustar ebourgebourg Building Commons Documentation Team

Commons IO uses Maven 2+ or Ant as a build system.

Commons IO requires a minimum of JDK 1.5 to build.

You may also be interested in the upgrade notes:
Upgrade from 2.0 to 2.0.1
Upgrade from 1.4 to 2.0
Upgrade from 1.3.2 to 1.4
Upgrade from 1.3, or 1.3.1 to 1.3.2
Upgrade from 1.3 to 1.3.1
Upgrade from 1.2 to 1.3
Upgrade from 1.1 to 1.2
Upgrade from 1.0 to 1.1

The following Maven commands can be used to build io:

  • mvn clean - clean up
  • mvn test - compile and run the unit tests
  • mvn site - create io documentation
  • mvn package - build the jar
  • mvn package -Prc - Create the source and binary distributions

Note:

  • Dependencies are automatically downloaded if not specified explicitly in a build.properties file.

The following Ant commands can be used to build io:

  • ant clean - clean up
  • ant test - compile and run the unit tests
  • ant javadoc - create javadocs
  • ant jar - build the jar
  • ant dist - Create the source and binary distributions
libcommons-io-java-2.4.orig/src/site/xdoc/upgradeto2_1.xml0000644000175000017500000000641112125050425023040 0ustar ebourgebourg Upgrade from 2.0.1 to 2.1 Commons Documentation Team

These are the release notes and advice for upgrading Commons-IO from version 2.0.1 to version 2.1 Commons IO is a package of Java utility classes for java.io's hierarchy. Classes in this package are considered to be so standard and of such high reuse as to justify existence in java.io. Commons IO contains utility classes, stream implementations, file filters, file comparators and endian transformation classes. Compatibility with 2.0.1 and 1.4 -------------------------------- Binary compatible - Yes Source compatible - Yes Semantic compatible - Yes Check the bug fixes section for semantic bug fixes Commons IO 2.1 requires a minimum of JDK 1.5 (Commons IO 1.4 had a minimum of JDK 1.3) New features since 2.0.1 ------------------------ o Use standard Maven directory layout Issue: IO-285. Thanks to ggregory. o Add IOUtils API toString for URL and URI to get contents Issue: IO-284. Thanks to ggregory. o Add API FileUtils.copyFile(File input, OutputStream output) Issue: IO-282. Thanks to ggregory. o FileAlterationObserver has no getter for FileFilter Issue: IO-262. o Add FileUtils.getFile API with varargs parameter Issue: IO-261. o Add new APPEND parameter for writing string into files Issue: IO-182. o Add new read method "toByteArray" to handle InputStream with known size. Issue: IO-251. Thanks to Marco Albini. Fixed Bugs since 2.0.1 ---------------------- o Dubious use of mkdirs() return code Issue: IO-280. Thanks to sebb. o ReaderInputStream enters infinite loop when it encounters an unmappable character Issue: IO-277. o FileUtils.moveFile() JavaDoc should specify FileExistsException thrown Issue: IO-264. o ClassLoaderObjectInputStream does not handle Proxy classes Issue: IO-260. o Tailer returning partial lines when reaching EOF before EOL Issue: IO-274. Thanks to Frank Grimes. o FileUtils.copyFile() throws IOException when copying large files to a shared directory (on Windows) Issue: IO-266. Thanks to Igor Smereka. o FileSystemUtils.freeSpaceKb throws exception for Windows volumes with no visible files. Improve coverage by also looking for hidden files. Issue: IO-263. Thanks to Gil Adam. Changes since 2.0.1 ------------------- o FileAlterationMonitor.stop(boolean allowIntervalToFinish) Issue: IO-259.

libcommons-io-java-2.4.orig/src/site/xdoc/download_io.xml0000644000175000017500000002054312125050425023044 0ustar ebourgebourg Download Commons IO Commons Documentation Team

We recommend you use a mirror to download our release builds, but you must verify the integrity of the downloaded files using signatures downloaded from our main distribution directories. Recent releases (48 hours) may not yet be available from the mirrors.

You are currently using [preferred]. If you encounter a problem with this mirror, please select another mirror. If all mirrors are failing, there are backup mirrors (at the end of the mirrors list) that should be available.

[if-any logo][end]

Other mirrors:

The KEYS link links to the code signing keys used to sign the product. The PGP link downloads the OpenPGP compatible signature from our main site. The MD5 link downloads the checksum from the main site.

commons-io-2.4-bin.tar.gz md5 pgp
commons-io-2.4-bin.zip md5 pgp
commons-io-2.4-src.tar.gz md5 pgp
commons-io-2.4-src.zip md5 pgp
commons-io-2.2-bin.tar.gz md5 pgp
commons-io-2.2-bin.zip md5 pgp
commons-io-2.2-src.tar.gz md5 pgp
commons-io-2.2-src.zip md5 pgp

Older releases can be obtained from the archives.

libcommons-io-java-2.4.orig/src/site/xdoc/description.xml0000644000175000017500000002367412125050425023101 0ustar ebourgebourg User guide Commons Documentation Team

Commons-IO contains utility classes, endian classes, line iterator, file filters, file comparators and stream implementations.

For a more detailed descriptions, take a look at the javadocs.

IOUtils contains utility methods dealing with reading, writing and copying. The methods work on InputStream, OutputStream, Reader and Writer.

As an example, consider the task of reading bytes from a URL, and printing them. This would typically done like this:

InputStream in = new URL( "http://jakarta.apache.org" ).openStream(); try { InputStreamReader inR = new InputStreamReader( in ); BufferedReader buf = new BufferedReader( inR ); String line; while ( ( line = buf.readLine() ) != null ) { System.out.println( line ); } } finally { in.close(); }

With the IOUtils class, that could be done with:

InputStream in = new URL( "http://jakarta.apache.org" ).openStream(); try { System.out.println( IOUtils.toString( in ) ); } finally { IOUtils.closeQuietly(in); }

In certain application domains, such IO operations are common, and this class can save a great deal of time. And you can rely on well-tested code.

For utility code such as this, flexibility and speed are of primary importance. However you should also understand the limitations of this approach. Using the above technique to read a 1GB file would result in an attempt to create a 1GB String object!

The FileUtils class contains utility methods for working with File objects. These include reading, writing, copying and comparing files.

For example to read an entire file line by line you could use:

File file = new File("/commons/io/project.properties"); List lines = FileUtils.readLines(file, "UTF-8");

The FilenameUtils class contains utility methods for working with filenames without using File objects. The class aims to be consistent between Unix and Windows, to aid transitions between these environments (such as moving from development to production).

For example to normalize a filename removing double dot segments:

String filename = "C:/commons/io/../lang/project.xml"; String normalized = FilenameUtils.normalize(filename); // result is "C:/commons/lang/project.xml"

The FileSystemUtils class contains utility methods for working with the file system to access functionality not supported by the JDK. Currently, the only method is to get the free space on a drive. Note that this uses the command line, not native code.

For example to find the free space on a drive:

long freeSpace = FileSystemUtils.freeSpace("C:/");

Different computer architectures adopt different conventions for byte ordering. In so-called "Little Endian" architectures (eg Intel), the low-order byte is stored in memory at the lowest address, and subsequent bytes at higher addresses. For "Big Endian" architectures (eg Motorola), the situation is reversed.

There are two classes in this package of relevance:

  • The EndianUtils class contains static methods for swapping the Endian-ness of Java primitives and streams.
  • The SwappedDataInputStream class is an implementation of the DataInput interface. With this, one can read data from files of non-native Endian-ness.

For more information, see http://www.cs.umass.edu/~verts/cs32/endian.html

The org.apache.commons.io.LineIterator class provides a flexible way for working with a line-based file. An instance can be created directly, or via factory methods on FileUtils or IOUtils. The recommended usage pattern is:

LineIterator it = FileUtils.lineIterator(file, "UTF-8"); try { while (it.hasNext()) { String line = it.nextLine(); /// do something with line } } finally { LineIterator.closeQuietly(iterator); }

The org.apache.commons.io.filefilter package defines an interface (IOFileFilter) that combines both java.io.FileFilter and java.io.FilenameFilter. Besides that the package offers a series of ready-to-use implementations of the IOFileFilter interface including implementation that allow you to combine other such filters. These filters can be used to list files or in FileDialog, for example.

See the filefilter package javadoc for more details.

The org.apache.commons.io.comparator package provides a number of java.util.Comparator implementations for java.io.File. These comparators can be used to sort lists and arrays of files, for example.

See the comparator package javadoc for more details.

The org.apache.commons.io.input and org.apache.commons.io.output packages contain various useful implementations of streams. These include:

  • Null output stream - that silently absorbs all data sent to it
  • Tee output stream - that sends output data to two streams instead of one
  • Byte array output stream - that is a faster version of the JDK class
  • Counting streams - that count the number of bytes passed
  • Proxy streams - that delegate to the correct method in the proxy
  • Lockable writer - that provides synchronization of writes using a lock file

See the input or output package javadoc for more details.

libcommons-io-java-2.4.orig/src/site/xdoc/upgradeto2_2.xml0000644000175000017500000001007112125050425023036 0ustar ebourgebourg Upgrade from 2.1 to 2.2 Commons Documentation Team

These are the release notes and advice for upgrading Commons-IO from version 2.1 to version 2.2 Commons IO is a package of Java utility classes like java.io. Classes in this package are considered to be so standard and of such high reuse as to justify existence in java.io. Commons IO contains utility classes, stream implementations, file filters, file comparators, endian transformation classes, and much more. ============================================================================== Commons IO Package Version 2.2 ============================================================================== Changes in this version include: New features: o IO-305: New copyLarge() method in IOUtils that takes additional offset, length arguments Thanks to Manoj Mokashi. o IO-287: Use terabyte (TB) , petabyte (PB) and exabyte (EB) in FileUtils.byteCountToDisplaySize(long size) Thanks to Ron Kuris, Gary Gregory. o IO-173: FileUtils.listFiles() doesn't return directories Thanks to Marcos VinĂ­cius da Silva. o IO-297: CharSequenceInputStream to efficiently stream content of a CharSequence Thanks to Oleg Kalnichevski. o IO-304: The second constructor of Tailer class does not pass 'delay' to the third one Thanks to liangly. o IO-303: TeeOutputStream does not call branch.close() when main.close() throws an exception Thanks to fabian.barney. o IO-302: ArrayIndexOutOfBoundsException in BOMInputStream when reading a file without BOM multiple times Thanks to jsteuerwald, detinho. o IO-301: Add IOUtils.closeQuietly(Selector) necessary Thanks to kaykay.unique. o IO-292: IOUtils.closeQuietly() should take a ServerSocket as a parameter Thanks to sebb. o IO-290: Add read/readFully methods to IOUtils Thanks to sebb. o IO-288: Supply a ReversedLinesFileReader Thanks to Georg Henzler. o IO-291: Add new function FileUtils.directoryContains. Thanks to ggregory. o IO-275: FileUtils.contentEquals and IOUtils.contentEquals - Add option to ignore "line endings" Added contentEqualsIgnoreEOL methods to both classes Thanks to CJ Aspromgos. Fixed Bugs: o IO-300: FileUtils.moveDirectoryToDirectory removes source directory if destination is a subdirectory o IO-307: ReaderInputStream#read(byte[] b, int off, int len) should check for valid parameters o IO-306: ReaderInputStream#read(byte[] b, int off, int len) should always return 0 for length == 0 o IO-276: "FileUtils#deleteDirectoryOnExit(File)" does not work Thanks to nkami. o IO-273: BoundedInputStream.read() treats max differently from BoundedInputStream.read(byte[]...) Thanks to sebb. o IO-298: Various methods of class 'org.apache.commons.io.FileUtils' incorrectly suppress 'java.io.IOException' Thanks to Christian Schulte. Changes: o IO-296: ReaderInputStream optimization: more efficient reading of small chunks of data Thanks to Oleg Kalnichevski. Compatibility with 2.1 and 1.4: Binary compatible: Yes Source compatible: Yes Semantic compatible: Yes. Check the bug fixes section for semantic bug fixes Commons IO 2.2 requires a minimum of JDK 1.5. Commons IO 1.4 requires a minimum of JDK 1.3.

libcommons-io-java-2.4.orig/src/site/xdoc/upgradeto2_3.xml0000644000175000017500000000440512125050425023043 0ustar ebourgebourg Upgrade from 2.2 to 2.3 Commons Documentation Team

These are the release notes and advice for upgrading Commons-IO from version 2.2 to version 2.3 Commons IO is a package of Java utility classes like java.io. Classes in this package are considered to be so standard and of such high reuse as to justify existence in java.io. The Commons IO library contains utility classes, stream implementations, file filters, file comparators, endian transformation classes, and much more. ============================================================================== Apache Commons IO Version 2.3-SNAPSHOT ============================================================================== Changes in this version include: New features: o IO-322: Add and use class Charsets. Thanks to ggregory. o IO-321: ByteOrderMark UTF_32LE is incorrect. Thanks to ggregory. o IO-318: Add Charset sister APIs to method that take a String charset name. Thanks to ggregory. Compatibility with 2.2 and 1.4: Binary compatible: Yes. Source compatible: No, see the rare case in https://issues.apache.org/jira/browse/IO-318. Semantic compatible: No, see the rare case in https://issues.apache.org/jira/browse/IO-318. Commons IO 2.3 requires JDK 1.6 or later. Commons IO 2.2 requires JDK 1.5 or later. Commons IO 1.4 requires JDK 1.3 or later.

libcommons-io-java-2.4.orig/src/site/xdoc/upgradeto1_3.xml0000644000175000017500000001770512125050425023051 0ustar ebourgebourg Upgrade from 1.2 to 1.3 Commons Documentation Team

These are the release notes and advice for upgrading Commons-IO from version 1.2 to version 1.3. Commons IO is a package of Java utility classes for java.io's hierarchy. Classes in this package are considered to be so standard and of such high reuse as to justify existence in java.io. Commons IO contains utility classes, stream implementations, file filters, and endian transformation classes. Compatibility with 1.2 ---------------------- Binary compatible - Yes Source compatible - Yes Semantic compatible - Yes Check the bug fixes section for semantic bug fixes Deprecations from 1.2 --------------------- - WildcardFilter deprecated, replaced by WildcardFileFilter - old class only accepted files, thus had a confusing dual purpose - FileSystemUtils.freeSpace deprecated, replaced by freeSpaceKb - freeSpace returns a result that varies by operating system and thus isn't that useful - freeSpaceKb returns much better and more consistent results - freeSpaceKb existed in v1.2, so this is a gentle cutover Bug fixes from 1.2 ------------------ - LineIterator now implements Iterator - It was always supposed to... - FileSystemUtils.freeSpace/freeSpaceKb [IO-83] - These should now work on AIX and HP-UX - FileSystemUtils.freeSpace/freeSpaceKb [IO-90] - Avoid infinite looping in Windows - Catch more errors with nice messages - FileSystemUtils.freeSpace [IO-91] - This is now documented not to work on SunOS 5 - FileSystemUtils [IO-93] - Fixed resource leak leading to 'Too many open files' error - Previously did not destroy Process instances (as JDK Javadoc is so poor) - http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4801027 - FileUtils.touch [IO-100] - The touch method previously gave no indication when the file could not be touched successfully (such as due to access restrictions) - it now throws an IOException if the last modified date cannot be changed - FileCleaner - This now handles the situation where an error occurs when deleting the file - IOUtils.copy [IO-84] - Copy methods could return inaccurate byte/char count for large streams - The copy(InputStream, OutputStream) method now returns -1 if the count is greater than an int - The copy(Reader, Writer) method now throws now returns -1 if the count is greater than an int - Added a new copyLarge(InputStream, OutputStream) method that returns a long - Added a new copyLarge(Reader, Writer) method that returns a long - CountingInputStream/CountingOutputStream [IO-84] - Methods were declared as int thus the count was innacurate for large streams - new long based methods getByteCount()/resetByteCount() added - existing methods changed to throw an exception if the count is greater than an int - FileBasedTestCase - Fixed bug in compare content methods identified by GNU classpath - EndianUtils.writeSwappedLong(byte[], int) [IO-101] - An int overrun in the bit shifting when it should have been a long - EndianUtils.writeSwappedLong(InputStream) [IO-102] - The return of input.read(byte[]) was not being checked to ensure all 8 bytes were read Enhancements from 1.2 --------------------- - DirectoryWalker [IO-86] - New class designed for subclassing to walk through a set of files. DirectoryWalker provides the walk of the directories, filtering of directories and files, and cancellation support. The subclass must provide the specific behaviour, such as text searching or image processing. - IOCase - New class/enumeration for case-sensitivity control - FilenameUtils - New methods to handle case-sensitivity - wildcardMatch - new method that has IOCase as a parameter - equals - new method that has IOCase as a parameter - FileUtils [IO-108] - new default encoding methods for: - readFileToString(File) - readLines(File) - lineIterator(File) - writeStringToFile(File, String) - writeLines(File, Collection) - writeLines(File, Collection, String) - FileUtils.openOutputStream [IO-107] - new method to open a FileOutputStream, creating parent directories if required - FileUtils.touch - FileUtils.copyURLToFile - FileUtils.writeStringToFile - FileUtils.writeByteArrayToFile - FileUtils.writeLines - enhanced to create parent directories if required - FileUtils.openInputStream [IO-107] - new method to open a FileInputStream, providing better error messages than the JDK - FileUtils.isFileOlder - new methods to check if a file is older (i.e. isFileOlder()) - counterparts to the existing isFileNewer() methods. - FileUtils.checksum, FileUtils.checksumCRC32 - new methods to create a checksum of a file - FileUtils.copyFileToDirectory [IO-104] - new variant that optionally retains the file date - FileDeleteStrategy - FileCleaner [IO-56,IO-70] - FileDeleteStrategy is a strategy for handling file deletion - This can be used as a calback in FileCleaner - Together these allow FileCleaner to do a forceDelete to kill directories - FileCleaner.exitWhenFinished [IO-99] - A new method that allows the internal cleaner thread to be cleanly terminated - WildcardFileFilter - Replacement for WildcardFilter - Accepts both files and directories - Ability to control case-sensitivity - NameFileFilter - Ability to control case-sensitivity - FileFileFilter - New IOFileFilter implementation - Accepts files where File.isFile() is true - In other words it filters out directories - Singleton instance provided (FILE) - CanReadFileFilter - New IOFileFilter implementation - Accepts files where File.canRead() is true - Singleton instances provided (CAN_READ/CANNOT_READ/READ_ONLY) - CanWriteFileFilter - New IOFileFilter implementation - Accepts files where File.canWrite() is true - Singleton instances provided (CAN_WRITE/CANNOT_WRITE) - HiddenFileFilter - New IOFileFilter implementation - Accepts files where File.isHidden() is true - Singleton instances provided (HIDDEN/VISIBLE) - EmptyFileFilter - New IOFileFilter implementation - Accepts files or directories that are empty - Singleton instances provided (EMPTY/NOT_EMPTY) - TrueFileFilter/FalseFileFilter/DirectoryFileFilter - New singleton instance constants (TRUE/FALSE/DIRECTORY) - The new constants are more JDK 1.5 friendly with regards to static imports (whereas if everything uses INSTANCE, then they just clash) - The old INSTANCE constants are still present and have not been deprecated - FileFilterUtils.sizeRangeFileFilter - new sizeRangeFileFilter(long minimumSize, long maximumSize) method which creates a filter that accepts files within the specified size range. - FileFilterUtils.makeDirectoryOnly/makeFileOnly - two new methods that decorate a file filter to make it apply to directories only or files only - NullWriter - New writer that acts as a sink for all data, as per /dev/null - NullInputStream - New input stream that emulates a stream of a specified size - NullReader - New reader that emulates a reader of a specified size - ByteArrayOutputStream [IO-97] - Performance enhancements

libcommons-io-java-2.4.orig/src/site/xdoc/mail-lists.xml0000644000175000017500000002217412125050425022626 0ustar ebourgebourg Commons IO Mailing Lists Commons Documentation Team

Commons IO shares mailing lists with all the other Commons Components. To make it easier for people to only read messages related to components they are interested in, the convention in Commons is to prefix the subject line of messages with the component's name, for example:

  • [io] Problem with the ...

Questions related to the usage of Commons IO should be posted to the User List.
The Developer List is for questions and discussion related to the development of Commons IO.
Please do not cross-post; developers are also subscribed to the user list.

Note: please don't send patches or attachments to any of the mailing lists. Patches are best handled via the Issue Tracking system. Otherwise, please upload the file to a public server and include the URL in the mail.

Please prefix the subject line of any messages for Commons IO with [io] - thanks!

Name Subscribe Unsubscribe Post Archive Other Archives
Commons User List

Questions on using Commons IO.

Subscribe Unsubscribe Post mail-archives.apache.org markmail.org
www.mail-archive.com
news.gmane.org
Commons Developer List

Discussion of development of Commons IO.

Subscribe Unsubscribe Post mail-archives.apache.org markmail.org
www.mail-archive.com
news.gmane.org
Commons Issues List

Only for e-mails automatically generated by the issue tracking system.

Subscribe Unsubscribe read only mail-archives.apache.org markmail.org
www.mail-archive.com
Commons Commits List

Only for e-mails automatically generated by the source control sytem.

Subscribe Unsubscribe read only mail-archives.apache.org markmail.org
www.mail-archive.com

Other mailing lists which you may find useful include:

Name Subscribe Unsubscribe Post Archive Other Archives
Apache Announce List

General announcements of Apache project releases.

Subscribe Unsubscribe read only mail-archives.apache.org markmail.org
old.nabble.com
www.mail-archive.com
news.gmane.org
libcommons-io-java-2.4.orig/src/site/xdoc/index.xml0000644000175000017500000000726512125050425021663 0ustar ebourgebourg Commons IO Overview Commons Documentation Team

Commons IO is a library of utilities to assist with developing IO functionality.

There are six main areas included:

  • Utility classes - with static methods to perform common tasks
  • Input - useful Input Stream and Reader implementations
  • Output - useful Output Stream and Writer implementations
  • Filters - various implementations of file filters
  • Comparators - various implementations of java.util.Comparator for files
  • File Monitor - a component for monitoring file system events

Commons IO 2.4 is the latest version and requires a minimum of JDK 1.6 - Download now!

View the Release Notes and JavaDoc API documents

Commons IO 2.2 requires a minimum of JDK 1.5 - Download now!

View the Release Notes and JavaDoc API documents

For previous releases, see the Apache Archive.

The commons mailing lists act as the main support forum. The user list is suitable for most library usage queries. The dev list is intended for the development discussion. Please remember that the lists are shared between all commons components, so prefix your email by [io].

Issues may be reported via ASF JIRA. Please read the instructions carefully to submit a useful bug report or enhancement request.

libcommons-io-java-2.4.orig/src/site/xdoc/upgradeto1_2.xml0000644000175000017500000000515012125050425023037 0ustar ebourgebourg Upgrade from 1.1 to 1.2 Commons Documentation Team

These are the release notes and advice for upgrading Commons-IO from version 1.1 to version 1.2. Commons IO is a package of Java utility classes for java.io's hierarchy. Classes in this package are considered to be so standard and of such high reuse as to justify existence in java.io. Commons IO contains utility classes, stream implementations, file filters, and endian transformation classes. Compatibility with 1.1 ---------------------- Binary compatible - Yes Source compatible - Yes Semantic compatible - Yes Deprecations from 1.1 --------------------- Bug fixes from 1.1 ------------------ - FileSystemUtils.freeSpace(drive) Fix to allow Windows based command to function in French locale - FileUtils.read* Increase certainty that files are closed in case of error - LockableFileWriter Locking mechanism was broken and only provided limited protection [38942] File deletion and locking in case of constructor error was broken Enhancements from 1.1 --------------------- - AgeFileFilter/SizeFileFilter New file filters that compares against the age and size of the file - FileSystemUtils.freeSpaceKb(drive) New method that unifies result to be in kilobytes [38574] - FileUtils.contentEquals(File,File) Performance improved by adding length and file location checking - FileUtils.iterateFiles Two new method to provide direct access to iterators over files - FileUtils.lineIterator IOUtils.lineIterator New methods to provide an iterator over the lines in a file [38083] - FileUtils.copyDirectoryToDirectory New method to copy a directory to within another directory [36315]

libcommons-io-java-2.4.orig/src/site/xdoc/upgradeto2_4.xml0000644000175000017500000000663312125050425023051 0ustar ebourgebourg Upgrade from 2.3 to 2.4 Commons Documentation Team

These are the release notes and advice for upgrading Commons-IO from version 2.3 to version 2.4 Commons IO is a package of Java utility classes like java.io. Classes in this package are considered to be so standard and of such high reuse as to justify existence in java.io. The Commons IO library contains utility classes, stream implementations, file filters, file comparators, endian transformation classes, and much more. ============================================================================== Apache Commons IO Version 2.4-SNAPSHOT ============================================================================== Changes in this version include: New features: o IO-269: Tailer locks file from deletion/rename on Windows. Thanks to sebb. o IO-333: Export OSGi packages at version 1.x in addition to 2.x. Thanks to fmeschbe. o IO-320: Add XmlStreamReader support for UTF-32. Thanks to ggregory. o IO-331: BOMInputStream wrongly detects UTF-32LE_BOM files as UTF-16LE_BOM files in method getBOM(). Thanks to ggregory. o IO-327: Add byteCountToDisplaySize(BigInteger). Thanks to ggregory. o IO-326: Add new FileUtils.sizeOf[Directory] APIs to return BigInteger. Thanks to ggregory. o IO-325: Add IOUtils.toByteArray methods to work with URL and URI. Thanks to raviprak. o IO-324: Add missing Charset sister APIs to method that take a String charset name. Thanks to raviprak. Fixed Bugs: o IO-279: Tailer erroneously considers file as new. Thanks to Sergio Bossa, Chris Baron. o IO-335: Tailer#readLines - incorrect CR handling. o IO-334: FileUtils.toURLs throws NPE for null parameter; document the behavior. o IO-332: Improve tailer's reading performance. Thanks to liangly. o IO-279: Improve Tailer performance with buffered reads (see IO-332). o IO-329: FileUtils.writeLines uses unbuffered IO. Thanks to tivv. o IO-319: FileUtils.sizeOfDirectory follows symbolic links. Thanks to raviprak. Compatibility with 2.3: Binary compatible: Yes. Source compatible: Yes. Semantic compatible: Yes. Compatibility with 2.2 and 1.4: Binary compatible: Yes. Source compatible: No, see the rare case in https://issues.apache.org/jira/browse/IO-318. Semantic compatible: No, see the rare case in https://issues.apache.org/jira/browse/IO-318. Commons IO 2.4 requires JDK 1.6 or later. Commons IO 2.3 requires JDK 1.6 or later. Commons IO 2.2 requires JDK 1.5 or later. Commons IO 1.4 requires JDK 1.3 or later.

libcommons-io-java-2.4.orig/src/site/resources/0000755000175000017500000000000011765740036021112 5ustar ebourgebourglibcommons-io-java-2.4.orig/src/site/resources/images/0000755000175000017500000000000012125050425022342 5ustar ebourgebourglibcommons-io-java-2.4.orig/src/site/resources/images/io-logo-white.png0000644000175000017500000002463012125050425025540 0ustar ebourgebourg‰PNG  IHDRćZ¬b*µsRGB®ÎébKGD˙˙˙ ˝§“ pHYs  šśtIMEŰ +!Hź!iTXtCommentCreated with The GIMPm°— IDATxÚí}ipVUŇ?K‚¦¦”' ‰źFŁ‚„ťt†QYŚIHơ`tf¤H•ă” X.(ŠE@D [•%,Ń„a`Ŕ°Č6n !* $Ďvţ´oőíŰçŢű„÷ýż喙•äÉsÎésN˙şűôéÓ×§”R@ˇ_O°Ş©ř|ľ„űű)őuÜöÁëÚŐłű_˘´JßďÍnh•Úĺýwt=ÝĐ|1sŁk˙“‡ěćÎçŐŐŐĆ媫®‚ÜÜ\ČËËĚĚLGćĂżĄÁú|>¨®®†Żľú ĘËËM˙ËËËĽĽ<ČÍÍuśT»>ęęęŕí·ß†AA^^žĄ˝šš¨®®†ššcŚĹĹŦľueÝşu°{÷nřꫯLuóňň´ Çéĺt×ÔÔ@yy9Ěž=[{yy9ÔÔÔ}ćĺĺAII‰e=¤yŘ˝{·i®±nVV–+zuë‹íă<"mYYYF?N¬çzś›’’c-±Mä#\G€ââb())qěĎŽ‡ř|”””Ŕ AŚ9ä‘G`öěŮZám÷·ń»r(/ľř˘ĘĘĘR`ű«“'OŞööví‡U8V‘HDEŁQ‹ĹT,SłgĎvŐGVV–*--M¸źh4ŞÖ¬YŁJJJڶ֬YŁ˘Ń¨ŠD"*«]»v©ÜÜ\mßąąąęĉęÂ… –çąçžłĄë¶µµ™ęµµµ©¶¶6Ý‘HD}öŮgjöěŮ*//ĎhiEz_xáŰ>'OžléďÂ… ęřńăjňäɶóŚuń‘hĄôҵü裏Lt;ńĚÎť;U{{»©?i=qěUUUęá‡6ŤýÍ7ß4ćĺż˙ýŻ*--µĺˇU«VYćE·8ľ)S¦Ú())Q%%%¦±<ä–/qŢb±ŠÇă*Ź+Ą”ŇłşşÚ4ř)S¦¨ŞŞ*cNž<©Š‹‹-_ąrĄúî»ď,Ď÷ßoLşzőjS?ü°Úµk— ‡ĂŞ˝˝]ťűĚĤyyyjÍš5żŕzK´Ů®ĺoĽˇŠ‹‹µ‚×rÇŽ®<¨+VórîÜ9Űń!ÍYYYj×®]&ŮŢŢ®vîÜi×… Ô÷ßo´Ążś"0ßzë-ÓńĹ&BÚŰŰŤŽhôňĺËŐ·ß~kŘ·o >ÜřŢŔaëÖ­&Ç}°/|z÷î §Nťű˘ żß~ż?‹\qĹIśĆ‚‚Xşt©86,Ó§O‡E‹YĆ7jÔ(X°`iÓN¤kúôé¦z›6m‚ľ}ű#ŤHo €M›6Á˝÷ŢkéséŇĄpçťwZhĄô0Ŕ2? ,€QŁFŮŇ{çťwÂŢ˝{ŤďdddŔżţő/KJkŻ^˝ ľľŢřαcÇ '§‘˙ţÔSOÁkŻ˝f˘3??-Zd˘ űôů|ÚąY˛d äçç›x•ňÓľ}ű   @»†´ß´iÓŕŐW_€ÂÂBXąr%ř|> Źbźţ󟡢˘š››-Ú6ýť˙ ŕ§€¸ë®»Ś†~řa”±X âń8Äb1FŁŤF!‰@$´´4čׯźe˘rrr ›žH$O<ń„é{<đ€Ń&}"‘„ĂaS_‘HÄ(Zţţ÷żC8†öövhoo7ębźáp8Ŕëôďß-Zd|ëŇßŰŰŰá¶Űnłô×»wo3g´µµiźöövQ`}ńŦöń»”îX,f©÷ôÓOèQŁLôrZŰÚÚLBËcŹ=Æ i¤4ôîÝŰTݎˇÁÔ>ťŁp8 ŻĽňŠ ”………––¦]O|p]¦Nť ¦>ßy稩©1őEëHs3}út1b„88¶îÝ»Czzş©ŢŢ˝{ŵŔľ¨çuĎž=ĆX(plŃhÂá°!ü(˙Ió‹Ĺ \q!bćś9s ®®ÎäZF0Ćăq‘śč &xŢĽyššjYŚÝ»w›$2J-Ţ>8XúYNNŽe1`áÂ…F?”y~·ź/fzzşń\şř{÷îÝ-Ś …lA‰môčŃĂR÷ÝwßŐ2{[[›ˇPČ"D$pÝpĂ –ş)))¦1ásáÂS={ö´Ô­¨¨°ôt.\¸Đ˘ít@äĂďŚ9R]?Jc4µ|?55Ő—DĺéÓ§-ߡż#`ęëëaŢĽy&ޤăÄqˇ`”ćń%Y?ADęŰożm"zŔ€&Ds”ÓŻĽňJ¨ŞŞ‚úúzHOOĄD"ËY#7 űöík™hÉ\ćŇdřđá°lŮ2 ĂŹ7Îd–Ї—x&Ú—t–ŹÇ- §3‡x‰ĹbĐÖÖfŞŚĄ±TŹŇ‹4Sz}>źX7ŤB[[›ĺÜ›Q‘HÄR7‰čEöÝwß…††Ów{őęápŘ0÷>Î|t=ożývX˛d‰©ťýű÷Ă—_~ih8J§Dc4…öövc^řÜĐu㥽˝ÝbjFŁ““ď˝÷žńݧžz âń8üĺ/1™Ět+¤”‚µk×óŔ·VŘ>íé˘frP)uuu¦ŘÜÜ\Ł3("ťjQžP(ŃhÔb#ďż˙ľ¨µxH:±t‚o»í6 08`Z4N¸pl8Nľ:`†Ăa“"1ş.&›ćĹçóA04¸:zuŔD‰NÁ÷<:`bżH/~—2,×\tžśÖłgĎžžž§Oź¶™·Ţz«…VÝÜ 6ŐÓçó‰–Ą—3 °aĂŕŮgź5}Ú´iPQQO>ů$ôęŐKcŹ= ‰Ö—’2řý~f‚ü±©óĚĚL”ś\ZsÇ ×tMMM"SfĐmÜů $“ `ßľ}pĂ 7XN†NcâOާ`ű‚ÁŚźş1Sđűý~“´wŇśTř!“ęęRćáBǸX—3/j‚\ŁĐőä‘.999–ööďß·Ür‹i-ü~ż‰ .LśÚʤ1éZŕś ĺҵkW¸űî»aĺĘ•>=z4ôîÝ^|ńE…B¦1JN«@ `‹„,A€Ý»w[¤:ejKV^?ŁŕýĎţ#j Lŕq tňŇŇŇ ±±ŃÔŢ©S§ŕÚkŻµÔłÓ´'­G­:¸¨@@d¬ËÇ ŤĎtZďUp-čXĄş¸á‚„2! ]]Ęt>ź<(D˛~¨ –ĽÁiii–¶Nź>m€†öëÖš <ĘŔëšś.?ÎŇ^ZZ §Oź†Í›7[ęîßż† ăĆŤ±cÇB(ŇzŰą€ ŹD[P)eň>Q`JÎŚÜ­Í÷\vńtŃ%[ťO*`Ż^˝ŕĂ?´ezŞtš‹Ž“ŹKjd4Ęě´]¤WŇü艎sŻ›+ PÚ7Ň* şýŕ‚$Źű[]] ĐRAŤ©;Jŕ?ëŐ«—E+ŃÓZßΔĄÚ’ŽçFâEîWĚĘ™3gBZZ¬ZµJ÷oĽ›7o†ß˙ţ÷0fĚ‹µ&in®€¸ĺé—:ÚłgŹEcrď·ăĄ= ?·áeóćÍbű\+Hf‰.ÂźëPO ŽŃ%Ź™®_É2°sŽIŚNëRš÷mLn~ó}•­şş:z%TţůĎZŽČtć7›ťŕ¦Lś8Ń•ÖD`ňăťöĐť‰Ţz뭢ɦ[Lé˙˘I!Y|ď,1ľÎDÓí»Ą  7ÚX:+“ {tŰŢŇGcޱ´´´ZÂnŹĹŰýŕ,áśéééÚů±ŰH‚ĘN(éś—J)5k¬[·Î¶ýÔÔT:u*<ţřă–¶wîÜ)Z‚NűNCcćććŠ7ŢKKKáÔ©SĐH{!Ôţýűa„ °páB 0i5–ÂÁm#)¸9"ťˇÝzë­˘ôł3ě’j ;pń>Ý0:´ťFtk&»ŃÜ<*ɉ1ąFá˙żćšk %%Ĺňý 6ű3ÝŢ[ZĎŰn»ÍB“hâLJŻÎÇA} Ň>|Xl—?C‡…ÂÂB‹ ˛‹“ĄV„ĺL™4i’x–ôâ‹/BCCvoĂĎ*'Lýúőţýű›\Ć@ú÷ď}úô±ôł}űvş3M®-˙řÇ?BFF†Ýb:™rnLYťĆÔ-˛nQ%FsKŻ$t‚„Ó&ŃźČ~úŽ;î°|żŞŞĘ‘O8ŹŃ3îôôt¸çž{,BĎ)÷Žť5‘Čzđ˛k×.‘G¤ą+**Ň:¦$_çQ7—Lš4IÔš[¶lűďżjkkµ¦f<‡eË–AII 444ŔkŻ˝&źřý~?ľĄŹµkבAN^CĄ”)/##{ě1-0Ü,Ş[í˘3íĚŮDťG‰7ă”Ě\N·NŁŘŤiÔ¨Qťťmú~kk+TTTŔ”ÎDyhĺÜąsEPv$ŰąqjżĽĽ\\sęěôűý¦€kŻ˝ÖöF‘t@â™gžŃžŃLš4 ĆŤŻ˝öěر*++a۶m0gθýöŰáąçž€ůóçCFF†V‚uëÖ ĘĘĘ,˙›1c†¸˙ă.ĺĺË—ÁÓFđ˝8śvIÜ:x?n5ĐĹd¬sÓź“)Ť·ŁĚ;eĘ‹IűúëŻCKK‹xź–>§Oź6sŢĽyЧOí¸ÜŇ(ŐŃŐ•ćCfSS“¨l(8Ďś9cŞ7xđ`‹w×άĄBË$& ańâĹZFhiiŤ7ÂĚ™3aĆŚ0mÚ4XłfŤ7gÎ>|¸ăYŕČ‘#ᥗ^2}väČ5k–ÖS©”‚>řŔP^^"ăŃÉăćf…˙ă^q_ÜQ 466:¦§”útPźĎ---"˝:w hÉčľ—’’3gδ€óÉ'ź„ÖÖVŃ BPŽ;Öřţ+ŻĽ#GŽ÷rt-±M;pézčС„LJÖW^yŢ5QS"07lŘ`ÔąńĆM{N»É’đs˘ L7óÝ”P(Ď>ű,üö·ż%´0LJ•+WšÔUUŚ?***L‹ZYY ÷Ýwüío€.*Ż]»ŇÓÓEçg °éc_­­­¶šÎçóÁöíŰĹŬ¬¬tÔ°k×®A"ôŰíkŔr-O§ĺ+++-u·mŰfË€ř™Dď¶mŰ…BJJ Ěš5  d2i'L+W®„cÇŽkyčĐ!(++QŁFAcc#¤§§CYYŚ1B J Îüă6mÚähúîرCxŇ|IĄ˛˛Ćʵµµ&z0ćŐW_5R2üqË'°sů"‘˘á^x!őłĎ>‰'Â'ź|bKpqq1Ś3˛˛˛ 99’““ŤsK~łC Ž‡Ă°bĹ XłfŤŁ¦čŮł'<účŁĐŻ_?CZá@č%éH$[¶l¦¦&Řąs'|úé§b{W^y%\wÝu0xđ`“—ńĉpěŘ1ř裏ŕČ‘#Zznľůf¸é¦› k×®pőŐWŔŃŁGářńăPUUĄ­ …ŕć›o†ěělčÚµ+\~ůĺpôčQ8zô(|ôŃG˘ÖčŢ˝;\wÝuťťmI?Ü:~ü8ěÚµK;‡ˇP† ŮŮŮťť W\qüNćرc¶u{ôčC‡…+®¸~ő«_Áĺ—_n ĹÄçčŃŁ°téRŚvÂüî»ď†{ď˝×ŕL/…8p<ëׯ×ÎÍ•W^ †ěělC@´¶¶Â‰'ŕăŹ?†ŞŞ*--Ý»w‡!C†ŔŕÁŤ±ů|>xá… µµBˇřý~ÄiiiĆĄkĄlٲĹÓď~÷;=z´ĺ&=¶JJJ‚ääd¸ě˛ËLĹŹďÇ@&ĎŢäľpá|ţůç°wď^Řşu«ˇťRRR ;;† Á`Đh¬K—.¦€Tńü€Zę/Ă ¶¶ÖÄĐ~żnąĺčŐ«\uŐU&ŕc›<¤/ĂSO=Ą˝6&™WpÍ5×Ŕé-Ž;¦ő rňµ×^ wŢy'(Ą ˘˘Ž=ęX"P6mÚ$:–¤ăĄ<účŁĆŘ^xáíŮŞäHŁcM´n~~>\}őŐ– oNkSS“!hh›=zô€śśčŰ·Żi-Q€Łŕ¦kązőj8tčëÇGy”Rpüřqxçťw´qŰ||8/ŘĎńăÇ!==şuëfĐzřđahnn†ÚÚZă' Á 7ÜżţőŻĹs>W™.]ş ěŇĄ‹ń€I™µć… Śônć]ˇ—J‘p:Ů( ůÂŃž~‚‡Đˇ„ ŃŘ6N0Ź·ĄŇŠß•äuč$ŇÉ ¦1ˇá‚cAiŤx˘ÖJ<Ź Ö•âŚi,*—Ä4Ú iĄuqś’«ççÇ‹ÂÇJiĄáuôŘGń3YJ'j|č8iźÜQ˘;äB’ŇĆűÄ9B!@ű˘cĂ~÷8_seĂC*ůéçCśo¤Ě ÎÓDAÇS_lá/ŘR0Ń˙S“VŠŚAfçQ!Ň#.áčbňëZ8én%˝ĚŠ×Éčµ'éěK·źLÔ ěTWçą•BÝDłčhrúŰŽVîlá‡ôŇeyIc!3óqJaž”(­&é¨ČnĚ|Ţi˙nŠî¨ Ű”®çé"±°ua]'‘€bJ´dć ÉL%ˇ“FŕH8|1Ą[ śY)ĂéíŃĎ9@ř›×•îłRFÇú”yčgTp+CŠćžBIzs3źÎ+ßÓů’ĚYľMŕűgÉÚ˘éV$ ‚ň]kĘ«’v˘óĆ׌ß|ŃÍ-Ź7ć‡ZvŔäĹůr›šk̤¤$1P€ćF‘í$6ß/zĄ·‹łSH˘żŘ%Rv —t»ŽN÷XÝÓÉL÷ů|`zŁ´ŽěŢ ěv@Nˇ_ş¬¸‘´v±Şş}€SFl7qŻş·‘ą‰›ŐŐµ»ßi—ĘMŠ ;z©k7÷ş¸T§ÇNŕt+;˛–NóâvMݬĄ“7ţŻ43$Ó4NŚ’H7í»•LnA§őí¶ÝĹÎ$uă,płđnĆîDo"uusä4÷vsŐŃő”řĂÍZÚÍ©›mEGŠŔ-ó©lfJG°nĎa'ůě4ăą]P7m»¨ŰۉK·Wt» 3ş9˝ŘşNŕtö‰0˛!žčZ&2/á]»xl§y·¦&tÚČ' DÚN„ˇťÚL ˇ-ŃTšS.&%f˘Âŕb5É˙ä:b]ąĺýŽféë¨"qĚ‹N"÷ţ:˘DSţ˙O‚ß+ÎDLx7&¶›—uŁ[í(ÖUÁ™?iz1%QMâů˙fťëęę şşÚ•i¬”‚¬¬,ČÍÍum×ŐŐAyy9ÔÔÔ@MM ÔŐŐ˙ö ĹĹĹâ+Eś€—čV뢀éŻü˙*Ěşş:xűí·- E•––Bff¦LşFpÔ××ĂË/ż sćĚ€ĽĽ<())¬¬,đĺĺĺ°{÷n¬ĄĄĄ0yňd[€:9yţW5¦WĽňeĺ <jjjLźź&`~đÁâľtů„ř;NPxŔôĘ%S¤ü?<˝*Ő®¨1uÚ’&áŇ˝¸Jw‰kM)ł!Ő¦üĺR0˝rIiQHţÎ bšZ÷Žş×äy¬ě}80iIš©‘ć»ň€é•KÎ)¤3M9xř+%)xhZI)3»›ÄcüU ü­Ňô­üU„0˝rITwô!ôóc é…Á4,~nGľ±Š/=ŠFŁ–\¸Ôdö€é•Kľ 2ÄňYccŁaĘň˝(3¶ô¶:]6ŔŰoż]ÜóŇT•Rp;żĹâEţxĺ’ךR9xđ ±Ď´»‚EĘ®ď÷űáß˙ţ·é{Ž{^77N<`zĄS•ަ0áZłąąŮôNę(’^űˇË:ęÔ)S»˝{÷ÖľoF¤ŽçiLŻül:tčPÓ߇ßAC=¸vtÚrÄ–ŚÜ\uz<Ťé•źŤI;dČHMM5ýoűöíÚW}čI?ŰłgŹé{ŁFŤrm^;e¦÷€é•źM=z´éďuëÖiäF[Ďź?ßř¬[·n¦»žvZÝ)YşLŻüě€yýő×9rŽ9âN)üoÆ FްÜőt¶S2.^ůYíI§Nťj2i.\h›V27ëëëá‰'ž0ľóŕB~~ľ#í^¬Ĺiđ€é•N»wěv …B0oŢ<śGŽ™3gÚľ˙’ď ź|ňIC[ŔÓO?m›.S÷b`» z0˝Ň) fąĂÂłŘ4 Áüůó pîÚµ fÍš%ľ ›łˇˇúöí 0cĆ Xşt©í«(éŃ ­;ł: i‰Ç^ńĘO@SľüňËPVVfúüüůópâÄ HKK””SČ2;Ă/~ń ¸ë®»ŕ»ďľĂ‡Ă—_~ ~řˇ´´4ŕ÷űa۶m°~ýz8q"ś;wú÷ďK–,‚‚SĎ´ÇŻ~áeé`0ÉÉÉ””IIIĆg¦8\/áłW:C©®®†—^zÉbZJQ5ńx®żţz=z´N޵číĄ466Â[o˝;vě€ććf- #FŚ€űďżhÄĘ€%×>‘HÄÔ €¤¤$HNN†Ë.» şté]şt1@ !ü@ŁLŻtMÉŁhh6ş¶¶6ăˇ)+QkQŤIo‡đ`÷x<;vě0@ŇŻ_?ČĘĘ‚äädHNN6LQz—ďwň\ÄŽýR`b{LěĎď÷˙¤ŘykzĹí’îď0€śjL„Ž §Ŕ6lâ`0IIIĆ÷hŘÖ?~<(Ą ©© RRRŕ˛Ë.{îąfĚóćÍ_ţň—°˙~;w.¬[·Î ‚ś:†~ĘŔôýřPzÎ*ŻhA)ď:Ňý%ŐšX¤«_üB4ŐÚ±X̤q.\ŃhJJJ ¬¬ b±ěßż’““aÆ 0~üx¨¨¨€H$bě)©źkv–k_RőăϧE˝Â=™x<•j@cgcÎrSÍĘ÷¨RŔ;Ň›› µµµpřđaČÎΆ/żüŇäđ‘ŔŮ™€I (˝˘Ó)Ç’‚SzKż{ÉďXZâ\Éeę@ ĹĹĹđŘcŹAEElÝşŐ$((˝,y^éô€äÚ‰źŇKĎNŞĄ¸‡?“LZî”âĆü±HĎđáĂ!55şvíúĂţ‘iJ Ll˦W:µ ËÍXšTť?Ô”ĺS2IĄĚzRäע<킿K—.pÓM7A04€ÉMjK»Ţq‰W:Cˇ‘5üÜ’żÄĎ1u{BąHşźi— VŇś\łS!ýÔEyÓ+ťJSró5•ä졟IÇ%<ˇ–äŇ“öŁ3łu!yRţ ^éT ”´!5GĄ˝(÷„ÚeŔg·ďĄÚRwT#“xÎŻtzŐš´p¤Á$ME(ĄqKô5 R0t7Ó¦W:­ć¤Aô˙şc0¤ý,=nŃ˝\6`JżKšŇhĎsţxĄł:t{B]v»ű\cęróp€Jf¬ôę>Ôä’†”„§1˝Ň©ť@Čđüý’N/ž•@aP'ŤÉ÷—|Ż©séR‹xÓ+ťRkr čö’ĂĆ)çŽ]ö:\t ÓŇ”0˝ŇéÁ©¨›˝`G@"ŔLXţ™±˝†U„śIEND®B`‚libcommons-io-java-2.4.orig/src/site/site.xml0000644000175000017500000000431512125050425020554 0ustar ebourgebourg Commons IO /images/io-logo-white.png /index.html libcommons-io-java-2.4.orig/src/test/0000755000175000017500000000000011765740035017112 5ustar ebourgebourglibcommons-io-java-2.4.orig/src/test/java/0000755000175000017500000000000011765740033020031 5ustar ebourgebourglibcommons-io-java-2.4.orig/src/test/java/org/0000755000175000017500000000000011765740033020620 5ustar ebourgebourglibcommons-io-java-2.4.orig/src/test/java/org/apache/0000755000175000017500000000000011765740033022041 5ustar ebourgebourglibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/0000755000175000017500000000000011765740033023514 5ustar ebourgebourglibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/0000755000175000017500000000000012125050425024111 5ustar ebourgebourglibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/FileCleanerTestCase.java0000644000175000017500000000245412125050425030566 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; @SuppressWarnings("deprecation") // testing deprecated class /** * This is used to test FileCleaner for correctness. * * @version $Id: FileCleanerTestCase.java 1302056 2012-03-18 03:03:38Z ggregory $ * @see FileCleaner */ public class FileCleanerTestCase extends FileCleaningTrackerTestCase { @Override protected FileCleaningTracker newInstance() { return FileCleaner.getInstance(); } public FileCleanerTestCase(String name) { super(name); } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/input/0000755000175000017500000000000012125050425025250 5ustar ebourgebourg././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/input/XmlStreamReaderUtilitiesTest.javalibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/input/XmlStreamReaderUtilitiesTest.j0000644000175000017500000004667212125050425033235 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.ByteArrayInputStream; import java.io.IOException; import org.junit.Test; /** * Test the Encoding Utilities part of {@link XmlStreamReader}. */ public class XmlStreamReaderUtilitiesTest { private static String RAWMGS1 = "encoding mismatch"; private static String RAWMGS2 = "unknown BOM"; private static String HTTPMGS1 = "BOM must be NULL"; private static String HTTPMGS2 = "encoding mismatch"; private static String HTTPMGS3 = "Invalid MIME"; private static String APPXML = "application/xml"; private static String APPXML_UTF8 = "application/xml;charset=UTF-8"; private static String APPXML_UTF16 = "application/xml;charset=UTF-16"; private static String APPXML_UTF32 = "application/xml;charset=UTF-32"; private static String APPXML_UTF16BE = "application/xml;charset=UTF-16BE"; private static String APPXML_UTF16LE = "application/xml;charset=UTF-16LE"; private static String APPXML_UTF32BE = "application/xml;charset=UTF-32BE"; private static String APPXML_UTF32LE = "application/xml;charset=UTF-32LE"; private static String TXTXML = "text/xml"; /** Test for {@link XmlStreamReader#getContentTypeEncoding(String)}. */ @Test public void testContentTypeEncoding() { checkContentTypeEncoding(null, null); checkContentTypeEncoding(null, ""); checkContentTypeEncoding(null, "application/xml"); checkContentTypeEncoding(null, "application/xml;"); checkContentTypeEncoding(null, "multipart/mixed;boundary=frontier"); checkContentTypeEncoding(null, "multipart/mixed;boundary='frontier'"); checkContentTypeEncoding(null, "multipart/mixed;boundary=\"frontier\""); checkContentTypeEncoding("UTF-16", "application/xml;charset=utf-16"); checkContentTypeEncoding("UTF-16", "application/xml;charset=UTF-16"); checkContentTypeEncoding("UTF-16", "application/xml;charset='UTF-16'"); checkContentTypeEncoding("UTF-16", "application/xml;charset=\"UTF-16\""); checkContentTypeEncoding("UTF-32", "application/xml;charset=utf-32"); checkContentTypeEncoding("UTF-32", "application/xml;charset=UTF-32"); checkContentTypeEncoding("UTF-32", "application/xml;charset='UTF-32'"); checkContentTypeEncoding("UTF-32", "application/xml;charset=\"UTF-32\""); } private void checkContentTypeEncoding(String expected, String httpContentType) { assertEquals("ContentTypeEncoding=[" + httpContentType + "]", expected, XmlStreamReader.getContentTypeEncoding(httpContentType)); } /** Test for {@link XmlStreamReader#getContentTypeEncoding(String)}. */ @Test public void testContentTypeMime() { checkContentTypeMime(null, null); checkContentTypeMime("", ""); checkContentTypeMime("application/xml", "application/xml"); checkContentTypeMime("application/xml", "application/xml;"); checkContentTypeMime("application/xml", "application/xml;charset=utf-16"); checkContentTypeMime("application/xml", "application/xml;charset=utf-32"); } private void checkContentTypeMime(String expected, String httpContentType) { assertEquals("ContentTypeMime=[" + httpContentType + "]", expected, XmlStreamReader.getContentTypeMime(httpContentType)); } /** Test for {@link XmlStreamReader#isAppXml(String)}. */ @Test public void testAppXml() { checkAppXml(false, null); checkAppXml(false, ""); checkAppXml(true, "application/xml"); checkAppXml(true, "application/xml-dtd"); checkAppXml(true, "application/xml-external-parsed-entity"); checkAppXml(true, "application/soap+xml"); checkAppXml(true, "application/atom+xml"); checkAppXml(false, "application/atomxml"); checkAppXml(false, "text/xml"); checkAppXml(false, "text/atom+xml"); checkAppXml(true, "application/xml-dtd"); checkAppXml(true, "application/xml-external-parsed-entity"); } private void checkAppXml(boolean expected, String mime) { assertEquals("Mime=[" + mime + "]", expected, XmlStreamReader.isAppXml(mime)); } /** Test for {@link XmlStreamReader#isTextXml(String)}. */ @Test public void testTextXml() { checkTextXml(false, null); checkTextXml(false, ""); checkTextXml(true, "text/xml"); checkTextXml(true, "text/xml-external-parsed-entity"); checkTextXml(true, "text/soap+xml"); checkTextXml(true, "text/atom+xml"); checkTextXml(false, "text/atomxml"); checkTextXml(false, "application/xml"); checkTextXml(false, "application/atom+xml"); } private void checkTextXml(boolean expected, String mime) { assertEquals("Mime=[" + mime + "]", expected, XmlStreamReader.isTextXml(mime)); } /** No BOM calculateRawEncoding() Test */ @Test public void testCalculateRawEncodingNoBOM() throws IOException { // No BOM Expected BOM Guess XML Default checkRawError(RAWMGS2, "UTF-32", null, null, null); // checkRawEncoding("UTF-8", null, null, null, null); checkRawEncoding("UTF-8", null, "UTF-16BE", null, null); /* why default & not Guess? */ checkRawEncoding("UTF-8", null, null, "UTF-16BE", null); /* why default & not XMLEnc? */ checkRawEncoding("UTF-8", null, "UTF-8", "UTF-8", "UTF-16BE"); // checkRawEncoding("UTF-16BE", null, "UTF-16BE", "UTF-16BE", null); checkRawEncoding("UTF-16BE", null, null, null, "UTF-16BE"); checkRawEncoding("UTF-16BE", null, "UTF-8", null, "UTF-16BE"); /* why default & not Guess? */ checkRawEncoding("UTF-16BE", null, null, "UTF-8", "UTF-16BE"); /* why default & not Guess? */ checkRawEncoding("UTF-16BE", null, "UTF-16BE", "UTF-16", null); checkRawEncoding("UTF-16LE", null, "UTF-16LE", "UTF-16", null); } /** BOM calculateRawEncoding() Test */ @Test public void testCalculateRawEncodingStandard() throws IOException { // Standard BOM Checks BOM Other Default testCalculateRawEncodingStandard("UTF-8", "UTF-16BE", "UTF-16LE"); testCalculateRawEncodingStandard("UTF-16BE", "UTF-8", "UTF-16LE"); testCalculateRawEncodingStandard("UTF-16LE", "UTF-8", "UTF-16BE"); } /** BOM calculateRawEncoding() Test */ @Test //@Ignore public void testCalculateRawEncodingStandardUtf32() throws IOException { // Standard BOM Checks BOM Other Default testCalculateRawEncodingStandard("UTF-8", "UTF-32BE", "UTF-32LE"); testCalculateRawEncodingStandard("UTF-32BE", "UTF-8", "UTF-32LE"); testCalculateRawEncodingStandard("UTF-32LE", "UTF-8", "UTF-32BE"); } private void testCalculateRawEncodingStandard(String bomEnc, String otherEnc, String defaultEnc) throws IOException { // Expected BOM Guess XMLEnc Default checkRawEncoding(bomEnc, bomEnc, null, null, defaultEnc); checkRawEncoding(bomEnc, bomEnc, bomEnc, null, defaultEnc); checkRawError(RAWMGS1, bomEnc, otherEnc, null, defaultEnc); checkRawEncoding(bomEnc, bomEnc, null, bomEnc, defaultEnc); checkRawError(RAWMGS1, bomEnc, null, otherEnc, defaultEnc); checkRawEncoding(bomEnc, bomEnc, bomEnc, bomEnc, defaultEnc); checkRawError(RAWMGS1, bomEnc, bomEnc, otherEnc, defaultEnc); checkRawError(RAWMGS1, bomEnc, otherEnc, bomEnc, defaultEnc); } /** Additional UTF-16 calculateRawEncoding() Test */ @Test public void testCalculateRawEncodingAdditonalUTF16() throws IOException { // BOM Guess XML Default checkRawError(RAWMGS1, "UTF-16BE", "UTF-16", null, null); checkRawEncoding("UTF-16BE", "UTF-16BE", null, "UTF-16", null); checkRawEncoding("UTF-16BE", "UTF-16BE", "UTF-16BE", "UTF-16", null); checkRawError(RAWMGS1, "UTF-16BE", null, "UTF-16LE", null); checkRawError(RAWMGS1, "UTF-16BE", "UTF-16BE", "UTF-16LE", null); checkRawError(RAWMGS1, "UTF-16LE", "UTF-16", null, null); checkRawEncoding("UTF-16LE", "UTF-16LE", null, "UTF-16", null); checkRawEncoding("UTF-16LE", "UTF-16LE", "UTF-16LE", "UTF-16", null); checkRawError(RAWMGS1, "UTF-16LE", null, "UTF-16BE", null); checkRawError(RAWMGS1, "UTF-16LE", "UTF-16LE", "UTF-16BE", null); } /** Additional UTF-32 calculateRawEncoding() Test */ @Test public void testCalculateRawEncodingAdditonalUTF32() throws IOException { // BOM Guess XML Default checkRawError(RAWMGS1, "UTF-32BE", "UTF-32", null, null); checkRawEncoding("UTF-32BE", "UTF-32BE", null, "UTF-32", null); checkRawEncoding("UTF-32BE", "UTF-32BE", "UTF-32BE", "UTF-32", null); checkRawError(RAWMGS1, "UTF-32BE", null, "UTF-32LE", null); checkRawError(RAWMGS1, "UTF-32BE", "UTF-32BE", "UTF-32LE", null); checkRawError(RAWMGS1, "UTF-32LE", "UTF-32", null, null); checkRawEncoding("UTF-32LE", "UTF-32LE", null, "UTF-32", null); checkRawEncoding("UTF-32LE", "UTF-32LE", "UTF-32LE", "UTF-32", null); checkRawError(RAWMGS1, "UTF-32LE", null, "UTF-32BE", null); checkRawError(RAWMGS1, "UTF-32LE", "UTF-32LE", "UTF-32BE", null); } private void checkRawEncoding(String expected, String bomEnc, String xmlGuessEnc, String xmlEnc, String defaultEncoding) throws IOException { StringBuilder builder = new StringBuilder(); builder.append("RawEncoding: ").append(bomEnc).append("], "); builder.append("bomEnc=[").append(bomEnc).append("], "); builder.append("xmlGuessEnc=[").append(xmlGuessEnc).append("], "); builder.append("xmlEnc=[").append(xmlEnc).append("], "); builder.append("defaultEncoding=[").append(defaultEncoding).append("],"); String encoding = calculateRawEncoding(bomEnc,xmlGuessEnc,xmlEnc, defaultEncoding); assertEquals(builder.toString(), expected, encoding); } protected String calculateRawEncoding(String bomEnc, String xmlGuessEnc, String xmlEnc, String defaultEncoding) throws IOException { MockXmlStreamReader mock = new MockXmlStreamReader(defaultEncoding); return mock.calculateRawEncoding(bomEnc, xmlGuessEnc, xmlEnc); } private void checkRawError(String msgSuffix, String bomEnc, String xmlGuessEnc, String xmlEnc, String defaultEncoding) { try { checkRawEncoding("XmlStreamReaderException", bomEnc, xmlGuessEnc, xmlEnc, defaultEncoding); fail("Expected XmlStreamReaderException"); } catch (XmlStreamReaderException e) { assertTrue("Msg Start: " + e.getMessage(), e.getMessage().startsWith("Invalid encoding")); assertTrue("Msg End: " + e.getMessage(), e.getMessage().endsWith(msgSuffix)); assertEquals("bomEnc", bomEnc, e.getBomEncoding()); assertEquals("xmlGuessEnc", xmlGuessEnc, e.getXmlGuessEncoding()); assertEquals("xmlEnc", xmlEnc, e.getXmlEncoding()); assertNull("ContentTypeEncoding", e.getContentTypeEncoding()); assertNull("ContentTypeMime", e.getContentTypeMime()); } catch (Exception e) { fail("Expected XmlStreamReaderException, but threw " + e); } } /** Test calculate HTTP Encoding */ @Test public void testCalculateHttpEncoding() throws IOException { // No BOM Expected Lenient cType BOM Guess XML Default checkHttpError(HTTPMGS3, true, null, null, null, null, null); checkHttpError(HTTPMGS3, false, null, null, null, "UTF-8", null); checkHttpEncoding("UTF-8", true, null, null, null, "UTF-8", null); checkHttpEncoding("UTF-16LE", true, null, null, null, "UTF-16LE", null); checkHttpError(HTTPMGS3, false, "text/css", null, null, null, null); checkHttpEncoding("US-ASCII", false, TXTXML, null, null, null, null); checkHttpEncoding("UTF-16BE", false, TXTXML, null, null, null, "UTF-16BE"); checkHttpEncoding("UTF-8", false, APPXML, null, null, null, null); checkHttpEncoding("UTF-16BE", false, APPXML, null, null, null, "UTF-16BE"); checkHttpEncoding("UTF-8", false, APPXML, "UTF-8", null, null, "UTF-16BE"); checkHttpEncoding("UTF-16LE", false, APPXML_UTF16LE, null, null, null, null); checkHttpEncoding("UTF-16BE", false, APPXML_UTF16BE, null, null, null, null); checkHttpError(HTTPMGS1, false, APPXML_UTF16LE, "UTF-16LE", null, null, null); checkHttpError(HTTPMGS1, false, APPXML_UTF16BE, "UTF-16BE", null, null, null); checkHttpError(HTTPMGS2, false, APPXML_UTF16, null, null, null, null); checkHttpError(HTTPMGS2, false, APPXML_UTF16, "UTF-8", null, null, null); checkHttpEncoding("UTF-16LE", false, APPXML_UTF16, "UTF-16LE", null, null, null); checkHttpEncoding("UTF-16BE", false, APPXML_UTF16, "UTF-16BE", null, null, null); checkHttpEncoding("UTF-8", false, APPXML_UTF8, null, null, null, null); checkHttpEncoding("UTF-8", false, APPXML_UTF8, "UTF-16BE", "UTF-16BE", "UTF-16BE", "UTF-16BE"); } /** Test calculate HTTP Encoding */ @Test //@Ignore public void testCalculateHttpEncodingUtf32() throws IOException { // No BOM Expected Lenient cType BOM Guess XML Default checkHttpEncoding("UTF-32LE", true, null, null, null, "UTF-32LE", null); checkHttpEncoding("UTF-32BE", false, TXTXML, null, null, null, "UTF-32BE"); checkHttpEncoding("UTF-32BE", false, APPXML, null, null, null, "UTF-32BE"); checkHttpEncoding("UTF-32LE", false, APPXML_UTF32LE, null, null, null, null); checkHttpEncoding("UTF-32BE", false, APPXML_UTF32BE, null, null, null, null); checkHttpError(HTTPMGS1, false, APPXML_UTF32LE, "UTF-32LE", null, null, null); checkHttpError(HTTPMGS1, false, APPXML_UTF32BE, "UTF-32BE", null, null, null); checkHttpError(HTTPMGS2, false, APPXML_UTF32, null, null, null, null); checkHttpError(HTTPMGS2, false, APPXML_UTF32, "UTF-8", null, null, null); checkHttpEncoding("UTF-32LE", false, APPXML_UTF32, "UTF-32LE", null, null, null); checkHttpEncoding("UTF-32BE", false, APPXML_UTF32, "UTF-32BE", null, null, null); checkHttpEncoding("UTF-8", false, APPXML_UTF8, "UTF-32BE", "UTF-32BE", "UTF-32BE", "UTF-32BE"); } private void checkHttpEncoding(String expected, boolean lenient, String httpContentType, String bomEnc, String xmlGuessEnc, String xmlEnc, String defaultEncoding) throws IOException { StringBuilder builder = new StringBuilder(); builder.append("HttpEncoding=[").append(bomEnc).append("], "); builder.append("lenient=[").append(lenient).append("], "); builder.append("httpContentType=[").append(httpContentType).append("], "); builder.append("bomEnc=[").append(bomEnc).append("], "); builder.append("xmlGuessEnc=[").append(xmlGuessEnc).append("], "); builder.append("xmlEnc=[").append(xmlEnc).append("], "); builder.append("defaultEncoding=[").append(defaultEncoding).append("],"); String encoding = calculateHttpEncoding(httpContentType, bomEnc, xmlGuessEnc, xmlEnc, lenient, defaultEncoding); assertEquals(builder.toString(), expected, encoding); } protected String calculateHttpEncoding(String httpContentType, String bomEnc, String xmlGuessEnc, String xmlEnc, boolean lenient, String defaultEncoding) throws IOException { MockXmlStreamReader mock = new MockXmlStreamReader(defaultEncoding); return mock.calculateHttpEncoding(httpContentType, bomEnc, xmlGuessEnc, xmlEnc, lenient); } private void checkHttpError(String msgSuffix, boolean lenient, String httpContentType, String bomEnc, String xmlGuessEnc, String xmlEnc, String defaultEncoding) { try { checkHttpEncoding("XmlStreamReaderException", lenient, httpContentType, bomEnc, xmlGuessEnc, xmlEnc, defaultEncoding); fail("Expected XmlStreamReaderException"); } catch (XmlStreamReaderException e) { assertTrue("Msg Start: " + e.getMessage(), e.getMessage().startsWith("Invalid encoding")); assertTrue("Msg End: " + e.getMessage(), e.getMessage().endsWith(msgSuffix)); assertEquals("bomEnc", bomEnc, e.getBomEncoding()); assertEquals("xmlGuessEnc", xmlGuessEnc, e.getXmlGuessEncoding()); assertEquals("xmlEnc", xmlEnc, e.getXmlEncoding()); assertEquals("ContentTypeEncoding", XmlStreamReader.getContentTypeEncoding(httpContentType), e.getContentTypeEncoding()); assertEquals("ContentTypeMime", XmlStreamReader.getContentTypeMime(httpContentType), e.getContentTypeMime()); } catch (Exception e) { fail("Expected XmlStreamReaderException, but threw " + e); } } /** Mock {@link XmlStreamReader} implementation */ private static class MockXmlStreamReader extends XmlStreamReader { MockXmlStreamReader(String defaultEncoding) throws IOException { super(new ByteArrayInputStream("".getBytes()), null, true, defaultEncoding); } } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/input/BoundedInputStreamTest.java0000644000175000017500000000760712125050425032541 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import java.io.ByteArrayInputStream; import junit.framework.TestCase; import org.apache.commons.io.IOUtils; /** * Tests for {@link BoundedInputStream}. * * @version $Id: BoundedInputStreamTest.java 1302056 2012-03-18 03:03:38Z ggregory $ */ public class BoundedInputStreamTest extends TestCase { public BoundedInputStreamTest(String name) { super(name); } /** * Test {@link BoundedInputStream#read()}. */ public void testReadSingle() throws Exception { BoundedInputStream bounded = null; byte[] helloWorld = "Hello World".getBytes(); byte[] hello = "Hello".getBytes(); // limit = length bounded = new BoundedInputStream(new ByteArrayInputStream(helloWorld), helloWorld.length); for (int i = 0; i < helloWorld.length; i++) { assertEquals("limit = length byte[" + i + "]", helloWorld[i], bounded.read()); } assertEquals("limit = length end", -1, bounded.read()); // limit > length bounded = new BoundedInputStream(new ByteArrayInputStream(helloWorld), helloWorld.length + 1); for (int i = 0; i < helloWorld.length; i++) { assertEquals("limit > length byte[" + i + "]", helloWorld[i], bounded.read()); } assertEquals("limit > length end", -1, bounded.read()); // limit < length bounded = new BoundedInputStream(new ByteArrayInputStream(helloWorld), hello.length); for (int i = 0; i < hello.length; i++) { assertEquals("limit < length byte[" + i + "]", hello[i], bounded.read()); } assertEquals("limit < length end", -1, bounded.read()); } /** * Test {@link BoundedInputStream#read(byte[], int, int)}. */ public void testReadArray() throws Exception { BoundedInputStream bounded = null; byte[] helloWorld = "Hello World".getBytes(); byte[] hello = "Hello".getBytes(); bounded = new BoundedInputStream(new ByteArrayInputStream(helloWorld)); compare("limit = -1", helloWorld, IOUtils.toByteArray(bounded)); bounded = new BoundedInputStream(new ByteArrayInputStream(helloWorld), 0); compare("limit = 0", new byte[0], IOUtils.toByteArray(bounded)); bounded = new BoundedInputStream(new ByteArrayInputStream(helloWorld), helloWorld.length); compare("limit = length", helloWorld, IOUtils.toByteArray(bounded)); bounded = new BoundedInputStream(new ByteArrayInputStream(helloWorld), helloWorld.length + 1); compare("limit > length", helloWorld, IOUtils.toByteArray(bounded)); bounded = new BoundedInputStream(new ByteArrayInputStream(helloWorld), helloWorld.length - 6); compare("limit < length", hello, IOUtils.toByteArray(bounded)); } /** * Compare byte arrays. */ private void compare(String msg, byte[] expected, byte[] actual) { assertEquals(msg + " length", expected.length, actual.length); for (int i = 0; i < expected.length; i++) { assertEquals(msg + " byte[" + i + "]", expected[i], actual[i]); } } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/input/SwappedDataInputStreamTest.javalibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/input/SwappedDataInputStreamTest.jav0000644000175000017500000001022412125050425033202 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import java.io.ByteArrayInputStream; import java.io.IOException; import junit.framework.TestCase; /** * Test for the SwappedDataInputStream. This also * effectively tests the underlying EndianUtils Stream methods. * * @version $Id: SwappedDataInputStreamTest.java 1302056 2012-03-18 03:03:38Z ggregory $ */ public class SwappedDataInputStreamTest extends TestCase { private SwappedDataInputStream sdis; private byte[] bytes; public SwappedDataInputStreamTest(String name) { super(name); } @Override public void setUp() { bytes = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }; ByteArrayInputStream bais = new ByteArrayInputStream( bytes ); this.sdis = new SwappedDataInputStream( bais ); } @Override public void tearDown() { this.sdis = null; } public void testReadBoolean() throws IOException { bytes = new byte[] { 0x00, 0x01, 0x02, }; ByteArrayInputStream bais = new ByteArrayInputStream( bytes ); SwappedDataInputStream sdis = new SwappedDataInputStream( bais ); assertEquals( false, sdis.readBoolean() ); assertEquals( true, sdis.readBoolean() ); assertEquals( true, sdis.readBoolean() ); } public void testReadByte() throws IOException { assertEquals( 0x01, this.sdis.readByte() ); } public void testReadChar() throws IOException { assertEquals( (char) 0x0201, this.sdis.readChar() ); } public void testReadDouble() throws IOException { assertEquals( Double.longBitsToDouble(0x0807060504030201L), this.sdis.readDouble(), 0 ); } public void testReadFloat() throws IOException { assertEquals( Float.intBitsToFloat(0x04030201), this.sdis.readFloat(), 0 ); } public void testReadFully() throws IOException { byte[] bytesIn = new byte[8]; this.sdis.readFully(bytesIn); for( int i=0; i<8; i++) { assertEquals( bytes[i], bytesIn[i] ); } } public void testReadInt() throws IOException { assertEquals( 0x04030201, this.sdis.readInt() ); } public void testReadLine() throws IOException { try { this.sdis.readLine(); fail("readLine should be unsupported. "); } catch(UnsupportedOperationException uoe) { } } public void testReadLong() throws IOException { assertEquals( 0x0807060504030201L, this.sdis.readLong() ); } public void testReadShort() throws IOException { assertEquals( (short) 0x0201, this.sdis.readShort() ); } public void testReadUnsignedByte() throws IOException { assertEquals( 0x01, this.sdis.readUnsignedByte() ); } public void testReadUnsignedShort() throws IOException { assertEquals( (short) 0x0201, this.sdis.readUnsignedShort() ); } public void testReadUTF() throws IOException { try { this.sdis.readUTF(); fail("readUTF should be unsupported. "); } catch(UnsupportedOperationException uoe) { } } public void testSkipBytes() throws IOException { this.sdis.skipBytes(4); assertEquals( 0x08070605, this.sdis.readInt() ); } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/input/TaggedInputStreamTest.java0000644000175000017500000001076412125050425032352 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.UUID; import junit.framework.TestCase; import org.apache.commons.io.TaggedIOException; /** * JUnit Test Case for {@link TaggedInputStream}. */ public class TaggedInputStreamTest extends TestCase { public void testEmptyStream() { try { InputStream stream = new TaggedInputStream(new ClosedInputStream()); assertEquals(0, stream.available()); assertEquals(-1, stream.read()); assertEquals(-1, stream.read(new byte[1])); assertEquals(-1, stream.read(new byte[1], 0, 1)); stream.close(); } catch (IOException e) { fail("Unexpected exception thrown"); } } public void testNormalStream() { try { InputStream stream = new TaggedInputStream( new ByteArrayInputStream(new byte[] { 'a', 'b', 'c' })); assertEquals(3, stream.available()); assertEquals('a', stream.read()); byte[] buffer = new byte[1]; assertEquals(1, stream.read(buffer)); assertEquals('b', buffer[0]); assertEquals(1, stream.read(buffer, 0, 1)); assertEquals('c', buffer[0]); assertEquals(-1, stream.read()); stream.close(); } catch (IOException e) { fail("Unexpected exception thrown"); } } public void testBrokenStream() { IOException exception = new IOException("test exception"); TaggedInputStream stream = new TaggedInputStream(new BrokenInputStream(exception)); // Test the available() method try { stream.available(); fail("Expected exception not thrown."); } catch (IOException e) { assertTrue(stream.isCauseOf(e)); try { stream.throwIfCauseOf(e); fail("Expected exception not thrown."); } catch (IOException e2) { assertEquals(exception, e2); } } // Test the read() method try { stream.read(); fail("Expected exception not thrown."); } catch (IOException e) { assertTrue(stream.isCauseOf(e)); try { stream.throwIfCauseOf(e); fail("Expected exception not thrown."); } catch (IOException e2) { assertEquals(exception, e2); } } // Test the close() method try { stream.close(); fail("Expected exception not thrown."); } catch (IOException e) { assertTrue(stream.isCauseOf(e)); try { stream.throwIfCauseOf(e); fail("Expected exception not thrown."); } catch (IOException e2) { assertEquals(exception, e2); } } } public void testOtherException() { IOException exception = new IOException("test exception"); InputStream closed = new ClosedInputStream(); TaggedInputStream stream = new TaggedInputStream(closed); assertFalse(stream.isCauseOf(exception)); assertFalse(stream.isCauseOf( new TaggedIOException(exception, UUID.randomUUID()))); try { stream.throwIfCauseOf(exception); } catch (IOException e) { fail("Unexpected exception thrown"); } try { stream.throwIfCauseOf( new TaggedIOException(exception, UUID.randomUUID())); } catch (IOException e) { fail("Unexpected exception thrown"); } } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/input/ReversedLinesFileReaderTestSimple.javalibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/input/ReversedLinesFileReaderTestSim0000644000175000017500000000511112125050425033177 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import static org.apache.commons.io.input.ReversedLinesFileReaderTestParamBlockSize.assertEqualsAndNoLineBreaks; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URISyntaxException; import org.junit.After; import org.junit.Test; public class ReversedLinesFileReaderTestSimple { private ReversedLinesFileReader reversedLinesFileReader; @After public void closeReader() { try { reversedLinesFileReader.close(); } catch(Exception e) { // ignore } } @Test public void testFileSizeIsExactMultipleOfBlockSize() throws URISyntaxException, IOException { int blockSize = 10; File testFile20Bytes = new File(this.getClass().getResource("/test-file-20byteslength.bin").toURI()); reversedLinesFileReader = new ReversedLinesFileReader(testFile20Bytes, blockSize, "ISO-8859-1"); String testLine = "123456789"; assertEqualsAndNoLineBreaks(testLine, reversedLinesFileReader.readLine()); assertEqualsAndNoLineBreaks(testLine, reversedLinesFileReader.readLine()); } @Test(expected=UnsupportedEncodingException.class) public void testUnsupportedEncodingUTF16() throws URISyntaxException, IOException { File testFileEmpty = new File(this.getClass().getResource("/test-file-empty.bin").toURI()); new ReversedLinesFileReader(testFileEmpty, 4096, "UTF-16"); } @Test(expected=UnsupportedEncodingException.class) public void testUnsupportedEncodingBig5() throws URISyntaxException, IOException { File testFileEncodingBig5 = new File(this.getClass().getResource("/test-file-empty.bin").toURI()); new ReversedLinesFileReader(testFileEncodingBig5, 4096, "Big5"); } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/input/TailerTest.java0000644000175000017500000003077512125050425030207 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.RandomAccessFile; import java.io.Writer; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.ScheduledThreadPoolExecutor; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.io.testtools.FileBasedTestCase; /** * Tests for {@link Tailer}. * * @version $Id: TailerTest.java 1348698 2012-06-11 01:09:58Z ggregory $ */ public class TailerTest extends FileBasedTestCase { private Tailer tailer; public TailerTest(String name) { super(name); } @Override protected void tearDown() throws Exception { if (tailer != null) { tailer.stop(); Thread.sleep(1000); } FileUtils.deleteDirectory(getTestDirectory()); Thread.sleep(1000); } public void testLongFile() throws Exception { long delay = 50; File file = new File(getTestDirectory(), "testLongFile.txt"); createFile(file, 0); Writer writer = new FileWriter(file, true); for (int i = 0; i < 100000; i++) { writer.write("LineLineLineLineLineLineLineLineLineLine\n"); } writer.write("SBTOURIST\n"); IOUtils.closeQuietly(writer); TestTailerListener listener = new TestTailerListener(); tailer = new Tailer(file, listener, delay, false); long start = System.currentTimeMillis(); Thread thread = new Thread(tailer); thread.start(); List lines = listener.getLines(); while (lines.isEmpty() || !lines.get(lines.size() - 1).equals("SBTOURIST")) { lines = listener.getLines(); } System.out.println("Elapsed: " + (System.currentTimeMillis() - start)); listener.clear(); } public void testBufferBreak() throws Exception { long delay = 50; File file = new File(getTestDirectory(), "testBufferBreak.txt"); createFile(file, 0); writeString(file, "SBTOURIST\n"); TestTailerListener listener = new TestTailerListener(); tailer = new Tailer(file, listener, delay, false, 1); Thread thread = new Thread(tailer); thread.start(); List lines = listener.getLines(); while (lines.isEmpty() || !lines.get(lines.size() - 1).equals("SBTOURIST")) { lines = listener.getLines(); } listener.clear(); } public void testTailerEof() throws Exception { // Create & start the Tailer long delay = 50; final File file = new File(getTestDirectory(), "tailer2-test.txt"); createFile(file, 0); final TestTailerListener listener = new TestTailerListener(); final Tailer tailer = new Tailer(file, listener, delay, false); final Thread thread = new Thread(tailer); thread.start(); // Write some lines to the file FileWriter writer = null; try { writeString(file, "Line"); Thread.sleep(delay * 2); List lines = listener.getLines(); assertEquals("1 line count", 0, lines.size()); writeString(file, " one\n"); Thread.sleep(delay * 2); lines = listener.getLines(); assertEquals("1 line count", 1, lines.size()); assertEquals("1 line 1", "Line one", lines.get(0)); listener.clear(); } finally { tailer.stop(); Thread.sleep(delay * 2); IOUtils.closeQuietly(writer); } } public void testTailer() throws Exception { // Create & start the Tailer long delayMillis = 50; final File file = new File(getTestDirectory(), "tailer1-test.txt"); createFile(file, 0); final TestTailerListener listener = new TestTailerListener(); String osname = System.getProperty("os.name"); boolean isWindows = osname.startsWith("Windows"); tailer = new Tailer(file, listener, delayMillis, false, isWindows); final Thread thread = new Thread(tailer); thread.start(); // Write some lines to the file write(file, "Line one", "Line two"); final long testDelayMillis = delayMillis * 10; Thread.sleep(testDelayMillis); List lines = listener.getLines(); assertEquals("1 line count", 2, lines.size()); assertEquals("1 line 1", "Line one", lines.get(0)); assertEquals("1 line 2", "Line two", lines.get(1)); listener.clear(); // Write another line to the file write(file, "Line three"); Thread.sleep(testDelayMillis); lines = listener.getLines(); assertEquals("2 line count", 1, lines.size()); assertEquals("2 line 3", "Line three", lines.get(0)); listener.clear(); // Check file does actually have all the lines lines = FileUtils.readLines(file); assertEquals("3 line count", 3, lines.size()); assertEquals("3 line 1", "Line one", lines.get(0)); assertEquals("3 line 2", "Line two", lines.get(1)); assertEquals("3 line 3", "Line three", lines.get(2)); // Delete & re-create file.delete(); boolean exists = file.exists(); assertFalse("File should not exist", exists); createFile(file, 0); Thread.sleep(testDelayMillis); // Write another line write(file, "Line four"); Thread.sleep(testDelayMillis); lines = listener.getLines(); assertEquals("4 line count", 1, lines.size()); assertEquals("4 line 3", "Line four", lines.get(0)); listener.clear(); // Stop tailer.stop(); tailer=null; thread.interrupt(); Thread.sleep(testDelayMillis); write(file, "Line five"); assertEquals("4 line count", 0, listener.getLines().size()); assertNull("Should not generate Exception", listener.exception); assertEquals("Expected init to be called", 1 , listener.initialised); assertEquals("fileNotFound should not be called", 0 , listener.notFound); assertEquals("fileRotated should be be called", 1 , listener.rotated); } @Override protected void createFile(File file, long size) throws IOException { super.createFile(file, size); // try to make sure file is found // (to stop continuum occasionally failing) RandomAccessFile reader = null; try { while (reader == null) { try { reader = new RandomAccessFile(file.getPath(), "r"); } catch (FileNotFoundException e) { } try { Thread.sleep(200L); } catch (InterruptedException e) { // ignore } } } finally { IOUtils.closeQuietly(reader); } } /** Append some lines to a file */ private void write(File file, String... lines) throws Exception { FileWriter writer = null; try { writer = new FileWriter(file, true); for (String line : lines) { writer.write(line + "\n"); } } finally { IOUtils.closeQuietly(writer); } } /** Append a string to a file */ private void writeString(File file, String ... strings) throws Exception { FileWriter writer = null; try { writer = new FileWriter(file, true); for (String string : strings) { writer.write(string); } } finally { IOUtils.closeQuietly(writer); } } public void testStopWithNoFile() throws Exception { final File file = new File(getTestDirectory(),"nosuchfile"); assertFalse("nosuchfile should not exist", file.exists()); final TestTailerListener listener = new TestTailerListener(); int delay = 100; int idle = 50; // allow time for thread to work tailer = Tailer.create(file, listener, delay, false); Thread.sleep(idle); tailer.stop(); tailer=null; Thread.sleep(delay+idle); assertNull("Should not generate Exception", listener.exception); assertEquals("Expected init to be called", 1 , listener.initialised); assertTrue("fileNotFound should be called", listener.notFound > 0); assertEquals("fileRotated should be not be called", 0 , listener.rotated); } public void testStopWithNoFileUsingExecutor() throws Exception { final File file = new File(getTestDirectory(),"nosuchfile"); assertFalse("nosuchfile should not exist", file.exists()); TestTailerListener listener = new TestTailerListener(); int delay = 100; int idle = 50; // allow time for thread to work tailer = new Tailer(file, listener, delay, false); Executor exec = new ScheduledThreadPoolExecutor(1); exec.execute(tailer); Thread.sleep(idle); tailer.stop(); tailer=null; Thread.sleep(delay+idle); assertNull("Should not generate Exception", listener.exception); assertEquals("Expected init to be called", 1 , listener.initialised); assertTrue("fileNotFound should be called", listener.notFound > 0); assertEquals("fileRotated should be not be called", 0 , listener.rotated); } public void testIO335() throws Exception { // test CR behaviour // Create & start the Tailer long delayMillis = 50; final File file = new File(getTestDirectory(), "tailer-testio334.txt"); createFile(file, 0); final TestTailerListener listener = new TestTailerListener(); tailer = new Tailer(file, listener, delayMillis, false); final Thread thread = new Thread(tailer); thread.start(); // Write some lines to the file writeString(file, "CRLF\r\n", "LF\n", "CR\r", "CRCR\r\r", "trail"); final long testDelayMillis = delayMillis * 10; Thread.sleep(testDelayMillis); List lines = listener.getLines(); assertEquals("line count", 4, lines.size()); assertEquals("line 1", "CRLF", lines.get(0)); assertEquals("line 2", "LF", lines.get(1)); assertEquals("line 3", "CR", lines.get(2)); assertEquals("line 4", "CRCR\r", lines.get(3)); // Stop tailer.stop(); tailer=null; thread.interrupt(); Thread.sleep(testDelayMillis); } /** * Test {@link TailerListener} implementation. */ private static class TestTailerListener implements TailerListener { // Must be synchronised because it is written by one thread and read by another private final List lines = Collections.synchronizedList(new ArrayList()); volatile Exception exception = null; volatile int notFound = 0; volatile int rotated = 0; volatile int initialised = 0; public void handle(String line) { lines.add(line); } public List getLines() { return lines; } public void clear() { lines.clear(); } public void handle(Exception e) { exception = e; } public void init(Tailer tailer) { initialised++; // not atomic, but OK because only updated here. } public void fileNotFound() { notFound++; // not atomic, but OK because only updated here. } public void fileRotated() { rotated++; // not atomic, but OK because only updated here. } } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/input/NullInputStreamTest.java0000644000175000017500000002100012125050425032052 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import junit.framework.TestCase; /** * JUnit Test Case for {@link NullInputStream}. * * @version $Id: NullInputStreamTest.java 1302748 2012-03-20 01:35:32Z ggregory $ */ public class NullInputStreamTest extends TestCase { /** Constructor */ public NullInputStreamTest(String name) { super(name); } /** Set up */ @Override protected void setUp() throws Exception { super.setUp(); } /** Tear Down */ @Override protected void tearDown() throws Exception { super.tearDown(); } /** * Test available() method. */ public void testRead() throws Exception { int size = 5; InputStream input = new TestNullInputStream(size); for (int i = 0; i < size; i++) { assertEquals("Check Size [" + i + "]", size - i, input.available()); assertEquals("Check Value [" + i + "]", i, input.read()); } assertEquals("Available after contents all read", 0, input.available()); // Check availbale is zero after End of file assertEquals("End of File", -1, input.read()); assertEquals("Available after End of File", 0, input.available()); // Test reading after the end of file try { int result = input.read(); fail("Should have thrown an IOException, byte=[" + result + "]"); } catch (IOException e) { assertEquals("Read after end of file", e.getMessage()); } // Close - should reset input.close(); assertEquals("Available after close", size, input.available()); } /** * Test read(byte[]) method. */ public void testReadByteArray() throws Exception { byte[] bytes = new byte[10]; InputStream input = new TestNullInputStream(15); // Read into array int count1 = input.read(bytes); assertEquals("Read 1", bytes.length, count1); for (int i = 0; i < count1; i++) { assertEquals("Check Bytes 1", i, bytes[i]); } // Read into array int count2 = input.read(bytes); assertEquals("Read 2", 5, count2); for (int i = 0; i < count2; i++) { assertEquals("Check Bytes 2", count1 + i, bytes[i]); } // End of File int count3 = input.read(bytes); assertEquals("Read 3 (EOF)", -1, count3); // Test reading after the end of file try { int count4 = input.read(bytes); fail("Should have thrown an IOException, byte=[" + count4 + "]"); } catch (IOException e) { assertEquals("Read after end of file", e.getMessage()); } // reset by closing input.close(); // Read into array using offset & length int offset = 2; int lth = 4; int count5 = input.read(bytes, offset, lth); assertEquals("Read 5", lth, count5); for (int i = offset; i < lth; i++) { assertEquals("Check Bytes 2", i, bytes[i]); } } /** * Test when configured to throw an EOFException at the end of file * (rather than return -1). */ public void testEOFException() throws Exception { InputStream input = new TestNullInputStream(2, false, true); assertEquals("Read 1", 0, input.read()); assertEquals("Read 2", 1, input.read()); try { int result = input.read(); fail("Should have thrown an EOFException, byte=[" + result + "]"); } catch (EOFException e) { // expected } } /** * Test mark() and reset() methods. */ public void testMarkAndReset() throws Exception { int position = 0; int readlimit = 10; InputStream input = new TestNullInputStream(100, true, false); assertTrue("Mark Should be Supported", input.markSupported()); // No Mark try { input.reset(); fail("Read limit exceeded, expected IOException "); } catch (IOException e) { assertEquals("No Mark IOException message", "No position has been marked", e.getMessage()); } for (; position < 3; position++) { assertEquals("Read Before Mark [" + position +"]", position, input.read()); } // Mark input.mark(readlimit); // Read further for (int i = 0; i < 3; i++) { assertEquals("Read After Mark [" + i +"]", position + i, input.read()); } // Reset input.reset(); // Read From marked position for (int i = 0; i < readlimit + 1; i++) { assertEquals("Read After Reset [" + i +"]", position + i, input.read()); } // Reset after read limit passed try { input.reset(); fail("Read limit exceeded, expected IOException "); } catch (IOException e) { assertEquals("Read limit IOException message", "Marked position [" + position + "] is no longer valid - passed the read limit [" + readlimit + "]", e.getMessage()); } } /** * Test mark() not supported. */ public void testMarkNotSupported() throws Exception { InputStream input = new TestNullInputStream(100, false, true); assertFalse("Mark Should NOT be Supported", input.markSupported()); try { input.mark(5); fail("mark() should throw UnsupportedOperationException"); } catch (UnsupportedOperationException e) { assertEquals("mark() error message", "Mark not supported", e.getMessage()); } try { input.reset(); fail("reset() should throw UnsupportedOperationException"); } catch (UnsupportedOperationException e) { assertEquals("reset() error message", "Mark not supported", e.getMessage()); } } /** * Test skip() method. */ public void testSkip() throws Exception { InputStream input = new TestNullInputStream(10, true, false); assertEquals("Read 1", 0, input.read()); assertEquals("Read 2", 1, input.read()); assertEquals("Skip 1", 5, input.skip(5)); assertEquals("Read 3", 7, input.read()); assertEquals("Skip 2", 2, input.skip(5)); // only 2 left to skip assertEquals("Skip 3 (EOF)", -1, input.skip(5)); // End of file try { input.skip(5); // fail("Expected IOException for skipping after end of file"); } catch (IOException e) { assertEquals("Skip after EOF IOException message", "Skip after end of file", e.getMessage()); } } // ------------- Test NullInputStream implementation ------------- private static final class TestNullInputStream extends NullInputStream { public TestNullInputStream(int size) { super(size); } public TestNullInputStream(int size, boolean markSupported, boolean throwEofException) { super(size, markSupported, throwEofException); } @Override protected int processByte() { return (int)getPosition() - 1; } @Override protected void processBytes(byte[] bytes, int offset, int length) { int startPos = (int)getPosition() - length; for (int i = offset; i < length; i++) { bytes[i] = (byte)(startPos + i); } } } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/input/AutoCloseInputStreamTest.java0000644000175000017500000000637512125050425033060 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import junit.framework.TestCase; /** * JUnit Test Case for {@link AutoCloseInputStream}. */ public class AutoCloseInputStreamTest extends TestCase { private byte[] data; private InputStream stream; private boolean closed; @Override protected void setUp() { data = new byte[] { 'x', 'y', 'z' }; stream = new AutoCloseInputStream(new ByteArrayInputStream(data) { @Override public void close() { closed = true; } }); closed = false; } /** * Test the close() method. */ public void testClose() throws IOException { stream.close(); assertTrue("closed", closed); assertEquals("read()", -1, stream.read()); } /** * Test the read() method. */ public void testRead() throws IOException { for (byte element : data) { assertEquals("read()", element, stream.read()); assertFalse("closed", closed); } assertEquals("read()", -1, stream.read()); assertTrue("closed", closed); } /** * Test the read(b) method. */ public void testReadBuffer() throws IOException { byte[] b = new byte[data.length * 2]; int total = 0; for (int n = 0; n != -1; n = stream.read(b)) { assertFalse("closed", closed); for (int i = 0; i < n; i++) { assertEquals("read(b)", data[total + i], b[i]); } total += n; } assertEquals("read(b)", data.length, total); assertTrue("closed", closed); assertEquals("read(b)", -1, stream.read(b)); } /** * Test the read(b, off, len) method. */ public void testReadBufferOffsetLength() throws IOException { byte[] b = new byte[data.length * 2]; int total = 0; for (int n = 0; n != -1; n = stream.read(b, total, b.length - total)) { assertFalse("closed", closed); total += n; } assertEquals("read(b, off, len)", data.length, total); for (int i = 0; i < data.length; i++) { assertEquals("read(b, off, len)", data[i], b[i]); } assertTrue("closed", closed); assertEquals("read(b, off, len)", -1, stream.read(b, 0, b.length)); } } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootlibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/input/ReversedLinesFileReaderTestParamBlockSize.javalibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/input/ReversedLinesFileReaderTestPar0000644000175000017500000002222412125050425033175 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URISyntaxException; import java.util.Arrays; import java.util.Collection; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class ReversedLinesFileReaderTestParamBlockSize { private static final String UTF_8 = "UTF-8"; private static final String ISO_8859_1 = "ISO-8859-1"; @SuppressWarnings("boxing") @Parameters // small and uneven block sizes are not used in reality but are good to show that the algorithm is solid public static Collection blockSizes() { return Arrays.asList(new Integer[][] { {1}, {3}, {8}, {256}, {4096} }); } private ReversedLinesFileReader reversedLinesFileReader; private int testParamBlockSize; public ReversedLinesFileReaderTestParamBlockSize(Integer testWithBlockSize) { testParamBlockSize = testWithBlockSize.intValue(); } // Strings are escaped in constants to avoid java source encoding issues (source file enc is UTF-8): // "A Test Line. Special chars: ÄäĂĹ“ĂÂĽĂ–Ă¶ĂŸ ĂĆ’Ă¡Ă©Ă­Ă¯çñ ©µ¥£±²®" private static final String TEST_LINE = "A Test Line. Special chars: \u00C4\u00E4\u00DC\u00FC\u00D6\u00F6\u00DF \u00C3\u00E1\u00E9\u00ED\u00EF\u00E7\u00F1\u00C2 \u00A9\u00B5\u00A5\u00A3\u00B1\u00B2\u00AE"; // Hiragana letters: ����� private static final String TEST_LINE_SHIFT_JIS1 = "Hiragana letters: \u3041\u3042\u3043\u3044\u3045"; // Kanji letters: 明輸�京 private static final String TEST_LINE_SHIFT_JIS2 = "Kanji letters: \u660E\u8F38\u5B50\u4EAC"; @After public void closeReader() { try { reversedLinesFileReader.close(); } catch(Exception e) { // ignore } } @Test public void testIsoFileDefaults() throws URISyntaxException, IOException { File testFileIso = new File(this.getClass().getResource("/test-file-iso8859-1.bin").toURI()); reversedLinesFileReader = new ReversedLinesFileReader(testFileIso, testParamBlockSize, ISO_8859_1); assertFileWithShrinkingTestLines(reversedLinesFileReader); } @Test public void testUTF8FileWindowsBreaks() throws URISyntaxException, IOException { File testFileIso = new File(this.getClass().getResource("/test-file-utf8-win-linebr.bin").toURI()); reversedLinesFileReader = new ReversedLinesFileReader(testFileIso, testParamBlockSize, UTF_8); assertFileWithShrinkingTestLines(reversedLinesFileReader); } @Test public void testUTF8FileCRBreaks() throws URISyntaxException, IOException { File testFileIso = new File(this.getClass().getResource("/test-file-utf8-cr-only.bin").toURI()); reversedLinesFileReader = new ReversedLinesFileReader(testFileIso, testParamBlockSize, UTF_8); assertFileWithShrinkingTestLines(reversedLinesFileReader); } @Test public void testUTF8File() throws URISyntaxException, IOException { File testFileIso = new File(this.getClass().getResource("/test-file-utf8.bin").toURI()); reversedLinesFileReader = new ReversedLinesFileReader(testFileIso, testParamBlockSize, UTF_8); assertFileWithShrinkingTestLines(reversedLinesFileReader); } @Test public void testEmptyFile() throws URISyntaxException, IOException { File testFileEmpty = new File(this.getClass().getResource("/test-file-empty.bin").toURI()); reversedLinesFileReader = new ReversedLinesFileReader(testFileEmpty, testParamBlockSize, UTF_8); assertNull(reversedLinesFileReader.readLine()); } @Test public void testUTF16BEFile() throws URISyntaxException, IOException { File testFileUTF16BE = new File(this.getClass().getResource("/test-file-utf16be.bin").toURI()); reversedLinesFileReader = new ReversedLinesFileReader(testFileUTF16BE, testParamBlockSize, "UTF-16BE"); assertFileWithShrinkingTestLines(reversedLinesFileReader); } @Test public void testUTF16LEFile() throws URISyntaxException, IOException { File testFileUTF16LE = new File(this.getClass().getResource("/test-file-utf16le.bin").toURI()); reversedLinesFileReader = new ReversedLinesFileReader(testFileUTF16LE, testParamBlockSize, "UTF-16LE"); assertFileWithShrinkingTestLines(reversedLinesFileReader); } @Test public void testShiftJISFile() throws URISyntaxException, IOException { File testFileShiftJIS = new File(this.getClass().getResource("/test-file-shiftjis.bin").toURI()); reversedLinesFileReader = new ReversedLinesFileReader(testFileShiftJIS, testParamBlockSize, "Shift_JIS"); assertEqualsAndNoLineBreaks(TEST_LINE_SHIFT_JIS2, reversedLinesFileReader.readLine()); assertEqualsAndNoLineBreaks(TEST_LINE_SHIFT_JIS1, reversedLinesFileReader.readLine()); } @Test // this test is run 3x for same block size as we want to test with 10 public void testFileSizeIsExactMultipleOfBlockSize() throws URISyntaxException, IOException { int blockSize = 10; File testFile20Bytes = new File(this.getClass().getResource("/test-file-20byteslength.bin").toURI()); reversedLinesFileReader = new ReversedLinesFileReader(testFile20Bytes, blockSize, ISO_8859_1); String testLine = "123456789"; assertEqualsAndNoLineBreaks(testLine, reversedLinesFileReader.readLine()); assertEqualsAndNoLineBreaks(testLine, reversedLinesFileReader.readLine()); } @Test public void testUTF8FileWindowsBreaksSmallBlockSize2VerifyBlockSpanningNewLines() throws URISyntaxException, IOException { File testFileUtf8 = new File(this.getClass().getResource("/test-file-utf8-win-linebr.bin").toURI()); reversedLinesFileReader = new ReversedLinesFileReader(testFileUtf8, testParamBlockSize, UTF_8); assertFileWithShrinkingTestLines(reversedLinesFileReader); } @Test public void testIsoFileManyWindowsBreaksSmallBlockSize2VerifyBlockSpanningNewLines() throws URISyntaxException, IOException { File testFileIso = new File(this.getClass().getResource("/test-file-iso8859-1-shortlines-win-linebr.bin").toURI()); reversedLinesFileReader = new ReversedLinesFileReader(testFileIso, testParamBlockSize, ISO_8859_1); for(int i=3;i>0;i--) { for(int j=1;j<=3;j++) { assertEqualsAndNoLineBreaks("", reversedLinesFileReader.readLine()); } assertEqualsAndNoLineBreaks(""+i, reversedLinesFileReader.readLine()); } } @Test(expected=UnsupportedEncodingException.class) public void testUnsupportedEncodingUTF16() throws URISyntaxException, IOException { File testFileEmpty = new File(this.getClass().getResource("/test-file-empty.bin").toURI()); new ReversedLinesFileReader(testFileEmpty, testParamBlockSize, "UTF-16"); } @Test(expected=UnsupportedEncodingException.class) public void testUnsupportedEncodingBig5() throws URISyntaxException, IOException { File testFileEncodingBig5 = new File(this.getClass().getResource("/test-file-empty.bin").toURI()); new ReversedLinesFileReader(testFileEncodingBig5, testParamBlockSize, "Big5"); } private void assertFileWithShrinkingTestLines(ReversedLinesFileReader reversedLinesFileReader) throws IOException { String line = null; int lineCount = 0; while ((line = reversedLinesFileReader.readLine()) != null) { lineCount++; assertEqualsAndNoLineBreaks("Line "+lineCount+" is not matching", TEST_LINE.substring(0, lineCount), line); } } static void assertEqualsAndNoLineBreaks(String msg, String expected, String actual) { if(actual!=null) { assertFalse("Line contains \\n: line="+actual, actual.contains("\n")); assertFalse("Line contains \\r: line="+actual, actual.contains("\r")); } assertEquals(msg, expected, actual); } static void assertEqualsAndNoLineBreaks(String expected, String actual) { assertEqualsAndNoLineBreaks(null, expected, actual); } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/input/ReversedLinesFileReaderTestParamFile.javalibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/input/ReversedLinesFileReaderTestPar0000644000175000017500000001017612125050425033200 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import static org.junit.Assert.assertEquals; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.URISyntaxException; import java.util.Arrays; import java.util.Collection; import java.util.Stack; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; /** * Test checks symmetric behaviour with BufferedReader * */ @RunWith(Parameterized.class) public class ReversedLinesFileReaderTestParamFile { @Parameters public static Collection blockSizes() { return Arrays.asList(new Object[][] { {"test-file-20byteslength.bin", "ISO_8859_1", null}, {"test-file-iso8859-1-shortlines-win-linebr.bin", "ISO_8859_1", null}, {"test-file-iso8859-1.bin", "ISO_8859_1", null}, {"test-file-shiftjis.bin", "Shift_JIS", null}, {"test-file-utf16be.bin", "UTF-16BE", null}, {"test-file-utf16le.bin", "UTF-16LE", null}, {"test-file-utf8-cr-only.bin", "UTF-8", null}, {"test-file-utf8-win-linebr.bin", "UTF-8", null}, {"test-file-utf8-win-linebr.bin", "UTF-8", Integer.valueOf(1)}, {"test-file-utf8-win-linebr.bin", "UTF-8", Integer.valueOf(2)}, {"test-file-utf8-win-linebr.bin", "UTF-8", Integer.valueOf(3)}, {"test-file-utf8-win-linebr.bin", "UTF-8", Integer.valueOf(4)}, {"test-file-utf8.bin", "UTF-8", null}, }); } private ReversedLinesFileReader reversedLinesFileReader; private BufferedReader bufferedReader; private final String fileName; private final String encoding; private final int buffSize; public ReversedLinesFileReaderTestParamFile(String fileName, String encoding, Integer buffsize) { this.fileName = fileName; this.encoding = encoding; this.buffSize = buffsize == null ? 4096 : buffsize.intValue(); } @Test public void testDataIntegrityWithBufferedReader() throws URISyntaxException, IOException { File testFileIso = new File(this.getClass().getResource("/"+fileName).toURI()); reversedLinesFileReader = new ReversedLinesFileReader(testFileIso, buffSize, encoding); Stack lineStack = new Stack(); bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(testFileIso), encoding)); String line = null; // read all lines in normal order while((line = bufferedReader.readLine())!=null) { lineStack.push(line); } // read in reverse order and compare with lines from stack while((line = reversedLinesFileReader.readLine())!=null) { String lineFromBufferedReader = lineStack.pop(); assertEquals(lineFromBufferedReader, line); } } @After public void closeReader() { try { bufferedReader.close(); } catch(Exception e) { // ignore } try { reversedLinesFileReader.close(); } catch(Exception e) { // ignore } } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/input/CountingInputStreamTest.java0000644000175000017500000001520312125050425032736 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.OutputStream; import junit.framework.TestCase; import org.apache.commons.io.IOUtils; import org.apache.commons.io.output.NullOutputStream; /** * Tests the CountingInputStream. * * @version $Id: CountingInputStreamTest.java 1302056 2012-03-18 03:03:38Z ggregory $ */ public class CountingInputStreamTest extends TestCase { public CountingInputStreamTest(String name) { super(name); } public void testCounting() throws Exception { String text = "A piece of text"; byte[] bytes = text.getBytes(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); CountingInputStream cis = new CountingInputStream(bais); // have to declare this larger as we're going to read // off the end of the stream and input stream seems // to do bounds checking byte[] result = new byte[21]; byte[] ba = new byte[5]; int found = cis.read(ba); System.arraycopy(ba, 0, result, 0, 5); assertEquals( found, cis.getCount() ); int value = cis.read(); found++; result[5] = (byte)value; assertEquals( found, cis.getCount() ); found += cis.read(result, 6, 5); assertEquals( found, cis.getCount() ); found += cis.read(result, 11, 10); // off the end assertEquals( found, cis.getCount() ); // trim to get rid of the 6 empty values String textResult = new String(result).trim(); assertEquals(textResult, text); } /** * Test for files > 2GB in size - see issue IO-84 */ public void testLargeFiles_IO84() throws Exception { long size = (long)Integer.MAX_VALUE + (long)1; NullInputStream mock = new NullInputStream(size); CountingInputStream cis = new CountingInputStream(mock); OutputStream out = new NullOutputStream(); // Test integer methods IOUtils.copyLarge(cis, out); try { cis.getCount(); fail("Expected getCount() to throw an ArithmeticException"); } catch (ArithmeticException ae) { // expected result } try { cis.resetCount(); fail("Expected resetCount() to throw an ArithmeticException"); } catch (ArithmeticException ae) { // expected result } mock.close(); // Test long methods IOUtils.copyLarge(cis, out); assertEquals("getByteCount()", size, cis.getByteCount()); assertEquals("resetByteCount()", size, cis.resetByteCount()); } public void testResetting() throws Exception { String text = "A piece of text"; byte[] bytes = text.getBytes(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); CountingInputStream cis = new CountingInputStream(bais); byte[] result = new byte[bytes.length]; int found = cis.read(result, 0, 5); assertEquals( found, cis.getCount() ); int count = cis.resetCount(); found = cis.read(result, 6, 5); assertEquals( found, count ); } public void testZeroLength1() throws Exception { ByteArrayInputStream bais = new ByteArrayInputStream(new byte[0]); CountingInputStream cis = new CountingInputStream(bais); int found = cis.read(); assertEquals(-1, found); assertEquals(0, cis.getCount()); } public void testZeroLength2() throws Exception { ByteArrayInputStream bais = new ByteArrayInputStream(new byte[0]); CountingInputStream cis = new CountingInputStream(bais); byte[] result = new byte[10]; int found = cis.read(result); assertEquals(-1, found); assertEquals(0, cis.getCount()); } public void testZeroLength3() throws Exception { ByteArrayInputStream bais = new ByteArrayInputStream(new byte[0]); CountingInputStream cis = new CountingInputStream(bais); byte[] result = new byte[10]; int found = cis.read(result, 0, 5); assertEquals(-1, found); assertEquals(0, cis.getCount()); } public void testEOF1() throws Exception { ByteArrayInputStream bais = new ByteArrayInputStream(new byte[2]); CountingInputStream cis = new CountingInputStream(bais); int found = cis.read(); assertEquals(0, found); assertEquals(1, cis.getCount()); found = cis.read(); assertEquals(0, found); assertEquals(2, cis.getCount()); found = cis.read(); assertEquals(-1, found); assertEquals(2, cis.getCount()); } public void testEOF2() throws Exception { ByteArrayInputStream bais = new ByteArrayInputStream(new byte[2]); CountingInputStream cis = new CountingInputStream(bais); byte[] result = new byte[10]; int found = cis.read(result); assertEquals(2, found); assertEquals(2, cis.getCount()); } public void testEOF3() throws Exception { ByteArrayInputStream bais = new ByteArrayInputStream(new byte[2]); CountingInputStream cis = new CountingInputStream(bais); byte[] result = new byte[10]; int found = cis.read(result, 0, 5); assertEquals(2, found); assertEquals(2, cis.getCount()); } public void testSkipping() throws IOException { String text = "Hello World!"; byte[] bytes = text.getBytes(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); CountingInputStream cis = new CountingInputStream(bais); assertEquals(6,cis.skip(6)); assertEquals(6,cis.getCount()); final byte[] result = new byte[6]; cis.read(result); assertEquals("World!",new String(result)); assertEquals(12,cis.getCount()); } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/input/NullReaderTest.java0000644000175000017500000002027512125050425031016 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import java.io.EOFException; import java.io.IOException; import java.io.Reader; import junit.framework.TestCase; /** * JUnit Test Case for {@link NullReader}. * * @version $Id: NullReaderTest.java 1302748 2012-03-20 01:35:32Z ggregory $ */ public class NullReaderTest extends TestCase { /** Constructor */ public NullReaderTest(String name) { super(name); } /** Set up */ @Override protected void setUp() throws Exception { super.setUp(); } /** Tear Down */ @Override protected void tearDown() throws Exception { super.tearDown(); } /** * Test available() method. */ public void testRead() throws Exception { int size = 5; TestNullReader reader = new TestNullReader(size); for (int i = 0; i < size; i++) { assertEquals("Check Value [" + i + "]", i, reader.read()); } // Check End of File assertEquals("End of File", -1, reader.read()); // Test reading after the end of file try { int result = reader.read(); fail("Should have thrown an IOException, value=[" + result + "]"); } catch (IOException e) { assertEquals("Read after end of file", e.getMessage()); } // Close - should reset reader.close(); assertEquals("Available after close", 0, reader.getPosition()); } /** * Test read(char[]) method. */ public void testReadCharArray() throws Exception { char[] chars = new char[10]; Reader reader = new TestNullReader(15); // Read into array int count1 = reader.read(chars); assertEquals("Read 1", chars.length, count1); for (int i = 0; i < count1; i++) { assertEquals("Check Chars 1", i, chars[i]); } // Read into array int count2 = reader.read(chars); assertEquals("Read 2", 5, count2); for (int i = 0; i < count2; i++) { assertEquals("Check Chars 2", count1 + i, chars[i]); } // End of File int count3 = reader.read(chars); assertEquals("Read 3 (EOF)", -1, count3); // Test reading after the end of file try { int count4 = reader.read(chars); fail("Should have thrown an IOException, value=[" + count4 + "]"); } catch (IOException e) { assertEquals("Read after end of file", e.getMessage()); } // reset by closing reader.close(); // Read into array using offset & length int offset = 2; int lth = 4; int count5 = reader.read(chars, offset, lth); assertEquals("Read 5", lth, count5); for (int i = offset; i < lth; i++) { assertEquals("Check Chars 3", i, chars[i]); } } /** * Test when configured to throw an EOFException at the end of file * (rather than return -1). */ public void testEOFException() throws Exception { Reader reader = new TestNullReader(2, false, true); assertEquals("Read 1", 0, reader.read()); assertEquals("Read 2", 1, reader.read()); try { int result = reader.read(); fail("Should have thrown an EOFException, value=[" + result + "]"); } catch (EOFException e) { // expected } } /** * Test mark() and reset() methods. */ public void testMarkAndReset() throws Exception { int position = 0; int readlimit = 10; Reader reader = new TestNullReader(100, true, false); assertTrue("Mark Should be Supported", reader.markSupported()); // No Mark try { reader.reset(); fail("Read limit exceeded, expected IOException "); } catch (IOException e) { assertEquals("No Mark IOException message", "No position has been marked", e.getMessage()); } for (; position < 3; position++) { assertEquals("Read Before Mark [" + position +"]", position, reader.read()); } // Mark reader.mark(readlimit); // Read further for (int i = 0; i < 3; i++) { assertEquals("Read After Mark [" + i +"]", position + i, reader.read()); } // Reset reader.reset(); // Read From marked position for (int i = 0; i < readlimit + 1; i++) { assertEquals("Read After Reset [" + i +"]", position + i, reader.read()); } // Reset after read limit passed try { reader.reset(); fail("Read limit exceeded, expected IOException "); } catch (IOException e) { assertEquals("Read limit IOException message", "Marked position [" + position + "] is no longer valid - passed the read limit [" + readlimit + "]", e.getMessage()); } } /** * Test mark() not supported. */ public void testMarkNotSupported() throws Exception { Reader reader = new TestNullReader(100, false, true); assertFalse("Mark Should NOT be Supported", reader.markSupported()); try { reader.mark(5); fail("mark() should throw UnsupportedOperationException"); } catch (UnsupportedOperationException e) { assertEquals("mark() error message", "Mark not supported", e.getMessage()); } try { reader.reset(); fail("reset() should throw UnsupportedOperationException"); } catch (UnsupportedOperationException e) { assertEquals("reset() error message", "Mark not supported", e.getMessage()); } } /** * Test skip() method. */ public void testSkip() throws Exception { Reader reader = new TestNullReader(10, true, false); assertEquals("Read 1", 0, reader.read()); assertEquals("Read 2", 1, reader.read()); assertEquals("Skip 1", 5, reader.skip(5)); assertEquals("Read 3", 7, reader.read()); assertEquals("Skip 2", 2, reader.skip(5)); // only 2 left to skip assertEquals("Skip 3 (EOF)", -1, reader.skip(5)); // End of file try { reader.skip(5); // fail("Expected IOException for skipping after end of file"); } catch (IOException e) { assertEquals("Skip after EOF IOException message", "Skip after end of file", e.getMessage()); } } // ------------- Test NullReader implementation ------------- private static final class TestNullReader extends NullReader { public TestNullReader(int size) { super(size); } public TestNullReader(int size, boolean markSupported, boolean throwEofException) { super(size, markSupported, throwEofException); } @Override protected int processChar() { return (int)getPosition() - 1; } @Override protected void processChars(char[] chars, int offset, int length) { int startPos = (int)getPosition() - length; for (int i = offset; i < length; i++) { chars[i] = (char)(startPos + i); } } } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/input/BOMInputStreamTest.java0000644000175000017500000003510512125050425031570 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import junit.framework.TestCase; import org.apache.commons.io.ByteOrderMark; import org.junit.Assert; /** * Test case for {@link BOMInputStream}. * * @version $Id: BOMInputStreamTest.java 1309619 2012-04-04 23:04:27Z sebb $ */ public class BOMInputStreamTest extends TestCase { //---------------------------------------------------------------------------- // Support code //---------------------------------------------------------------------------- /** * Creates the underlying data stream, with or without BOM. */ public InputStream createDataStream(byte[] baseData, boolean addBOM) { byte[] data = baseData; if (addBOM) { data = new byte[baseData.length + 3]; data[0] = (byte) 0xEF; data[1] = (byte) 0xBB; data[2] = (byte) 0xBF; System.arraycopy(baseData, 0, data, 3, baseData.length); } return new ByteArrayInputStream(data); } private void assertData(byte[] expected, byte[] actual, int len) throws Exception { assertEquals("length", expected.length, len); for (int ii = 0; ii < expected.length; ii++) { assertEquals("byte " + ii, expected[ii], actual[ii]); } } /** * A mock InputStream that expects close() to be called. */ private static class ExpectCloseInputStream extends InputStream { private boolean _closeCalled; @Override public void close() throws IOException { _closeCalled = true; } @Override public int read() throws IOException { return -1; } public void assertCloseCalled() { assertTrue(_closeCalled); } } //---------------------------------------------------------------------------- // Test cases //---------------------------------------------------------------------------- // make sure that our support code works as expected public void testSupportCode() throws Exception { InputStream in = createDataStream(new byte[] { 'A', 'B' }, true); byte[] buf = new byte[1024]; int len = in.read(buf); assertEquals(5, len); assertEquals(0xEF, buf[0] & 0xFF); assertEquals(0xBB, buf[1] & 0xFF); assertEquals(0xBF, buf[2] & 0xFF); assertEquals('A', buf[3] & 0xFF); assertEquals('B', buf[4] & 0xFF); assertData( new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF, 'A', 'B' }, buf, len); } public void testReadWithoutBOM() throws Exception { byte[] data = new byte[] { 'A', 'B', 'C' }; BOMInputStream in = new BOMInputStream(createDataStream(data, false)); assertEquals('A', in.read()); assertEquals('B', in.read()); assertEquals('C', in.read()); assertEquals(-1, in.read()); assertFalse("hasBOM()", in.hasBOM()); assertFalse("hasBOM(UTF-8)", in.hasBOM(ByteOrderMark.UTF_8)); assertNull("getBOM", in.getBOM()); } public void testReadEmpty() throws Exception { byte[] data = new byte[] {}; BOMInputStream in = new BOMInputStream(createDataStream(data, false)); assertEquals(-1, in.read()); assertFalse("hasBOM()", in.hasBOM()); assertFalse("hasBOM(UTF-8)", in.hasBOM(ByteOrderMark.UTF_8)); assertNull("getBOM", in.getBOM()); } public void testReadSmall() throws Exception { byte[] data = new byte[] { 'A', 'B' }; BOMInputStream in = new BOMInputStream(createDataStream(data, false)); assertEquals('A', in.read()); assertEquals('B', in.read()); assertEquals(-1, in.read()); assertFalse("hasBOM()", in.hasBOM()); assertFalse("hasBOM(UTF-8)", in.hasBOM(ByteOrderMark.UTF_8)); assertNull("getBOM", in.getBOM()); } public void testReadWithBOM() throws Exception { byte[] data = new byte[] { 'A', 'B', 'C' }; BOMInputStream in = new BOMInputStream(createDataStream(data, true)); assertEquals('A', in.read()); assertEquals('B', in.read()); assertEquals('C', in.read()); assertEquals(-1, in.read()); assertTrue("hasBOM()", in.hasBOM()); assertTrue("hasBOM(UTF-8)", in.hasBOM(ByteOrderMark.UTF_8)); assertEquals("getBOM", ByteOrderMark.UTF_8, in.getBOM()); try { in.hasBOM(ByteOrderMark.UTF_16BE); } catch (IllegalArgumentException e) { // expected - not configured for UTF-16BE } } public void testGetBOMFirstThenRead() throws Exception { byte[] data = new byte[] { 'A', 'B', 'C' }; BOMInputStream in = new BOMInputStream(createDataStream(data, true)); assertEquals("getBOM", ByteOrderMark.UTF_8, in.getBOM()); assertTrue("hasBOM()", in.hasBOM()); assertTrue("hasBOM(UTF-8)", in.hasBOM(ByteOrderMark.UTF_8)); assertEquals('A', in.read()); assertEquals('B', in.read()); assertEquals('C', in.read()); assertEquals(-1, in.read()); } public void testReadWithBOMInclude() throws Exception { byte[] data = new byte[] { 'A', 'B', 'C' }; BOMInputStream in = new BOMInputStream(createDataStream(data, true), true); assertEquals(0xEF, in.read()); assertEquals(0xBB, in.read()); assertEquals(0xBF, in.read()); assertEquals('A', in.read()); assertEquals('B', in.read()); assertEquals('C', in.read()); assertEquals(-1, in.read()); assertTrue("hasBOM()", in.hasBOM()); assertTrue("hasBOM(UTF-8)", in.hasBOM(ByteOrderMark.UTF_8)); assertEquals("getBOM", ByteOrderMark.UTF_8, in.getBOM()); } public void testGetBOMFirstThenReadInclude() throws Exception { byte[] data = new byte[] { 'A', 'B', 'C' }; BOMInputStream in = new BOMInputStream(createDataStream(data, true), true); assertTrue("hasBOM()", in.hasBOM()); assertTrue("hasBOM(UTF-8)", in.hasBOM(ByteOrderMark.UTF_8)); assertEquals("getBOM", ByteOrderMark.UTF_8, in.getBOM()); assertEquals(0xEF, in.read()); assertEquals(0xBB, in.read()); assertEquals(0xBF, in.read()); assertEquals('A', in.read()); assertEquals('B', in.read()); assertEquals('C', in.read()); assertEquals(-1, in.read()); } public void testReadWithMultipleBOM() throws Exception { byte[] data = new byte[] { 'A', 'B', 'C' }; BOMInputStream in = new BOMInputStream(createDataStream(data, true), ByteOrderMark.UTF_16BE, ByteOrderMark.UTF_8); assertEquals('A', in.read()); assertEquals('B', in.read()); assertEquals('C', in.read()); assertEquals(-1, in.read()); assertTrue("hasBOM()", in.hasBOM()); assertTrue("hasBOM(UTF-8)", in.hasBOM(ByteOrderMark.UTF_8)); assertFalse("hasBOM(UTF-16BE)", in.hasBOM(ByteOrderMark.UTF_16BE)); assertEquals("getBOM", ByteOrderMark.UTF_8, in.getBOM()); } public void testEmptyBufferWithoutBOM() throws Exception { byte[] data = new byte[] {}; InputStream in = new BOMInputStream(createDataStream(data, false)); byte[] buf = new byte[1024]; assertEquals(-1, in.read(buf)); } public void testEmptyBufferWithBOM() throws Exception { byte[] data = new byte[] {}; InputStream in = new BOMInputStream(createDataStream(data, true)); byte[] buf = new byte[1024]; assertEquals(-1, in.read(buf)); } public void testLargeBufferWithoutBOM() throws Exception { byte[] data = new byte[] { 'A', 'B', 'C' }; InputStream in = new BOMInputStream(createDataStream(data, false)); byte[] buf = new byte[1024]; assertData(data, buf, in.read(buf)); } public void testLargeBufferWithBOM() throws Exception { byte[] data = new byte[] { 'A', 'B', 'C' }; InputStream in = new BOMInputStream(createDataStream(data, true)); byte[] buf = new byte[1024]; assertData(data, buf, in.read(buf)); } public void testSmallBufferWithoutBOM() throws Exception { byte[] data = new byte[] { 'A', 'B', 'C' }; InputStream in = new BOMInputStream(createDataStream(data, false)); byte[] buf = new byte[1024]; assertData(new byte[] { 'A', 'B' }, buf, in.read(buf, 0, 2)); assertData(new byte[] { 'C' }, buf, in.read(buf, 0, 2)); } public void testSmallBufferWithBOM() throws Exception { byte[] data = new byte[] { 'A', 'B', 'C' }; InputStream in = new BOMInputStream(createDataStream(data, true)); byte[] buf = new byte[1024]; assertData(new byte[] { 'A', 'B' }, buf, in.read(buf, 0, 2)); assertData(new byte[] { 'C' }, buf, in.read(buf, 0, 2)); } public void testLeadingNonBOMSingleRead() throws Exception { byte[] data = new byte[] { (byte) 0xEF, (byte) 0xAB, (byte) 0xCD }; InputStream in = new BOMInputStream(createDataStream(data, false)); assertEquals(0xEF, in.read()); assertEquals(0xAB, in.read()); assertEquals(0xCD, in.read()); assertEquals(-1, in.read()); } public void testLeadingNonBOMBufferedRead() throws Exception { byte[] data = new byte[] { (byte) 0xEF, (byte) 0xAB, (byte) 0xCD }; InputStream in = new BOMInputStream(createDataStream(data, false)); byte[] buf = new byte[1024]; assertData(data, buf, in.read(buf)); } public void testSkipWithoutBOM() throws Exception { byte[] data = new byte[] { 'A', 'B', 'C', 'D' }; InputStream in = new BOMInputStream(createDataStream(data, false)); in.skip(2L); assertEquals('C', in.read()); } public void testSkipWithBOM() throws Exception { byte[] data = new byte[] { 'A', 'B', 'C', 'D' }; InputStream in = new BOMInputStream(createDataStream(data, true)); in.skip(2L); assertEquals('C', in.read()); } public void testMarkResetAfterReadWithoutBOM() throws Exception { byte[] data = new byte[] { 'A', 'B', 'C', 'D' }; InputStream in = new BOMInputStream(createDataStream(data, false)); assertTrue(in.markSupported()); in.read(); in.mark(10); in.read(); in.read(); in.reset(); assertEquals('B', in.read()); } public void testMarkResetAfterReadWithBOM() throws Exception { byte[] data = new byte[] { 'A', 'B', 'C', 'D' }; InputStream in = new BOMInputStream(createDataStream(data, true)); assertTrue(in.markSupported()); in.read(); in.mark(10); in.read(); in.read(); in.reset(); assertEquals('B', in.read()); } public void testMarkResetBeforeReadWithoutBOM() throws Exception { byte[] data = new byte[] { 'A', 'B', 'C', 'D' }; InputStream in = new BOMInputStream(createDataStream(data, false)); assertTrue(in.markSupported()); in.mark(10); in.read(); in.read(); in.reset(); assertEquals('A', in.read()); } public void testMarkResetBeforeReadWithBOM() throws Exception { byte[] data = new byte[] { 'A', 'B', 'C', 'D' }; InputStream in = new BOMInputStream(createDataStream(data, true)); assertTrue(in.markSupported()); in.mark(10); in.read(); in.read(); in.reset(); assertEquals('A', in.read()); } public void testAvailableWithoutBOM() throws Exception { byte[] data = new byte[] { 'A', 'B', 'C', 'D' }; InputStream in = new BOMInputStream(createDataStream(data, false)); assertEquals(4, in.available()); } public void testAvailableWithBOM() throws Exception { byte[] data = new byte[] { 'A', 'B', 'C', 'D' }; InputStream in = new BOMInputStream(createDataStream(data, true)); assertEquals(7, in.available()); } public void testNoBoms() throws Exception { byte[] data = new byte[] { 'A', 'B', 'C' }; try { new BOMInputStream(createDataStream(data, true), false, (ByteOrderMark[])null); fail("Null BOMs, expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // expected } try { new BOMInputStream(createDataStream(data, true), false, new ByteOrderMark[0]); fail("Null BOMs, expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // expected } } public void testReadTwiceWithoutBOM() throws Exception { this.readBOMInputStreamTwice("/org/apache/commons/io/testfileNoBOM.xml"); } public void testReadTwiceWithBOM() throws Exception { this.readBOMInputStreamTwice("/org/apache/commons/io/testfileBOM.xml"); } public void readBOMInputStreamTwice(String resource) throws Exception { InputStream inputStream = this.getClass().getResourceAsStream(resource); Assert.assertNotNull(inputStream); BOMInputStream bomInputStream = new BOMInputStream(inputStream); bomInputStream.mark(1000000); this.readFile(bomInputStream); bomInputStream.reset(); this.readFile(bomInputStream); } private void readFile(BOMInputStream bomInputStream) throws Exception { int bytes = 0; byte[] bytesFromStream = new byte[100]; do { bytes = bomInputStream.read(bytesFromStream); } while (bytes > 0); } // this is here for coverage public void testClose() throws Exception { ExpectCloseInputStream del = new ExpectCloseInputStream(); InputStream in = new BOMInputStream(del); in.close(); del.assertCloseCalled(); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/input/CharSequenceInputStreamTest.javalibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/input/CharSequenceInputStreamTest.ja0000644000175000017500000001334512125050425033174 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.util.Random; import org.junit.Test; public class CharSequenceInputStreamTest { private static final String TEST_STRING = "\u00e0 peine arriv\u00e9s nous entr\u00e2mes dans sa chambre"; private static final String LARGE_TEST_STRING; static { StringBuilder buffer = new StringBuilder(); for (int i=0; i<100; i++) { buffer.append(TEST_STRING); } LARGE_TEST_STRING = buffer.toString(); } private Random random = new Random(); private void testWithSingleByteRead(String testString, String charsetName) throws IOException { byte[] bytes = testString.getBytes(charsetName); InputStream in = new CharSequenceInputStream(testString, charsetName, 512); for (byte b : bytes) { int read = in.read(); assertTrue("read "+read+" >=0 ", read >= 0); assertTrue("read "+read+" <= 255", read <= 255); assertEquals("Should agree with input", b, (byte)read); } assertEquals(-1, in.read()); } private void testWithBufferedRead(String testString, String charsetName) throws IOException { byte[] expected = testString.getBytes(charsetName); InputStream in = new CharSequenceInputStream(testString, charsetName, 512); byte[] buffer = new byte[128]; int offset = 0; while (true) { int bufferOffset = random.nextInt(64); int bufferLength = random.nextInt(64); int read = in.read(buffer, bufferOffset, bufferLength); if (read == -1) { assertEquals("EOF: offset should equal length", expected.length, offset); break; } else { assertTrue("Read "+read+" <= "+bufferLength, read <= bufferLength); while (read > 0) { assertTrue("offset "+offset+" < "+expected.length, offset < expected.length); assertEquals("bytes should agree", expected[offset], buffer[bufferOffset]); offset++; bufferOffset++; read--; } } } } @Test public void testUTF8WithSingleByteRead() throws IOException { testWithSingleByteRead(TEST_STRING, "UTF-8"); } @Test public void testLargeUTF8WithSingleByteRead() throws IOException { testWithSingleByteRead(LARGE_TEST_STRING, "UTF-8"); } @Test public void testUTF8WithBufferedRead() throws IOException { testWithBufferedRead(TEST_STRING, "UTF-8"); } @Test public void testLargeUTF8WithBufferedRead() throws IOException { testWithBufferedRead(LARGE_TEST_STRING, "UTF-8"); } @Test public void testUTF16WithSingleByteRead() throws IOException { testWithSingleByteRead(TEST_STRING, "UTF-16"); } @Test public void testReadZero() throws Exception { InputStream r = new CharSequenceInputStream("test", "UTF-8"); byte[] bytes = new byte[30]; assertEquals(0, r.read(bytes, 0, 0)); } @Test public void testReadZeroEmptyString() throws Exception { InputStream r = new CharSequenceInputStream("", "UTF-8"); byte[] bytes = new byte[30]; assertEquals(0, r.read(bytes, 0, 0)); } @Test public void testCharsetMismatchInfiniteLoop() throws IOException { // Input is UTF-8 bytes: 0xE0 0xB2 0xA0 char[] inputChars = new char[] { (char) 0xE0, (char) 0xB2, (char) 0xA0 }; // Charset charset = Charset.forName("UTF-8"); // works Charset charset = Charset.forName("ASCII"); // infinite loop InputStream stream = new CharSequenceInputStream(new String(inputChars), charset, 512); try { while (stream.read() != -1) { } } finally { stream.close(); } } @Test public void testSkip() throws Exception { InputStream r = new CharSequenceInputStream("test", "UTF-8"); r.skip(1); r.skip(2); assertEquals('t', r.read()); r.skip(100); assertEquals(-1, r.read()); } @Test public void testMarkReset() throws Exception { InputStream r = new CharSequenceInputStream("test", "UTF-8"); r.skip(2); r.mark(0); assertEquals('s', r.read()); assertEquals('t', r.read()); assertEquals(-1, r.read()); r.reset(); assertEquals('s', r.read()); assertEquals('t', r.read()); assertEquals(-1, r.read()); r.reset(); r.reset(); } @Test public void testMarkSupported() throws Exception { InputStream r = new CharSequenceInputStream("test", "UTF-8"); assertTrue(r.markSupported()); } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/input/ClosedInputStreamTest.java0000644000175000017500000000220412125050425032356 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import junit.framework.TestCase; /** * JUnit Test Case for {@link ClosedInputStream}. */ public class ClosedInputStreamTest extends TestCase { /** * Test the read() method. */ public void testRead() { assertEquals("read()", -1, new ClosedInputStream().read()); } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/input/ReaderInputStreamTest.java0000644000175000017500000001233012125050425032350 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.CharArrayReader; import java.io.IOException; import java.io.StringReader; import java.nio.charset.Charset; import java.util.Random; import org.junit.Test; public class ReaderInputStreamTest { private static final String TEST_STRING = "\u00e0 peine arriv\u00e9s nous entr\u00e2mes dans sa chambre"; private static final String LARGE_TEST_STRING; static { StringBuilder buffer = new StringBuilder(); for (int i=0; i<100; i++) { buffer.append(TEST_STRING); } LARGE_TEST_STRING = buffer.toString(); } private Random random = new Random(); private void testWithSingleByteRead(String testString, String charsetName) throws IOException { byte[] bytes = testString.getBytes(charsetName); ReaderInputStream in = new ReaderInputStream(new StringReader(testString), charsetName); for (byte b : bytes) { int read = in.read(); assertTrue(read >= 0); assertTrue(read <= 255); assertEquals(b, (byte)read); } assertEquals(-1, in.read()); } private void testWithBufferedRead(String testString, String charsetName) throws IOException { byte[] expected = testString.getBytes(charsetName); ReaderInputStream in = new ReaderInputStream(new StringReader(testString), charsetName); byte[] buffer = new byte[128]; int offset = 0; while (true) { int bufferOffset = random.nextInt(64); int bufferLength = random.nextInt(64); int read = in.read(buffer, bufferOffset, bufferLength); if (read == -1) { assertEquals(offset, expected.length); break; } else { assertTrue(read <= bufferLength); while (read > 0) { assertTrue(offset < expected.length); assertEquals(expected[offset], buffer[bufferOffset]); offset++; bufferOffset++; read--; } } } } @Test public void testUTF8WithSingleByteRead() throws IOException { testWithSingleByteRead(TEST_STRING, "UTF-8"); } @Test public void testLargeUTF8WithSingleByteRead() throws IOException { testWithSingleByteRead(LARGE_TEST_STRING, "UTF-8"); } @Test public void testUTF8WithBufferedRead() throws IOException { testWithBufferedRead(TEST_STRING, "UTF-8"); } @Test public void testLargeUTF8WithBufferedRead() throws IOException { testWithBufferedRead(LARGE_TEST_STRING, "UTF-8"); } @Test public void testUTF16WithSingleByteRead() throws IOException { testWithSingleByteRead(TEST_STRING, "UTF-16"); } @Test public void testReadZero() throws Exception { final String inStr = "test"; ReaderInputStream r = new ReaderInputStream(new StringReader(inStr)); byte[] bytes = new byte[30]; assertEquals(0, r.read(bytes, 0, 0)); assertEquals(inStr.length(), r.read(bytes, 0, inStr.length()+1)); // Should always return 0 for length == 0 assertEquals(0, r.read(bytes, 0, 0)); } @Test public void testReadZeroEmptyString() throws Exception { ReaderInputStream r = new ReaderInputStream(new StringReader("")); byte[] bytes = new byte[30]; // Should always return 0 for length == 0 assertEquals(0, r.read(bytes, 0, 0)); assertEquals(-1, r.read(bytes, 0, 1)); assertEquals(0, r.read(bytes, 0, 0)); assertEquals(-1, r.read(bytes, 0, 1)); } /** * Tests https://issues.apache.org/jira/browse/IO-277 * * @throws IOException */ @Test public void testCharsetMismatchInfiniteLoop() throws IOException { // Input is UTF-8 bytes: 0xE0 0xB2 0xA0 char[] inputChars = new char[] { (char) 0xE0, (char) 0xB2, (char) 0xA0 }; // Charset charset = Charset.forName("UTF-8"); // works Charset charset = Charset.forName("ASCII"); // infinite loop ReaderInputStream stream = new ReaderInputStream(new CharArrayReader(inputChars), charset); try { while (stream.read() != -1) { } } finally { stream.close(); } } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/input/ClassLoaderObjectInputStreamTest.javalibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/input/ClassLoaderObjectInputStreamTe0000644000175000017500000000525612125050425033213 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.ObjectOutputStream; import junit.framework.TestCase; /** * Tests the CountingInputStream. * * @version $Id: ClassLoaderObjectInputStreamTest.java 1302056 2012-03-18 03:03:38Z ggregory $ */ public class ClassLoaderObjectInputStreamTest extends TestCase { public ClassLoaderObjectInputStreamTest(String name) { super(name); } /* Note: This test case tests the simplest functionality of * ObjectInputStream. IF we really wanted to test ClassLoaderObjectInputStream * we would probably need to create a transient Class Loader. -TO */ public void testExpected() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject( Boolean.FALSE ); InputStream bais = new ByteArrayInputStream(baos.toByteArray()); ClassLoaderObjectInputStream clois = new ClassLoaderObjectInputStream(getClass().getClassLoader(), bais); Boolean result = (Boolean) clois.readObject(); assertTrue( !result.booleanValue() ); } public void testResolveProxyClass() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject( Boolean.FALSE ); InputStream bais = new ByteArrayInputStream(baos.toByteArray()); ClassLoaderObjectInputStream clois = new ClassLoaderObjectInputStream(getClass().getClassLoader(), bais); String[] interfaces = new String[] { Comparable.class.getName() }; Class result = clois.resolveProxyClass(interfaces); assertTrue("Assignable", Comparable.class.isAssignableFrom(result)); } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/input/BrokenInputStreamTest.java0000644000175000017500000000526212125050425032374 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import java.io.IOException; import java.io.InputStream; import junit.framework.TestCase; /** * JUnit Test Case for {@link BrokenInputStream}. */ public class BrokenInputStreamTest extends TestCase { private IOException exception; private InputStream stream; @Override protected void setUp() { exception = new IOException("test exception"); stream = new BrokenInputStream(exception); } public void testRead() { try { stream.read(); fail("Expected exception not thrown."); } catch (IOException e) { assertEquals(exception, e); } try { stream.read(new byte[1]); fail("Expected exception not thrown."); } catch (IOException e) { assertEquals(exception, e); } try { stream.read(new byte[1], 0, 1); fail("Expected exception not thrown."); } catch (IOException e) { assertEquals(exception, e); } } public void testAvailable() { try { stream.available(); fail("Expected exception not thrown."); } catch (IOException e) { assertEquals(exception, e); } } public void testSkip() { try { stream.skip(1); fail("Expected exception not thrown."); } catch (IOException e) { assertEquals(exception, e); } } public void testReset() { try { stream.reset(); fail("Expected exception not thrown."); } catch (IOException e) { assertEquals(exception, e); } } public void testClose() { try { stream.close(); fail("Expected exception not thrown."); } catch (IOException e) { assertEquals(exception, e); } } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/input/ProxyReaderTest.java0000644000175000017500000000510612125050425031221 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import java.io.IOException; import java.io.Reader; import java.nio.CharBuffer; import junit.framework.TestCase; /** * Test {@link ProxyReader}. * * @version $Id: ProxyReaderTest.java 1302056 2012-03-18 03:03:38Z ggregory $ */ public class ProxyReaderTest extends TestCase { public ProxyReaderTest(String name) { super(name); } /** Test writing Null Char Array */ public void testNullCharArray() { ProxyReader proxy = new ProxyReaderImpl(new CustomNullReader(0)); try { proxy.read((char[])null); } catch(Exception e) { fail("Writing null String threw " + e); } try { proxy.read((char[])null, 0, 0); } catch(Exception e) { fail("Writing null String threw " + e); } } /** Test writing Null CharBuffer */ public void testNullCharBuffer() { ProxyReader proxy = new ProxyReaderImpl(new CustomNullReader(0)); try { proxy.read((CharBuffer)null); } catch(Exception e) { fail("Writing null String threw " + e); } } /** ProxyReader implementation */ private static class ProxyReaderImpl extends ProxyReader { ProxyReaderImpl(Reader proxy) { super(proxy); } } /** Custom NullReader implementation */ private static class CustomNullReader extends NullReader { CustomNullReader(int len) { super(len); } @Override public int read(char[] chars) throws IOException { return chars == null ? 0 : super.read(chars); } @Override public int read(CharBuffer target) throws IOException { return target == null ? 0 : super.read(target); } } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/input/XmlStreamReaderTest.java0000644000175000017500000005216412125050425032022 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.text.MessageFormat; import java.util.HashMap; import java.util.Map; import org.apache.commons.io.IOUtils; import org.junit.Test; /** */ public class XmlStreamReaderTest { private static final String XML5 = "xml-prolog-encoding-spaced-single-quotes"; private static final String XML4 = "xml-prolog-encoding-single-quotes"; private static final String XML3 = "xml-prolog-encoding-double-quotes"; private static final String XML2 = "xml-prolog"; private static final String XML1 = "xml"; protected void _testRawNoBomValid(String encoding) throws Exception { InputStream is = getXmlStream("no-bom", XML1, encoding, encoding); XmlStreamReader xmlReader = new XmlStreamReader(is, false); assertEquals(xmlReader.getEncoding(), "UTF-8"); is = getXmlStream("no-bom", XML2, encoding, encoding); xmlReader = new XmlStreamReader(is); assertEquals(xmlReader.getEncoding(), "UTF-8"); is = getXmlStream("no-bom", XML3, encoding, encoding); xmlReader = new XmlStreamReader(is); assertEquals(xmlReader.getEncoding(), encoding); is = getXmlStream("no-bom", XML4, encoding, encoding); xmlReader = new XmlStreamReader(is); assertEquals(xmlReader.getEncoding(), encoding); is = getXmlStream("no-bom", XML5, encoding, encoding); xmlReader = new XmlStreamReader(is); assertEquals(xmlReader.getEncoding(), encoding); } protected void _testRawNoBomInvalid(String encoding) throws Exception { InputStream is = getXmlStream("no-bom", XML3, encoding, encoding); try { new XmlStreamReader(is, false); fail("It should have failed"); } catch (IOException ex) { assertTrue(ex.getMessage().indexOf("Invalid encoding,") > -1); } } @Test public void testRawNoBomUsAscii() throws Exception { _testRawNoBomValid("US-ASCII"); } @Test public void testRawNoBomUtf8() throws Exception { _testRawNoBomValid("UTF-8"); } @Test public void testRawNoBomUtf16BE() throws Exception { _testRawNoBomValid("UTF-16BE"); } @Test public void testRawNoBomUtf16LE() throws Exception { _testRawNoBomValid("UTF-16LE"); } @Test public void testRawNoBomUtf32BE() throws Exception { _testRawNoBomValid("UTF-32BE"); } @Test public void testRawNoBomUtf32LE() throws Exception { _testRawNoBomValid("UTF-32LE"); } @Test public void testRawNoBomIso8859_1() throws Exception { _testRawNoBomValid("ISO-8859-1"); } @Test public void testRawNoBomCp1047() throws Exception { _testRawNoBomValid("CP1047"); } protected void _testRawBomValid(String encoding) throws Exception { InputStream is = getXmlStream(encoding + "-bom", XML3, encoding, encoding); XmlStreamReader xmlReader = new XmlStreamReader(is, false); if (!encoding.equals("UTF-16") && !encoding.equals("UTF-32")) { assertEquals(xmlReader.getEncoding(), encoding); } else { assertEquals(xmlReader.getEncoding() .substring(0, encoding.length()), encoding); } } protected void _testRawBomInvalid(String bomEnc, String streamEnc, String prologEnc) throws Exception { InputStream is = getXmlStream(bomEnc, XML3, streamEnc, prologEnc); try { XmlStreamReader xmlReader = new XmlStreamReader(is, false); String foundEnc = xmlReader.getEncoding(); fail("Expected IOException for BOM " + bomEnc + ", streamEnc " + streamEnc + " and prologEnc " + prologEnc + ": found " + foundEnc); } catch (IOException ex) { assertTrue(ex.getMessage().indexOf("Invalid encoding,") > -1); } } @Test public void testRawBomUtf8() throws Exception { _testRawBomValid("UTF-8"); _testRawBomInvalid("UTF-8-bom", "US-ASCII", "US-ASCII"); _testRawBomInvalid("UTF-8-bom", "ISO-8859-1", "ISO-8859-1"); _testRawBomInvalid("UTF-8-bom", "UTF-8", "UTF-16"); _testRawBomInvalid("UTF-8-bom", "UTF-8", "UTF-16BE"); _testRawBomInvalid("UTF-8-bom", "UTF-8", "UTF-16LE"); _testRawBomInvalid("UTF-16BE-bom", "UTF-16BE", "UTF-16LE"); _testRawBomInvalid("UTF-16LE-bom", "UTF-16LE", "UTF-16BE"); _testRawBomInvalid("UTF-16LE-bom", "UTF-16LE", "UTF-8"); _testRawBomInvalid("UTF-32BE-bom", "UTF-32BE", "UTF-32LE"); _testRawBomInvalid("UTF-32LE-bom", "UTF-32LE", "UTF-32BE"); _testRawBomInvalid("UTF-32LE-bom", "UTF-32LE", "UTF-8"); } @Test public void testRawBomUtf16() throws Exception { _testRawBomValid("UTF-16BE"); _testRawBomValid("UTF-16LE"); _testRawBomValid("UTF-16"); _testRawBomInvalid("UTF-16BE-bom", "UTF-16BE", "UTF-16LE"); _testRawBomInvalid("UTF-16LE-bom", "UTF-16LE", "UTF-16BE"); _testRawBomInvalid("UTF-16LE-bom", "UTF-16LE", "UTF-8"); } @Test public void testRawBomUtf32() throws Exception { _testRawBomValid("UTF-32BE"); _testRawBomValid("UTF-32LE"); _testRawBomValid("UTF-32"); _testRawBomInvalid("UTF-32BE-bom", "UTF-32BE", "UTF-32LE"); _testRawBomInvalid("UTF-32LE-bom", "UTF-32LE", "UTF-32BE"); _testRawBomInvalid("UTF-32LE-bom", "UTF-32LE", "UTF-8"); } @Test public void testHttp() throws Exception { // niallp 2010-10-06 - remove following 2 tests - I reinstated // checks for non-UTF-16 encodings (18 tests) and these failed // _testHttpValid("application/xml", "no-bom", "US-ASCII", null); // _testHttpValid("application/xml", "UTF-8-bom", "US-ASCII", null); _testHttpValid("application/xml", "UTF-8-bom", "UTF-8", null); _testHttpValid("application/xml", "UTF-8-bom", "UTF-8", "UTF-8"); _testHttpValid("application/xml;charset=UTF-8", "UTF-8-bom", "UTF-8", null); _testHttpValid("application/xml;charset=\"UTF-8\"", "UTF-8-bom", "UTF-8", null); _testHttpValid("application/xml;charset='UTF-8'", "UTF-8-bom", "UTF-8", null); _testHttpValid("application/xml;charset=UTF-8", "UTF-8-bom", "UTF-8", "UTF-8"); _testHttpValid("application/xml;charset=UTF-16", "UTF-16BE-bom", "UTF-16BE", null); _testHttpValid("application/xml;charset=UTF-16", "UTF-16BE-bom", "UTF-16BE", "UTF-16"); _testHttpValid("application/xml;charset=UTF-16", "UTF-16BE-bom", "UTF-16BE", "UTF-16BE"); _testHttpInvalid("application/xml;charset=UTF-16BE", "UTF-16BE-bom", "UTF-16BE", null); _testHttpInvalid("application/xml;charset=UTF-16BE", "UTF-16BE-bom", "UTF-16BE", "UTF-16"); _testHttpInvalid("application/xml;charset=UTF-16BE", "UTF-16BE-bom", "UTF-16BE", "UTF-16BE"); _testHttpInvalid("application/xml;charset=UTF-32BE", "UTF-32BE-bom", "UTF-32BE", null); _testHttpInvalid("application/xml;charset=UTF-32BE", "UTF-32BE-bom", "UTF-32BE", "UTF-32"); _testHttpInvalid("application/xml;charset=UTF-32BE", "UTF-32BE-bom", "UTF-32BE", "UTF-32BE"); _testHttpInvalid("application/xml", "UTF-8-bom", "US-ASCII", "US-ASCII"); _testHttpInvalid("application/xml;charset=UTF-16", "UTF-16LE", "UTF-8", "UTF-8"); _testHttpInvalid("application/xml;charset=UTF-16", "no-bom", "UTF-16BE", "UTF-16BE"); _testHttpInvalid("application/xml;charset=UTF-32", "UTF-32LE", "UTF-8", "UTF-8"); _testHttpInvalid("application/xml;charset=UTF-32", "no-bom", "UTF-32BE", "UTF-32BE"); _testHttpValid("text/xml", "no-bom", "US-ASCII", null); _testHttpValid("text/xml;charset=UTF-8", "UTF-8-bom", "UTF-8", "UTF-8"); _testHttpValid("text/xml;charset=UTF-8", "UTF-8-bom", "UTF-8", null); _testHttpValid("text/xml;charset=UTF-16", "UTF-16BE-bom", "UTF-16BE", null); _testHttpValid("text/xml;charset=UTF-16", "UTF-16BE-bom", "UTF-16BE", "UTF-16"); _testHttpValid("text/xml;charset=UTF-16", "UTF-16BE-bom", "UTF-16BE", "UTF-16BE"); _testHttpValid("text/xml;charset=UTF-32", "UTF-32BE-bom", "UTF-32BE", null); _testHttpValid("text/xml;charset=UTF-32", "UTF-32BE-bom", "UTF-32BE", "UTF-32"); _testHttpValid("text/xml;charset=UTF-32", "UTF-32BE-bom", "UTF-32BE", "UTF-32BE"); _testHttpValid("text/xml", "UTF-8-bom", "US-ASCII", null); _testAlternateDefaultEncoding("application/xml", "UTF-8-bom", "UTF-8", null, null); _testAlternateDefaultEncoding("application/xml", "no-bom", "US-ASCII", null, "US-ASCII"); _testAlternateDefaultEncoding("application/xml", "UTF-8-bom", "UTF-8", null, "UTF-8"); _testAlternateDefaultEncoding("text/xml", "no-bom", "US-ASCII", null, null); _testAlternateDefaultEncoding("text/xml", "no-bom", "US-ASCII", null, "US-ASCII"); _testAlternateDefaultEncoding("text/xml", "no-bom", "US-ASCII", null, "UTF-8"); _testHttpInvalid("text/xml;charset=UTF-16BE", "UTF-16BE-bom", "UTF-16BE", null); _testHttpInvalid("text/xml;charset=UTF-16BE", "UTF-16BE-bom", "UTF-16BE", "UTF-16"); _testHttpInvalid("text/xml;charset=UTF-16BE", "UTF-16BE-bom", "UTF-16BE", "UTF-16BE"); _testHttpInvalid("text/xml;charset=UTF-16", "no-bom", "UTF-16BE", "UTF-16BE"); _testHttpInvalid("text/xml;charset=UTF-16", "no-bom", "UTF-16BE", null); _testHttpInvalid("text/xml;charset=UTF-32BE", "UTF-32BE-bom", "UTF-32BE", null); _testHttpInvalid("text/xml;charset=UTF-32BE", "UTF-32BE-bom", "UTF-32BE", "UTF-32"); _testHttpInvalid("text/xml;charset=UTF-32BE", "UTF-32BE-bom", "UTF-32BE", "UTF-32BE"); _testHttpInvalid("text/xml;charset=UTF-32", "no-bom", "UTF-32BE", "UTF-32BE"); _testHttpInvalid("text/xml;charset=UTF-32", "no-bom", "UTF-32BE", null); _testHttpLenient("text/xml", "no-bom", "US-ASCII", null, "US-ASCII"); _testHttpLenient("text/xml;charset=UTF-8", "UTF-8-bom", "UTF-8", "UTF-8", "UTF-8"); _testHttpLenient("text/xml;charset=UTF-8", "UTF-8-bom", "UTF-8", null, "UTF-8"); _testHttpLenient("text/xml;charset=UTF-16", "UTF-16BE-bom", "UTF-16BE", null, "UTF-16BE"); _testHttpLenient("text/xml;charset=UTF-16", "UTF-16BE-bom", "UTF-16BE", "UTF-16", "UTF-16"); _testHttpLenient("text/xml;charset=UTF-16", "UTF-16BE-bom", "UTF-16BE", "UTF-16BE", "UTF-16BE"); _testHttpLenient("text/xml;charset=UTF-32", "UTF-32BE-bom", "UTF-32BE", null, "UTF-32BE"); _testHttpLenient("text/xml;charset=UTF-32", "UTF-32BE-bom", "UTF-32BE", "UTF-32", "UTF-32"); _testHttpLenient("text/xml;charset=UTF-32", "UTF-32BE-bom", "UTF-32BE", "UTF-32BE", "UTF-32BE"); _testHttpLenient("text/xml", "UTF-8-bom", "US-ASCII", null, "US-ASCII"); _testHttpLenient("text/xml;charset=UTF-16BE", "UTF-16BE-bom", "UTF-16BE", null, "UTF-16BE"); _testHttpLenient("text/xml;charset=UTF-16BE", "UTF-16BE-bom", "UTF-16BE", "UTF-16", "UTF-16"); _testHttpLenient("text/xml;charset=UTF-16BE", "UTF-16BE-bom", "UTF-16BE", "UTF-16BE", "UTF-16BE"); _testHttpLenient("text/xml;charset=UTF-16", "no-bom", "UTF-16BE", "UTF-16BE", "UTF-16BE"); _testHttpLenient("text/xml;charset=UTF-16", "no-bom", "UTF-16BE", null, "UTF-16"); _testHttpLenient("text/xml;charset=UTF-32BE", "UTF-32BE-bom", "UTF-32BE", null, "UTF-32BE"); _testHttpLenient("text/xml;charset=UTF-32BE", "UTF-32BE-bom", "UTF-32BE", "UTF-32", "UTF-32"); _testHttpLenient("text/xml;charset=UTF-32BE", "UTF-32BE-bom", "UTF-32BE", "UTF-32BE", "UTF-32BE"); _testHttpLenient("text/xml;charset=UTF-32", "no-bom", "UTF-32BE", "UTF-32BE", "UTF-32BE"); _testHttpLenient("text/xml;charset=UTF-32", "no-bom", "UTF-32BE", null, "UTF-32"); _testHttpLenient("text/html", "no-bom", "US-ASCII", "US-ASCII", "US-ASCII"); _testHttpLenient("text/html", "no-bom", "US-ASCII", null, "US-ASCII"); _testHttpLenient("text/html;charset=UTF-8", "no-bom", "US-ASCII", "UTF-8", "UTF-8"); _testHttpLenient("text/html;charset=UTF-16BE", "no-bom", "US-ASCII", "UTF-8", "UTF-8"); _testHttpLenient("text/html;charset=UTF-32BE", "no-bom", "US-ASCII", "UTF-8", "UTF-8"); } @Test public void testRawContent() throws Exception { String encoding = "UTF-8"; String xml = getXML("no-bom", XML3, encoding, encoding); ByteArrayInputStream is = new ByteArrayInputStream(xml.getBytes(encoding)); XmlStreamReader xmlReader = new XmlStreamReader(is); assertEquals("Check encoding", xmlReader.getEncoding(), encoding); assertEquals("Check content", xml, IOUtils.toString(xmlReader)); } @Test public void testHttpContent() throws Exception { String encoding = "UTF-8"; String xml = getXML("no-bom", XML3, encoding, encoding); ByteArrayInputStream is = new ByteArrayInputStream(xml.getBytes(encoding)); XmlStreamReader xmlReader = new XmlStreamReader(is, encoding); assertEquals("Check encoding", xmlReader.getEncoding(), encoding); assertEquals("Check content", xml, IOUtils.toString(xmlReader)); } public void _testAlternateDefaultEncoding(String cT, String bomEnc, String streamEnc, String prologEnc, String alternateEnc) throws Exception { InputStream is = getXmlStream(bomEnc, prologEnc == null ? XML1 : XML3, streamEnc, prologEnc); XmlStreamReader xmlReader = new XmlStreamReader(is, cT, false, alternateEnc); if (!streamEnc.equals("UTF-16")) { // we can not assert things here because UTF-8, US-ASCII and // ISO-8859-1 look alike for the chars used for detection // (niallp 2010-10-06 - I re-instated the check below - the tests(6) passed) String enc = alternateEnc != null ? alternateEnc : streamEnc; assertEquals(xmlReader.getEncoding(), enc); } else { //String enc = (alternateEnc != null) ? alternateEnc : streamEnc; assertEquals(xmlReader.getEncoding().substring(0, streamEnc.length()), streamEnc); } } public void _testHttpValid(String cT, String bomEnc, String streamEnc, String prologEnc) throws Exception { InputStream is = getXmlStream(bomEnc, prologEnc == null ? XML1 : XML3, streamEnc, prologEnc); XmlStreamReader xmlReader = new XmlStreamReader(is, cT, false); if (!streamEnc.equals("UTF-16")) { // we can not assert things here because UTF-8, US-ASCII and // ISO-8859-1 look alike for the chars used for detection // (niallp 2010-10-06 - I re-instated the check below and removed the 2 tests that failed) assertEquals(xmlReader.getEncoding(), streamEnc); } else { assertEquals(xmlReader.getEncoding().substring(0, streamEnc.length()), streamEnc); } } protected void _testHttpInvalid(String cT, String bomEnc, String streamEnc, String prologEnc) throws Exception { InputStream is = getXmlStream(bomEnc, prologEnc == null ? XML2 : XML3, streamEnc, prologEnc); try { new XmlStreamReader(is, cT, false); fail("It should have failed for HTTP Content-type " + cT + ", BOM " + bomEnc + ", streamEnc " + streamEnc + " and prologEnc " + prologEnc); } catch (IOException ex) { assertTrue(ex.getMessage().indexOf("Invalid encoding,") > -1); } } protected void _testHttpLenient(String cT, String bomEnc, String streamEnc, String prologEnc, String shouldbe) throws Exception { InputStream is = getXmlStream(bomEnc, prologEnc == null ? XML2 : XML3, streamEnc, prologEnc); XmlStreamReader xmlReader = new XmlStreamReader(is, cT, true); assertEquals(xmlReader.getEncoding(), shouldbe); } private static final String ENCODING_ATTRIBUTE_XML = " \n" + "\n" + "\n" + " \n" + " BOMs = new HashMap(); static { BOMs.put("no-bom", NO_BOM_BYTES); BOMs.put("UTF-16BE-bom", UTF_16BE_BOM_BYTES); BOMs.put("UTF-16LE-bom", UTF_16LE_BOM_BYTES); BOMs.put("UTF-32BE-bom", UTF_32BE_BOM_BYTES); BOMs.put("UTF-32LE-bom", UTF_32LE_BOM_BYTES); BOMs.put("UTF-16-bom", NO_BOM_BYTES); // it's added by the writer BOMs.put("UTF-8-bom", UTF_8_BOM_BYTES); } private static final MessageFormat XML = new MessageFormat( "{2}"); private static final MessageFormat XML_WITH_PROLOG = new MessageFormat( "\n{2}"); private static final MessageFormat XML_WITH_PROLOG_AND_ENCODING_DOUBLE_QUOTES = new MessageFormat( "\n{2}"); private static final MessageFormat XML_WITH_PROLOG_AND_ENCODING_SINGLE_QUOTES = new MessageFormat( "\n{2}"); private static final MessageFormat XML_WITH_PROLOG_AND_ENCODING_SPACED_SINGLE_QUOTES = new MessageFormat( "\n{2}"); private static final MessageFormat INFO = new MessageFormat( "\nBOM : {0}\nDoc : {1}\nStream Enc : {2}\nProlog Enc : {3}\n"); private static final Map XMLs = new HashMap(); static { XMLs.put(XML1, XML); XMLs.put(XML2, XML_WITH_PROLOG); XMLs.put(XML3, XML_WITH_PROLOG_AND_ENCODING_DOUBLE_QUOTES); XMLs.put(XML4, XML_WITH_PROLOG_AND_ENCODING_SINGLE_QUOTES); XMLs.put(XML5, XML_WITH_PROLOG_AND_ENCODING_SPACED_SINGLE_QUOTES); } /** * * @param bomType no-bom, UTF-16BE-bom, UTF-16LE-bom, UTF-8-bom * @param xmlType xml, xml-prolog, xml-prolog-charset * @return XML stream */ protected InputStream getXmlStream(String bomType, String xmlType, String streamEnc, String prologEnc) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); int[] bom = BOMs.get(bomType); if (bom == null) { bom = new int[0]; } for (int element : bom) { baos.write(element); } Writer writer = new OutputStreamWriter(baos, streamEnc); String xmlDoc = getXML(bomType, xmlType, streamEnc, prologEnc); writer.write(xmlDoc); // PADDDING TO TEST THINGS WORK BEYOND PUSHBACK_SIZE writer.write("\n"); for (int i = 0; i < 10000; i++) { writer.write("\n"); } writer.write("\n"); writer.close(); return new ByteArrayInputStream(baos.toByteArray()); } /** * Create the XML. */ private String getXML(String bomType, String xmlType, String streamEnc, String prologEnc) { MessageFormat xml = XMLs.get(xmlType); String info = INFO.format(new Object[] { bomType, xmlType, prologEnc }); String xmlDoc = xml.format(new Object[] { streamEnc, prologEnc, info }); return xmlDoc; } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/input/TeeInputStreamTest.java0000644000175000017500000000650212125050425031667 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import junit.framework.TestCase; /** * JUnit Test Case for {@link TeeInputStream}. */ public class TeeInputStreamTest extends TestCase { private final String ASCII = "US-ASCII"; private InputStream tee; private ByteArrayOutputStream output; @Override protected void setUp() throws Exception { InputStream input = new ByteArrayInputStream("abc".getBytes(ASCII)); output = new ByteArrayOutputStream(); tee = new TeeInputStream(input, output); } public void testReadNothing() throws Exception { assertEquals("", new String(output.toString(ASCII))); } public void testReadOneByte() throws Exception { assertEquals('a', tee.read()); assertEquals("a", new String(output.toString(ASCII))); } public void testReadEverything() throws Exception { assertEquals('a', tee.read()); assertEquals('b', tee.read()); assertEquals('c', tee.read()); assertEquals(-1, tee.read()); assertEquals("abc", new String(output.toString(ASCII))); } public void testReadToArray() throws Exception { byte[] buffer = new byte[8]; assertEquals(3, tee.read(buffer)); assertEquals('a', buffer[0]); assertEquals('b', buffer[1]); assertEquals('c', buffer[2]); assertEquals(-1, tee.read(buffer)); assertEquals("abc", new String(output.toString(ASCII))); } public void testReadToArrayWithOffset() throws Exception { byte[] buffer = new byte[8]; assertEquals(3, tee.read(buffer, 4, 4)); assertEquals('a', buffer[4]); assertEquals('b', buffer[5]); assertEquals('c', buffer[6]); assertEquals(-1, tee.read(buffer, 4, 4)); assertEquals("abc", new String(output.toString(ASCII))); } public void testSkip() throws Exception { assertEquals('a', tee.read()); assertEquals(1, tee.skip(1)); assertEquals('c', tee.read()); assertEquals(-1, tee.read()); assertEquals("ac", new String(output.toString(ASCII))); } public void testMarkReset() throws Exception { assertEquals('a', tee.read()); tee.mark(1); assertEquals('b', tee.read()); tee.reset(); assertEquals('b', tee.read()); assertEquals('c', tee.read()); assertEquals(-1, tee.read()); assertEquals("abbc", new String(output.toString(ASCII))); } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/input/compatibility/0000755000175000017500000000000012125050425030121 5ustar ebourgebourg././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/input/compatibility/XmlStreamReader.javalibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/input/compatibility/XmlStreamReader.0000644000175000017500000007277312125050425033201 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input.compatibility; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.text.MessageFormat; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.io.output.XmlStreamWriter; /** * Character stream that handles all the necessary Voodo to figure out the * charset encoding of the XML document within the stream. *

* IMPORTANT: This class is not related in any way to the org.xml.sax.XMLReader. * This one IS a character stream. *

* All this has to be done without consuming characters from the stream, if not * the XML parser will not recognized the document as a valid XML. This is not * 100% true, but it's close enough (UTF-8 BOM is not handled by all parsers * right now, XmlStreamReader handles it and things work in all parsers). *

* The XmlStreamReader class handles the charset encoding of XML documents in * Files, raw streams and HTTP streams by offering a wide set of constructors. *

* By default the charset encoding detection is lenient, the constructor with * the lenient flag can be used for an script (following HTTP MIME and XML * specifications). All this is nicely explained by Mark Pilgrim in his blog, * Determining the character encoding of a feed. *

* Originally developed for ROME under * Apache License 2.0. * * @version $Id: XmlStreamReader.java 1346400 2012-06-05 14:48:01Z ggregory $ * @see XmlStreamWriter */ public class XmlStreamReader extends Reader { private static final int BUFFER_SIZE = 4096; private static final String UTF_8 = "UTF-8"; private static final String US_ASCII = "US-ASCII"; private static final String UTF_16BE = "UTF-16BE"; private static final String UTF_16LE = "UTF-16LE"; private static final String UTF_16 = "UTF-16"; private static final String UTF_32BE = "UTF-32BE"; private static final String UTF_32LE = "UTF-32LE"; private static final String UTF_32 = "UTF-32"; private static final String EBCDIC = "CP1047"; private static String staticDefaultEncoding = null; private Reader reader; private String encoding; private String defaultEncoding; /** * Sets the default encoding to use if none is set in HTTP content-type, XML * prolog and the rules based on content-type are not adequate. *

* If it is set to NULL the content-type based rules are used. *

* By default it is NULL. * * @param encoding charset encoding to default to. */ public static void setDefaultEncoding(String encoding) { staticDefaultEncoding = encoding; } /** * Returns the default encoding to use if none is set in HTTP content-type, * XML prolog and the rules based on content-type are not adequate. *

* If it is NULL the content-type based rules are used. * * @return the default encoding to use. */ public static String getDefaultEncoding() { return staticDefaultEncoding; } /** * Creates a Reader for a File. *

* It looks for the UTF-8 BOM first, if none sniffs the XML prolog charset, * if this is also missing defaults to UTF-8. *

* It does a lenient charset encoding detection, check the constructor with * the lenient parameter for details. * * @param file File to create a Reader from. * @throws IOException thrown if there is a problem reading the file. */ public XmlStreamReader(File file) throws IOException { this(new FileInputStream(file)); } /** * Creates a Reader for a raw InputStream. *

* It follows the same logic used for files. *

* It does a lenient charset encoding detection, check the constructor with * the lenient parameter for details. * * @param is InputStream to create a Reader from. * @throws IOException thrown if there is a problem reading the stream. */ public XmlStreamReader(InputStream is) throws IOException { this(is, true); } /** * Creates a Reader for a raw InputStream. *

* It follows the same logic used for files. *

* If lenient detection is indicated and the detection above fails as per * specifications it then attempts the following: *

* If the content type was 'text/html' it replaces it with 'text/xml' and * tries the detection again. *

* Else if the XML prolog had a charset encoding that encoding is used. *

* Else if the content type had a charset encoding that encoding is used. *

* Else 'UTF-8' is used. *

* If lenient detection is indicated an XmlStreamReaderException is never * thrown. * * @param is InputStream to create a Reader from. * @param lenient indicates if the charset encoding detection should be * relaxed. * @throws IOException thrown if there is a problem reading the stream. * @throws XmlStreamReaderException thrown if the charset encoding could not * be determined according to the specs. */ public XmlStreamReader(InputStream is, boolean lenient) throws IOException, XmlStreamReaderException { defaultEncoding = staticDefaultEncoding; try { doRawStream(is, lenient); } catch (XmlStreamReaderException ex) { if (!lenient) { throw ex; } else { doLenientDetection(null, ex); } } } /** * Creates a Reader using the InputStream of a URL. *

* If the URL is not of type HTTP and there is not 'content-type' header in * the fetched data it uses the same logic used for Files. *

* If the URL is a HTTP Url or there is a 'content-type' header in the * fetched data it uses the same logic used for an InputStream with * content-type. *

* It does a lenient charset encoding detection, check the constructor with * the lenient parameter for details. * * @param url URL to create a Reader from. * @throws IOException thrown if there is a problem reading the stream of * the URL. */ public XmlStreamReader(URL url) throws IOException { this(url.openConnection()); } /** * Creates a Reader using the InputStream of a URLConnection. *

* If the URLConnection is not of type HttpURLConnection and there is not * 'content-type' header in the fetched data it uses the same logic used for * files. *

* If the URLConnection is a HTTP Url or there is a 'content-type' header in * the fetched data it uses the same logic used for an InputStream with * content-type. *

* It does a lenient charset encoding detection, check the constructor with * the lenient parameter for details. * * @param conn URLConnection to create a Reader from. * @throws IOException thrown if there is a problem reading the stream of * the URLConnection. */ public XmlStreamReader(URLConnection conn) throws IOException { defaultEncoding = staticDefaultEncoding; boolean lenient = true; if (conn instanceof HttpURLConnection) { try { doHttpStream(conn.getInputStream(), conn.getContentType(), lenient); } catch (XmlStreamReaderException ex) { doLenientDetection(conn.getContentType(), ex); } } else if (conn.getContentType() != null) { try { doHttpStream(conn.getInputStream(), conn.getContentType(), lenient); } catch (XmlStreamReaderException ex) { doLenientDetection(conn.getContentType(), ex); } } else { try { doRawStream(conn.getInputStream(), lenient); } catch (XmlStreamReaderException ex) { doLenientDetection(null, ex); } } } /** * Creates a Reader using an InputStream an the associated content-type * header. *

* First it checks if the stream has BOM. If there is not BOM checks the * content-type encoding. If there is not content-type encoding checks the * XML prolog encoding. If there is not XML prolog encoding uses the default * encoding mandated by the content-type MIME type. *

* It does a lenient charset encoding detection, check the constructor with * the lenient parameter for details. * * @param is InputStream to create the reader from. * @param httpContentType content-type header to use for the resolution of * the charset encoding. * @throws IOException thrown if there is a problem reading the file. */ public XmlStreamReader(InputStream is, String httpContentType) throws IOException { this(is, httpContentType, true); } /** * Creates a Reader using an InputStream an the associated content-type * header. This constructor is lenient regarding the encoding detection. *

* First it checks if the stream has BOM. If there is not BOM checks the * content-type encoding. If there is not content-type encoding checks the * XML prolog encoding. If there is not XML prolog encoding uses the default * encoding mandated by the content-type MIME type. *

* If lenient detection is indicated and the detection above fails as per * specifications it then attempts the following: *

* If the content type was 'text/html' it replaces it with 'text/xml' and * tries the detection again. *

* Else if the XML prolog had a charset encoding that encoding is used. *

* Else if the content type had a charset encoding that encoding is used. *

* Else 'UTF-8' is used. *

* If lenient detection is indicated an XmlStreamReaderException is never * thrown. * * @param is InputStream to create the reader from. * @param httpContentType content-type header to use for the resolution of * the charset encoding. * @param lenient indicates if the charset encoding detection should be * relaxed. * @throws IOException thrown if there is a problem reading the file. * @throws XmlStreamReaderException thrown if the charset encoding could not * be determined according to the specs. */ public XmlStreamReader(InputStream is, String httpContentType, boolean lenient, String defaultEncoding) throws IOException, XmlStreamReaderException { this.defaultEncoding = defaultEncoding == null ? staticDefaultEncoding : defaultEncoding; try { doHttpStream(is, httpContentType, lenient); } catch (XmlStreamReaderException ex) { if (!lenient) { throw ex; } else { doLenientDetection(httpContentType, ex); } } } /** * Creates a Reader using an InputStream an the associated content-type * header. This constructor is lenient regarding the encoding detection. *

* First it checks if the stream has BOM. If there is not BOM checks the * content-type encoding. If there is not content-type encoding checks the * XML prolog encoding. If there is not XML prolog encoding uses the default * encoding mandated by the content-type MIME type. *

* If lenient detection is indicated and the detection above fails as per * specifications it then attempts the following: *

* If the content type was 'text/html' it replaces it with 'text/xml' and * tries the detection again. *

* Else if the XML prolog had a charset encoding that encoding is used. *

* Else if the content type had a charset encoding that encoding is used. *

* Else 'UTF-8' is used. *

* If lenient detection is indicated an XmlStreamReaderException is never * thrown. * * @param is InputStream to create the reader from. * @param httpContentType content-type header to use for the resolution of * the charset encoding. * @param lenient indicates if the charset encoding detection should be * relaxed. * @throws IOException thrown if there is a problem reading the file. * @throws XmlStreamReaderException thrown if the charset encoding could not * be determined according to the specs. */ public XmlStreamReader(InputStream is, String httpContentType, boolean lenient) throws IOException, XmlStreamReaderException { this(is, httpContentType, lenient, null); } private void doLenientDetection(String httpContentType, XmlStreamReaderException ex) throws IOException { if (httpContentType != null) { if (httpContentType.startsWith("text/html")) { httpContentType = httpContentType.substring("text/html" .length()); httpContentType = "text/xml" + httpContentType; try { doHttpStream(ex.getInputStream(), httpContentType, true); ex = null; } catch (XmlStreamReaderException ex2) { ex = ex2; } } } if (ex != null) { String encoding = ex.getXmlEncoding(); if (encoding == null) { encoding = ex.getContentTypeEncoding(); } if (encoding == null) { encoding = defaultEncoding == null ? UTF_8 : defaultEncoding; } prepareReader(ex.getInputStream(), encoding); } } /** * Returns the charset encoding of the XmlStreamReader. * * @return charset encoding. */ public String getEncoding() { return encoding; } @Override public int read(char[] buf, int offset, int len) throws IOException { return reader.read(buf, offset, len); } /** * Closes the XmlStreamReader stream. * * @throws IOException thrown if there was a problem closing the stream. */ @Override public void close() throws IOException { reader.close(); } private void doRawStream(InputStream is, boolean lenient) throws IOException { BufferedInputStream pis = new BufferedInputStream(is, BUFFER_SIZE); String bomEnc = getBOMEncoding(pis); String xmlGuessEnc = getXMLGuessEncoding(pis); String xmlEnc = getXmlProlog(pis, xmlGuessEnc); String encoding = calculateRawEncoding(bomEnc, xmlGuessEnc, xmlEnc, pis); prepareReader(pis, encoding); } private void doHttpStream(InputStream is, String httpContentType, boolean lenient) throws IOException { BufferedInputStream pis = new BufferedInputStream(is, BUFFER_SIZE); String cTMime = getContentTypeMime(httpContentType); String cTEnc = getContentTypeEncoding(httpContentType); String bomEnc = getBOMEncoding(pis); String xmlGuessEnc = getXMLGuessEncoding(pis); String xmlEnc = getXmlProlog(pis, xmlGuessEnc); String encoding = calculateHttpEncoding(cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc, pis, lenient); prepareReader(pis, encoding); } private void prepareReader(InputStream is, String encoding) throws IOException { reader = new InputStreamReader(is, encoding); this.encoding = encoding; } // InputStream is passed for XmlStreamReaderException creation only String calculateRawEncoding(String bomEnc, String xmlGuessEnc, String xmlEnc, InputStream is) throws IOException { String encoding; if (bomEnc == null) { if (xmlGuessEnc == null || xmlEnc == null) { encoding = defaultEncoding == null ? UTF_8 : defaultEncoding; } else if (xmlEnc.equals(UTF_16) && (xmlGuessEnc.equals(UTF_16BE) || xmlGuessEnc .equals(UTF_16LE))) { encoding = xmlGuessEnc; } else if (xmlEnc.equals(UTF_32) && (xmlGuessEnc.equals(UTF_32BE) || xmlGuessEnc .equals(UTF_32LE))) { encoding = xmlGuessEnc; } else { encoding = xmlEnc; } } else if (bomEnc.equals(UTF_8)) { if (xmlGuessEnc != null && !xmlGuessEnc.equals(UTF_8)) { throw new XmlStreamReaderException(RAW_EX_1 .format(new Object[] { bomEnc, xmlGuessEnc, xmlEnc }), bomEnc, xmlGuessEnc, xmlEnc, is); } if (xmlEnc != null && !xmlEnc.equals(UTF_8)) { throw new XmlStreamReaderException(RAW_EX_1 .format(new Object[] { bomEnc, xmlGuessEnc, xmlEnc }), bomEnc, xmlGuessEnc, xmlEnc, is); } encoding = UTF_8; } else if (bomEnc.equals(UTF_16BE) || bomEnc.equals(UTF_16LE)) { if (xmlGuessEnc != null && !xmlGuessEnc.equals(bomEnc)) { throw new XmlStreamReaderException(RAW_EX_1.format(new Object[] { bomEnc, xmlGuessEnc, xmlEnc }), bomEnc, xmlGuessEnc, xmlEnc, is); } if (xmlEnc != null && !xmlEnc.equals(UTF_16) && !xmlEnc.equals(bomEnc)) { throw new XmlStreamReaderException(RAW_EX_1 .format(new Object[] { bomEnc, xmlGuessEnc, xmlEnc }), bomEnc, xmlGuessEnc, xmlEnc, is); } encoding = bomEnc; } else if (bomEnc.equals(UTF_32BE) || bomEnc.equals(UTF_32LE)) { if (xmlGuessEnc != null && !xmlGuessEnc.equals(bomEnc)) { throw new XmlStreamReaderException(RAW_EX_1.format(new Object[] { bomEnc, xmlGuessEnc, xmlEnc }), bomEnc, xmlGuessEnc, xmlEnc, is); } if (xmlEnc != null && !xmlEnc.equals(UTF_32) && !xmlEnc.equals(bomEnc)) { throw new XmlStreamReaderException(RAW_EX_1 .format(new Object[] { bomEnc, xmlGuessEnc, xmlEnc }), bomEnc, xmlGuessEnc, xmlEnc, is); } encoding = bomEnc; } else { throw new XmlStreamReaderException(RAW_EX_2.format(new Object[] { bomEnc, xmlGuessEnc, xmlEnc }), bomEnc, xmlGuessEnc, xmlEnc, is); } return encoding; } // InputStream is passed for XmlStreamReaderException creation only String calculateHttpEncoding(String cTMime, String cTEnc, String bomEnc, String xmlGuessEnc, String xmlEnc, InputStream is, boolean lenient) throws IOException { String encoding; if (lenient & xmlEnc != null) { encoding = xmlEnc; } else { boolean appXml = isAppXml(cTMime); boolean textXml = isTextXml(cTMime); if (appXml || textXml) { if (cTEnc == null) { if (appXml) { encoding = calculateRawEncoding(bomEnc, xmlGuessEnc, xmlEnc, is); } else { encoding = defaultEncoding == null ? US_ASCII : defaultEncoding; } } else if (bomEnc != null && (cTEnc.equals(UTF_16BE) || cTEnc.equals(UTF_16LE))) { throw new XmlStreamReaderException(HTTP_EX_1 .format(new Object[] { cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc }), cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc, is); } else if (cTEnc.equals(UTF_16)) { if (bomEnc != null && bomEnc.startsWith(UTF_16)) { encoding = bomEnc; } else { throw new XmlStreamReaderException(HTTP_EX_2 .format(new Object[] { cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc }), cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc, is); } } else if (bomEnc != null && (cTEnc.equals(UTF_32BE) || cTEnc.equals(UTF_32LE))) { throw new XmlStreamReaderException(HTTP_EX_1 .format(new Object[] { cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc }), cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc, is); } else if (cTEnc.equals(UTF_32)) { if (bomEnc != null && bomEnc.startsWith(UTF_32)) { encoding = bomEnc; } else { throw new XmlStreamReaderException(HTTP_EX_2 .format(new Object[] { cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc }), cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc, is); } } else { encoding = cTEnc; } } else { throw new XmlStreamReaderException(HTTP_EX_3 .format(new Object[] { cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc }), cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc, is); } } return encoding; } // returns MIME type or NULL if httpContentType is NULL static String getContentTypeMime(String httpContentType) { String mime = null; if (httpContentType != null) { int i = httpContentType.indexOf(";"); mime = (i == -1 ? httpContentType : httpContentType.substring(0, i)).trim(); } return mime; } private static final Pattern CHARSET_PATTERN = Pattern .compile("charset=[\"']?([.[^; \"']]*)[\"']?"); // returns charset parameter value, NULL if not present, NULL if // httpContentType is NULL static String getContentTypeEncoding(String httpContentType) { String encoding = null; if (httpContentType != null) { int i = httpContentType.indexOf(";"); if (i > -1) { String postMime = httpContentType.substring(i + 1); Matcher m = CHARSET_PATTERN.matcher(postMime); encoding = m.find() ? m.group(1) : null; encoding = encoding != null ? encoding.toUpperCase() : null; } } return encoding; } // returns the BOM in the stream, NULL if not present, // if there was BOM the in the stream it is consumed static String getBOMEncoding(BufferedInputStream is) throws IOException { String encoding = null; int[] bytes = new int[3]; is.mark(3); bytes[0] = is.read(); bytes[1] = is.read(); bytes[2] = is.read(); if (bytes[0] == 0xFE && bytes[1] == 0xFF) { encoding = UTF_16BE; is.reset(); is.read(); is.read(); } else if (bytes[0] == 0xFF && bytes[1] == 0xFE) { encoding = UTF_16LE; is.reset(); is.read(); is.read(); } else if (bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF) { encoding = UTF_8; } else { is.reset(); } return encoding; } // returns the best guess for the encoding by looking the first bytes of the // stream, ', NULL if none private static String getXmlProlog(BufferedInputStream is, String guessedEnc) throws IOException { String encoding = null; if (guessedEnc != null) { byte[] bytes = new byte[BUFFER_SIZE]; is.mark(BUFFER_SIZE); int offset = 0; int max = BUFFER_SIZE; int c = is.read(bytes, offset, max); int firstGT = -1; String xmlProlog = null; while (c != -1 && firstGT == -1 && offset < BUFFER_SIZE) { offset += c; max -= c; c = is.read(bytes, offset, max); xmlProlog = new String(bytes, 0, offset, guessedEnc); firstGT = xmlProlog.indexOf('>'); } if (firstGT == -1) { if (c == -1) { throw new IOException("Unexpected end of XML stream"); } else { throw new IOException( "XML prolog or ROOT element not found on first " + offset + " bytes"); } } int bytesRead = offset; if (bytesRead > 0) { is.reset(); BufferedReader bReader = new BufferedReader(new StringReader( xmlProlog.substring(0, firstGT + 1))); StringBuffer prolog = new StringBuffer(); String line = bReader.readLine(); while (line != null) { prolog.append(line); line = bReader.readLine(); } Matcher m = ENCODING_PATTERN.matcher(prolog); if (m.find()) { encoding = m.group(1).toUpperCase(); encoding = encoding.substring(1, encoding.length() - 1); } } } return encoding; } // indicates if the MIME type belongs to the APPLICATION XML family static boolean isAppXml(String mime) { return mime != null && (mime.equals("application/xml") || mime.equals("application/xml-dtd") || mime .equals("application/xml-external-parsed-entity") || mime .startsWith("application/") && mime.endsWith("+xml")); } // indicates if the MIME type belongs to the TEXT XML family static boolean isTextXml(String mime) { return mime != null && (mime.equals("text/xml") || mime.equals("text/xml-external-parsed-entity") || mime .startsWith("text/") && mime.endsWith("+xml")); } private static final MessageFormat RAW_EX_1 = new MessageFormat( "Invalid encoding, BOM [{0}] XML guess [{1}] XML prolog [{2}] encoding mismatch"); private static final MessageFormat RAW_EX_2 = new MessageFormat( "Invalid encoding, BOM [{0}] XML guess [{1}] XML prolog [{2}] unknown BOM"); private static final MessageFormat HTTP_EX_1 = new MessageFormat( "Invalid encoding, CT-MIME [{0}] CT-Enc [{1}] BOM [{2}] XML guess [{3}] XML prolog [{4}], BOM must be NULL"); private static final MessageFormat HTTP_EX_2 = new MessageFormat( "Invalid encoding, CT-MIME [{0}] CT-Enc [{1}] BOM [{2}] XML guess [{3}] XML prolog [{4}], encoding mismatch"); private static final MessageFormat HTTP_EX_3 = new MessageFormat( "Invalid encoding, CT-MIME [{0}] CT-Enc [{1}] BOM [{2}] XML guess [{3}] XML prolog [{4}], Invalid MIME"); } ././@LongLink0000000000000000000000000000020300000000000011560 Lustar rootrootlibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/input/compatibility/XmlStreamReaderUtilitiesCompatibilityTest.javalibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/input/compatibility/XmlStreamReaderU0000644000175000017500000000444412125050425033236 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input.compatibility; import java.io.ByteArrayInputStream; import java.io.IOException; import org.apache.commons.io.input.XmlStreamReaderUtilitiesTest; /** * Test compatibility of the original XmlStreamReader (before all the refactoring). */ public class XmlStreamReaderUtilitiesCompatibilityTest extends XmlStreamReaderUtilitiesTest { @Override protected String calculateRawEncoding(String bomEnc, String xmlGuessEnc, String xmlEnc, String defaultEncoding) throws IOException { MockXmlStreamReader mock = new MockXmlStreamReader(defaultEncoding); return mock.calculateRawEncoding(bomEnc, xmlGuessEnc, xmlEnc, null); } @Override protected String calculateHttpEncoding(String httpContentType, String bomEnc, String xmlGuessEnc, String xmlEnc, boolean lenient, String defaultEncoding) throws IOException { MockXmlStreamReader mock = new MockXmlStreamReader(defaultEncoding); return mock.calculateHttpEncoding( XmlStreamReader.getContentTypeMime(httpContentType), XmlStreamReader.getContentTypeEncoding(httpContentType), bomEnc, xmlGuessEnc, xmlEnc, null, lenient); } /** Mock {@link XmlStreamReader} implementation */ private static class MockXmlStreamReader extends XmlStreamReader { MockXmlStreamReader(String defaultEncoding) throws IOException { super(new ByteArrayInputStream("".getBytes()), null, true, defaultEncoding); } } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/input/compatibility/XmlStreamReaderException.javalibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/input/compatibility/XmlStreamReaderE0000644000175000017500000000633412125050425033216 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input.compatibility; import java.io.InputStream; /** * The XmlStreamReaderException is thrown by the XmlStreamReader constructors if * the charset encoding can not be determined according to the XML 1.0 * specification and RFC 3023. *

* The exception returns the unconsumed InputStream to allow the application to * do an alternate processing with the stream. Note that the original * InputStream given to the XmlStreamReader cannot be used as that one has been * already read. * * @version $Id: XmlStreamReaderException.java 1302056 2012-03-18 03:03:38Z ggregory $ */ public class XmlStreamReaderException extends org.apache.commons.io.input.XmlStreamReaderException { private static final long serialVersionUID = 1L; private final InputStream is; /** * Creates an exception instance if the charset encoding could not be * determined. *

* Instances of this exception are thrown by the XmlStreamReader. * * @param msg message describing the reason for the exception. * @param bomEnc BOM encoding. * @param xmlGuessEnc XML guess encoding. * @param xmlEnc XML prolog encoding. * @param is the unconsumed InputStream. */ public XmlStreamReaderException(String msg, String bomEnc, String xmlGuessEnc, String xmlEnc, InputStream is) { this(msg, null, null, bomEnc, xmlGuessEnc, xmlEnc, is); } /** * Creates an exception instance if the charset encoding could not be * determined. *

* Instances of this exception are thrown by the XmlStreamReader. * * @param msg message describing the reason for the exception. * @param ctMime MIME type in the content-type. * @param ctEnc encoding in the content-type. * @param bomEnc BOM encoding. * @param xmlGuessEnc XML guess encoding. * @param xmlEnc XML prolog encoding. * @param is the unconsumed InputStream. */ public XmlStreamReaderException(String msg, String ctMime, String ctEnc, String bomEnc, String xmlGuessEnc, String xmlEnc, InputStream is) { super(msg, ctMime, ctEnc, bomEnc, xmlGuessEnc, xmlEnc); this.is = is; } /** * Returns the unconsumed InputStream to allow the application to do an * alternate encoding detection on the InputStream. * * @return the unconsumed InputStream. */ public InputStream getInputStream() { return is; } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/input/CharSequenceReaderTest.java0000644000175000017500000001107112125050425032444 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.io.Reader; import org.junit.Test; /** * Test case for {@link CharSequenceReader}. * * @version $Id: CharSequenceReaderTest.java 1302056 2012-03-18 03:03:38Z ggregory $ */ public class CharSequenceReaderTest { private static final char NONE = (new char[1])[0]; /** Test {@link Reader#close()}. */ @Test public void testClose() throws IOException { Reader reader = new CharSequenceReader("FooBar"); checkRead(reader, "Foo"); reader.close(); checkRead(reader, "Foo"); } /** Test {@link Reader#markSupported()}. */ @Test public void testMarkSupported() { Reader reader = new CharSequenceReader("FooBar"); assertTrue(reader.markSupported()); } /** Test {@link Reader#mark(int)}. */ @Test public void testMark() throws IOException { Reader reader = new CharSequenceReader("FooBar"); checkRead(reader, "Foo"); reader.mark(0); checkRead(reader, "Bar"); reader.reset(); checkRead(reader, "Bar"); reader.close(); checkRead(reader, "Foo"); reader.reset(); checkRead(reader, "Foo"); } /** Test {@link Reader#skip(long)}. */ @Test public void testSkip() throws IOException { Reader reader = new CharSequenceReader("FooBar"); assertEquals(3, reader.skip(3)); checkRead(reader, "Bar"); assertEquals(-1, reader.skip(3)); reader.reset(); assertEquals(2, reader.skip(2)); assertEquals(4, reader.skip(10)); assertEquals(-1, reader.skip(1)); reader.close(); assertEquals(6, reader.skip(20)); assertEquals(-1, reader.read()); } /** Test {@link Reader#read()}. */ @Test public void testRead() throws IOException { Reader reader = new CharSequenceReader("Foo"); assertEquals('F', reader.read()); assertEquals('o', reader.read()); assertEquals('o', reader.read()); assertEquals(-1, reader.read()); assertEquals(-1, reader.read()); } /** Test {@link Reader#read(char[])}. */ @Test public void testReadCharArray() throws IOException { Reader reader = new CharSequenceReader("FooBar"); char[] chars = new char[2]; assertEquals(2, reader.read(chars)); checkArray(new char[] {'F', 'o'}, chars); chars = new char[3]; assertEquals(3, reader.read(chars)); checkArray(new char[] {'o', 'B', 'a'}, chars); chars = new char[3]; assertEquals(1, reader.read(chars)); checkArray(new char[] {'r', NONE, NONE}, chars); assertEquals(-1, reader.read(chars)); } /** Test {@link Reader#read(char[], int, int)}. */ @Test public void testReadCharArrayPortion() throws IOException { char[] chars = new char[10]; Reader reader = new CharSequenceReader("FooBar"); assertEquals(3, reader.read(chars, 3, 3)); checkArray(new char[] {NONE, NONE, NONE, 'F', 'o', 'o'}, chars); assertEquals(3, reader.read(chars, 0, 3)); checkArray(new char[] {'B', 'a', 'r', 'F', 'o', 'o', NONE}, chars); assertEquals(-1, reader.read(chars)); } private void checkRead(Reader reader, String expected) throws IOException { for (int i = 0; i < expected.length(); i++) { assertEquals("Read[" + i + "] of '" + expected + "'", expected.charAt(i), (char)reader.read()); } } private void checkArray(char[] expected, char[] actual) { for (int i = 0; i < expected.length; i++) { assertEquals("Compare[" +i + "]", expected[i], actual[i]); } } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/input/CloseShieldInputStreamTest.javalibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/input/CloseShieldInputStreamTest.jav0000644000175000017500000000347612125050425033216 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import junit.framework.TestCase; /** * JUnit Test Case for {@link CloseShieldInputStream}. */ public class CloseShieldInputStreamTest extends TestCase { private byte[] data; private InputStream original; private InputStream shielded; private boolean closed; @Override protected void setUp() { data = new byte[] { 'x', 'y', 'z' }; original = new ByteArrayInputStream(data) { @Override public void close() { closed = true; } }; shielded = new CloseShieldInputStream(original); closed = false; } /** * Test the close() method. */ public void testClose() throws IOException { shielded.close(); assertFalse("closed", closed); assertEquals("read()", -1, shielded.read()); assertEquals("read()", data[0], original.read()); } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/DirectoryWalkerTestCase.java0000644000175000017500000005164612125050425031536 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import junit.framework.Assert; import org.apache.commons.io.filefilter.FileFilterUtils; import org.apache.commons.io.filefilter.IOFileFilter; import org.apache.commons.io.filefilter.NameFileFilter; import org.apache.commons.io.filefilter.OrFileFilter; import org.junit.Test; /** * This is used to test DirectoryWalker for correctness. * * @version $Id: DirectoryWalkerTestCase.java 1311751 2012-04-10 14:26:21Z ggregory $ * @see DirectoryWalker * */ public class DirectoryWalkerTestCase { // Directories private static final File current = new File("."); private static final File javaDir = new File("src/main/java"); private static final File orgDir = new File(javaDir, "org"); private static final File apacheDir = new File(orgDir, "apache"); private static final File commonsDir = new File(apacheDir, "commons"); private static final File ioDir = new File(commonsDir, "io"); private static final File outputDir = new File(ioDir, "output"); private static final File[] dirs = new File[] {orgDir, apacheDir, commonsDir, ioDir, outputDir}; // Files private static final File filenameUtils = new File(ioDir, "FilenameUtils.java"); private static final File ioUtils = new File(ioDir, "IOUtils.java"); private static final File proxyWriter = new File(outputDir, "ProxyWriter.java"); private static final File nullStream = new File(outputDir, "NullOutputStream.java"); private static final File[] ioFiles = new File[] {filenameUtils, ioUtils}; private static final File[] outputFiles = new File[] {proxyWriter, nullStream}; // Filters private static final IOFileFilter dirsFilter = createNameFilter(dirs); private static final IOFileFilter iofilesFilter = createNameFilter(ioFiles); private static final IOFileFilter outputFilesFilter = createNameFilter(outputFiles); private static final IOFileFilter ioDirAndFilesFilter = new OrFileFilter(dirsFilter, iofilesFilter); private static final IOFileFilter dirsAndFilesFilter = new OrFileFilter(ioDirAndFilesFilter, outputFilesFilter); // Filter to exclude SVN files private static final IOFileFilter NOT_SVN = FileFilterUtils.makeSVNAware(null); //----------------------------------------------------------------------- /** * Test Filtering */ @Test public void testFilter() { List results = new TestFileFinder(dirsAndFilesFilter, -1).find(javaDir); assertEquals("Result Size", 1 + dirs.length + ioFiles.length + outputFiles.length, results.size()); assertTrue("Start Dir", results.contains(javaDir)); checkContainsFiles("Dir", dirs, results); checkContainsFiles("IO File", ioFiles, results); checkContainsFiles("Output File", outputFiles, results); } /** * Test Filtering and limit to depth 0 */ @Test public void testFilterAndLimitA() { List results = new TestFileFinder(NOT_SVN, 0).find(javaDir); assertEquals("[A] Result Size", 1, results.size()); assertTrue("[A] Start Dir", results.contains(javaDir)); } /** * Test Filtering and limit to depth 1 */ @Test public void testFilterAndLimitB() { List results = new TestFileFinder(NOT_SVN, 1).find(javaDir); assertEquals("[B] Result Size", 2, results.size()); assertTrue("[B] Start Dir", results.contains(javaDir)); assertTrue("[B] Org Dir", results.contains(orgDir)); } /** * Test Filtering and limit to depth 3 */ @Test public void testFilterAndLimitC() { List results = new TestFileFinder(NOT_SVN, 3).find(javaDir); assertEquals("[C] Result Size", 4, results.size()); assertTrue("[C] Start Dir", results.contains(javaDir)); assertTrue("[C] Org Dir", results.contains(orgDir)); assertTrue("[C] Apache Dir", results.contains(apacheDir)); assertTrue("[C] Commons Dir", results.contains(commonsDir)); } /** * Test Filtering and limit to depth 5 */ @Test public void testFilterAndLimitD() { List results = new TestFileFinder(dirsAndFilesFilter, 5).find(javaDir); assertEquals("[D] Result Size", 1 + dirs.length + ioFiles.length, results.size()); assertTrue("[D] Start Dir", results.contains(javaDir)); checkContainsFiles("[D] Dir", dirs, results); checkContainsFiles("[D] File", ioFiles, results); } /** * Test separate dir and file filters */ @Test public void testFilterDirAndFile1() { List results = new TestFileFinder(dirsFilter, iofilesFilter, -1).find(javaDir); assertEquals("[DirAndFile1] Result Size", 1 + dirs.length + ioFiles.length, results.size()); assertTrue("[DirAndFile1] Start Dir", results.contains(javaDir)); checkContainsFiles("[DirAndFile1] Dir", dirs, results); checkContainsFiles("[DirAndFile1] File", ioFiles, results); } /** * Test separate dir and file filters */ @Test public void testFilterDirAndFile2() { List results = new TestFileFinder((IOFileFilter) null, (IOFileFilter) null, -1).find(javaDir); assertTrue("[DirAndFile2] Result Size", results.size() > 1 + dirs.length + ioFiles.length); assertTrue("[DirAndFile2] Start Dir", results.contains(javaDir)); checkContainsFiles("[DirAndFile2] Dir", dirs, results); checkContainsFiles("[DirAndFile2] File", ioFiles, results); } /** * Test separate dir and file filters */ @Test public void testFilterDirAndFile3() { List results = new TestFileFinder(dirsFilter, (IOFileFilter) null, -1).find(javaDir); List resultDirs = directoriesOnly(results); assertEquals("[DirAndFile3] Result Size", 1 + dirs.length, resultDirs.size()); assertTrue("[DirAndFile3] Start Dir", results.contains(javaDir)); checkContainsFiles("[DirAndFile3] Dir", dirs, resultDirs); } /** * Test separate dir and file filters */ @Test public void testFilterDirAndFile4() { List results = new TestFileFinder((IOFileFilter) null, iofilesFilter, -1).find(javaDir); List resultFiles = filesOnly(results); assertEquals("[DirAndFile4] Result Size", ioFiles.length, resultFiles.size()); assertTrue("[DirAndFile4] Start Dir", results.contains(javaDir)); checkContainsFiles("[DirAndFile4] File", ioFiles, resultFiles); } /** * Test Limiting to current directory */ @Test public void testLimitToCurrent() { List results = new TestFileFinder(null, 0).find(current); assertEquals("Result Size", 1, results.size()); assertTrue("Current Dir", results.contains(new File("."))); } /** * test an invalid start directory */ @Test public void testMissingStartDirectory() { // TODO is this what we want with invalid directory? File invalidDir = new File("invalid-dir"); List results = new TestFileFinder(null, -1).find(invalidDir); assertEquals("Result Size", 1, results.size()); assertTrue("Current Dir", results.contains(invalidDir)); try { new TestFileFinder(null, -1).find(null); fail("Null start directory didn't throw Exception"); } catch (NullPointerException ignore) { // expected result } } /** * test an invalid start directory */ @Test public void testHandleStartDirectoryFalse() { List results = new TestFalseFileFinder(null, -1).find(current); assertEquals("Result Size", 0, results.size()); } // ------------ Convenience Test Methods ------------------------------------ /** * Check the files in the array are in the results list. */ private void checkContainsFiles(String prefix, File[] files, Collection results) { for (int i = 0; i < files.length; i++) { assertTrue(prefix + "["+i+"] " + files[i], results.contains(files[i])); } } private void checkContainsString(String prefix, File[] files, Collection results) { for (int i = 0; i < files.length; i++) { assertTrue(prefix + "["+i+"] " + files[i], results.contains(files[i].toString())); } } /** * Extract the directories. */ private List directoriesOnly(Collection results) { List list = new ArrayList(results.size()); for (File file : results) { if (file.isDirectory()) { list.add(file); } } return list; } /** * Extract the files. */ private List filesOnly(Collection results) { List list = new ArrayList(results.size()); for (File file : results) { if (file.isFile()) { list.add(file); } } return list; } /** * Create an name filter containg the names of the files * in the array. */ private static IOFileFilter createNameFilter(File[] files) { String[] names = new String[files.length]; for (int i = 0; i < files.length; i++) { names[i] = files[i].getName(); } return new NameFileFilter(names); } /** * Test Cancel */ @Test public void testCancel() { String cancelName = null; // Cancel on a file try { cancelName = "DirectoryWalker.java"; new TestCancelWalker(cancelName, false).find(javaDir); fail("CancelException not thrown for '" + cancelName + "'"); } catch (DirectoryWalker.CancelException cancel) { assertEquals("File: " + cancelName, cancelName, cancel.getFile().getName()); assertEquals("Depth: " + cancelName, 5, cancel.getDepth()); } catch(IOException ex) { fail("IOException: " + cancelName + " " + ex); } // Cancel on a directory try { cancelName = "commons"; new TestCancelWalker(cancelName, false).find(javaDir); fail("CancelException not thrown for '" + cancelName + "'"); } catch (DirectoryWalker.CancelException cancel) { assertEquals("File: " + cancelName, cancelName, cancel.getFile().getName()); assertEquals("Depth: " + cancelName, 3, cancel.getDepth()); } catch(IOException ex) { fail("IOException: " + cancelName + " " + ex); } // Suppress CancelException (use same file name as preceeding test) try { List results = new TestCancelWalker(cancelName, true).find(javaDir); File lastFile = results.get(results.size() - 1); assertEquals("Suppress: " + cancelName, cancelName, lastFile.getName()); } catch(IOException ex) { fail("Suppress threw " + ex); } } /** * Test Cancel */ @Test public void testMultiThreadCancel() { String cancelName = "DirectoryWalker.java"; TestMultiThreadCancelWalker walker = new TestMultiThreadCancelWalker(cancelName, false); // Cancel on a file try { walker.find(javaDir); fail("CancelException not thrown for '" + cancelName + "'"); } catch (DirectoryWalker.CancelException cancel) { File last = walker.results.get(walker.results.size() - 1); assertEquals(cancelName, last.getName()); assertEquals("Depth: " + cancelName, 5, cancel.getDepth()); } catch(IOException ex) { fail("IOException: " + cancelName + " " + ex); } // Cancel on a directory try { cancelName = "commons"; walker = new TestMultiThreadCancelWalker(cancelName, false); walker.find(javaDir); fail("CancelException not thrown for '" + cancelName + "'"); } catch (DirectoryWalker.CancelException cancel) { assertEquals("File: " + cancelName, cancelName, cancel.getFile().getName()); assertEquals("Depth: " + cancelName, 3, cancel.getDepth()); } catch(IOException ex) { fail("IOException: " + cancelName + " " + ex); } // Suppress CancelException (use same file name as preceeding test) try { walker = new TestMultiThreadCancelWalker(cancelName, true); List results = walker.find(javaDir); File lastFile = results.get(results.size() - 1); assertEquals("Suppress: " + cancelName, cancelName, lastFile.getName()); } catch(IOException ex) { fail("Suppress threw " + ex); } } /** * Test Filtering */ @Test public void testFilterString() { List results = new TestFileFinderString(dirsAndFilesFilter, -1).find(javaDir); assertEquals("Result Size", outputFiles.length + ioFiles.length, results.size()); checkContainsString("IO File", ioFiles, results); checkContainsString("Output File", outputFiles, results); } // ------------ Test DirectoryWalker implementation -------------------------- /** * Test DirectoryWalker implementation that finds files in a directory hierarchy * applying a file filter. */ private static class TestFileFinder extends DirectoryWalker { protected TestFileFinder(FileFilter filter, int depthLimit) { super(filter, depthLimit); } protected TestFileFinder(IOFileFilter dirFilter, IOFileFilter fileFilter, int depthLimit) { super(dirFilter, fileFilter, depthLimit); } /** find files. */ protected List find(File startDirectory) { List results = new ArrayList(); try { walk(startDirectory, results); } catch(IOException ex) { Assert.fail(ex.toString()); } return results; } /** Handles a directory end by adding the File to the result set. */ @Override protected void handleDirectoryEnd(File directory, int depth, Collection results) { results.add(directory); } /** Handles a file by adding the File to the result set. */ @Override protected void handleFile(File file, int depth, Collection results) { results.add(file); } } // ------------ Test DirectoryWalker implementation -------------------------- /** * Test DirectoryWalker implementation that always returns false * from handleDirectoryStart() */ private static class TestFalseFileFinder extends TestFileFinder { protected TestFalseFileFinder(FileFilter filter, int depthLimit) { super(filter, depthLimit); } /** Always returns false. */ @Override protected boolean handleDirectory(File directory, int depth, Collection results) { return false; } } // ------------ Test DirectoryWalker implementation -------------------------- /** * Test DirectoryWalker implementation that finds files in a directory hierarchy * applying a file filter. */ static class TestCancelWalker extends DirectoryWalker { private String cancelFileName; private boolean suppressCancel; TestCancelWalker(String cancelFileName,boolean suppressCancel) { super(); this.cancelFileName = cancelFileName; this.suppressCancel = suppressCancel; } /** find files. */ protected List find(File startDirectory) throws IOException { List results = new ArrayList(); walk(startDirectory, results); return results; } /** Handles a directory end by adding the File to the result set. */ @Override protected void handleDirectoryEnd(File directory, int depth, Collection results) throws IOException { results.add(directory); if (cancelFileName.equals(directory.getName())) { throw new CancelException(directory, depth); } } /** Handles a file by adding the File to the result set. */ @Override protected void handleFile(File file, int depth, Collection results) throws IOException { results.add(file); if (cancelFileName.equals(file.getName())) { throw new CancelException(file, depth); } } /** Handles Cancel. */ @Override protected void handleCancelled(File startDirectory, Collection results, CancelException cancel) throws IOException { if (!suppressCancel) { super.handleCancelled(startDirectory, results, cancel); } } } /** * Test DirectoryWalker implementation that finds files in a directory hierarchy * applying a file filter. */ static class TestMultiThreadCancelWalker extends DirectoryWalker { private String cancelFileName; private boolean suppressCancel; private boolean cancelled; public List results; TestMultiThreadCancelWalker(String cancelFileName, boolean suppressCancel) { super(); this.cancelFileName = cancelFileName; this.suppressCancel = suppressCancel; } /** find files. */ protected List find(File startDirectory) throws IOException { results = new ArrayList(); walk(startDirectory, results); return results; } /** Handles a directory end by adding the File to the result set. */ @Override protected void handleDirectoryEnd(File directory, int depth, Collection results) throws IOException { results.add(directory); assertFalse(cancelled); if (cancelFileName.equals(directory.getName())) { cancelled = true; } } /** Handles a file by adding the File to the result set. */ @Override protected void handleFile(File file, int depth, Collection results) throws IOException { results.add(file); assertFalse(cancelled); if (cancelFileName.equals(file.getName())) { cancelled = true; } } /** Handles Cancelled. */ @Override protected boolean handleIsCancelled(File file, int depth, Collection results) throws IOException { return cancelled; } /** Handles Cancel. */ @Override protected void handleCancelled(File startDirectory, Collection results, CancelException cancel) throws IOException { if (!suppressCancel) { super.handleCancelled(startDirectory, results, cancel); } } } /** * Test DirectoryWalker implementation that finds files in a directory hierarchy * applying a file filter. */ private static class TestFileFinderString extends DirectoryWalker { protected TestFileFinderString(FileFilter filter, int depthLimit) { super(filter, depthLimit); } /** find files. */ protected List find(File startDirectory) { List results = new ArrayList(); try { walk(startDirectory, results); } catch(IOException ex) { Assert.fail(ex.toString()); } return results; } /** Handles a file by adding the File to the result set. */ @Override protected void handleFile(File file, int depth, Collection results) { results.add(file.toString()); } } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/IOUtilsTestCase.java0000644000175000017500000011216312125050425027744 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.CharArrayReader; import java.io.CharArrayWriter; import java.io.Closeable; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; import java.net.ServerSocket; import java.net.Socket; import java.net.URI; import java.net.URL; import java.net.URLConnection; import java.nio.channels.Selector; import java.util.Arrays; import java.util.List; import org.apache.commons.io.testtools.FileBasedTestCase; import org.junit.Assert; /** * This is used to test IOUtils for correctness. The following checks are performed: *

    *
  • The return must not be null, must be the same type and equals() to the method's second arg
  • *
  • All bytes must have been read from the source (available() == 0)
  • *
  • The source and destination content must be identical (byte-wise comparison check)
  • *
  • The output stream must not have been closed (a byte/char is written to test this, and subsequent size checked)
  • *
* Due to interdependencies in IOUtils and IOUtilsTestlet, one bug may cause multiple tests to fail. */ public class IOUtilsTestCase extends FileBasedTestCase { /** Determine if this is windows. */ private static final boolean WINDOWS = File.separatorChar == '\\'; /* * Note: this is not particularly beautiful code. A better way to check for flush and close status would be to * implement "trojan horse" wrapper implementations of the various stream classes, which set a flag when relevant * methods are called. (JT) */ private static final int FILE_SIZE = 1024 * 4 + 1; private File m_testFile; @Override public void setUp() { try { getTestDirectory().mkdirs(); m_testFile = new File(getTestDirectory(), "file2-test.txt"); createFile(m_testFile, FILE_SIZE); } catch (IOException ioe) { throw new RuntimeException("Can't run this test because the environment could not be built: " + ioe.getMessage()); } // Create and init a byte array as input data iarr = new byte[200]; Arrays.fill( iarr, (byte)-1); for( int i=0; i< 80; i++){ iarr[i] = (byte) i; } carr = new char[200]; Arrays.fill( carr, (char)-1); for( int i=0; i< 80; i++){ carr[i] = (char) i; } } @Override public void tearDown() { carr = null; iarr = null; try { FileUtils.deleteDirectory(getTestDirectory()); } catch (IOException e) { throw new RuntimeException("Could not clear up " + getTestDirectory() + ": " + e); } } public IOUtilsTestCase(String name) { super(name); } public void testCloseQuietlyNullSelector() { Selector selector = null; IOUtils.closeQuietly(selector); } public void testCloseableCloseQuietlyOnException() { IOUtils.closeQuietly(new Closeable() { public void close() throws IOException { throw new IOException(); } }); } public void testSocketCloseQuietlyOnException() { IOUtils.closeQuietly(new Socket() { @Override public void close() throws IOException { throw new IOException(); } }); } public void testServerSocketCloseQuietlyOnException() throws IOException { IOUtils.closeQuietly(new ServerSocket() { @Override public void close() throws IOException { throw new IOException(); } }); } public void testSocketCloseQuietly() { IOUtils.closeQuietly((Socket) null); IOUtils.closeQuietly(new Socket()); } public void testServerSocketCloseQuietly() throws IOException { IOUtils.closeQuietly((ServerSocket) null); IOUtils.closeQuietly(new ServerSocket()); } public void testCloseQuietlySelector() { Selector selector = null; try { selector = Selector.open(); } catch (IOException e) { } finally { IOUtils.closeQuietly(selector); } } public void testCloseQuietlySelectorIOException() { Selector selector = new SelectorAdapter() { @Override public void close() throws IOException { throw new IOException(); } }; IOUtils.closeQuietly(selector); } public void testCloseQuietlySelectorTwice() { Selector selector = null; try { selector = Selector.open(); } catch (IOException e) { } finally { IOUtils.closeQuietly(selector); IOUtils.closeQuietly(selector); } } // ----------------------------------------------------------------------- public void testConstants() throws Exception { assertEquals('/', IOUtils.DIR_SEPARATOR_UNIX); assertEquals('\\', IOUtils.DIR_SEPARATOR_WINDOWS); assertEquals("\n", IOUtils.LINE_SEPARATOR_UNIX); assertEquals("\r\n", IOUtils.LINE_SEPARATOR_WINDOWS); if (WINDOWS) { assertEquals('\\', IOUtils.DIR_SEPARATOR); assertEquals("\r\n", IOUtils.LINE_SEPARATOR); } else { assertEquals('/', IOUtils.DIR_SEPARATOR); assertEquals("\n", IOUtils.LINE_SEPARATOR); } } // ----------------------------------------------------------------------- /** Assert that the contents of two byte arrays are the same. */ private void assertEqualContent(byte[] b0, byte[] b1) { assertTrue("Content not equal according to java.util.Arrays#equals()", Arrays.equals(b0, b1)); } public void testInputStreamToString() throws Exception { FileInputStream fin = new FileInputStream(m_testFile); try { String out = IOUtils.toString(fin); assertNotNull(out); assertEquals("Not all bytes were read", 0, fin.available()); assertEquals("Wrong output size", FILE_SIZE, out.length()); } finally { fin.close(); } } public void testReaderToString() throws Exception { FileReader fin = new FileReader(m_testFile); try { String out = IOUtils.toString(fin); assertNotNull(out); assertEquals("Wrong output size", FILE_SIZE, out.length()); } finally { fin.close(); } } @SuppressWarnings("deprecation") // testing deprecated method public void testStringToOutputStream() throws Exception { File destination = newFile("copy5.txt"); FileReader fin = new FileReader(m_testFile); String str; try { // Create our String. Rely on testReaderToString() to make sure this is valid. str = IOUtils.toString(fin); } finally { fin.close(); } FileOutputStream fout = new FileOutputStream(destination); try { CopyUtils.copy(str, fout); // Note: this method *does* flush. It is equivalent to: // OutputStreamWriter _out = new OutputStreamWriter(fout); // CopyUtils.copy( str, _out, 4096 ); // copy( Reader, Writer, int ); // _out.flush(); // out = fout; // note: we don't flush here; this IOUtils method does it for us checkFile(destination, m_testFile); checkWrite(fout); } finally { fout.close(); } deleteFile(destination); } @SuppressWarnings("deprecation") // testing deprecated method public void testStringToWriter() throws Exception { File destination = newFile("copy6.txt"); FileReader fin = new FileReader(m_testFile); String str; try { // Create our String. Rely on testReaderToString() to make sure this is valid. str = IOUtils.toString(fin); } finally { fin.close(); } FileWriter fout = new FileWriter(destination); try { CopyUtils.copy(str, fout); fout.flush(); checkFile(destination, m_testFile); checkWrite(fout); } finally { fout.close(); } deleteFile(destination); } public void testToByteArray_Reader() throws IOException { final String charsetName = "UTF-8"; final byte[] expecteds = charsetName.getBytes(charsetName); byte[] actuals = IOUtils.toByteArray(new InputStreamReader(new ByteArrayInputStream(expecteds))); Assert.assertArrayEquals(expecteds, actuals); actuals = IOUtils.toByteArray(new InputStreamReader(new ByteArrayInputStream(expecteds)), charsetName); Assert.assertArrayEquals(expecteds, actuals); } public void testInputStreamToByteArray() throws Exception { FileInputStream fin = new FileInputStream(m_testFile); try { byte[] out = IOUtils.toByteArray(fin); assertNotNull(out); assertEquals("Not all bytes were read", 0, fin.available()); assertEquals("Wrong output size", FILE_SIZE, out.length); assertEqualContent(out, m_testFile); } finally { fin.close(); } } public void testInputStreamToByteArray_Size() throws Exception { FileInputStream fin = new FileInputStream(m_testFile); try { byte[] out = IOUtils.toByteArray(fin, m_testFile.length()); assertNotNull(out); assertEquals("Not all bytes were read", 0, fin.available()); assertEquals("Wrong output size: out.length=" + out.length + "!=" + FILE_SIZE, FILE_SIZE, out.length); assertEqualContent(out, m_testFile); } finally { fin.close(); } } public void testInputStreamToByteArray_NegativeSize() throws Exception { FileInputStream fin = new FileInputStream(m_testFile); try { IOUtils.toByteArray(fin, -1); fail("IllegalArgumentException excepted"); } catch (IllegalArgumentException exc) { assertTrue("Exception message does not start with \"Size must be equal or greater than zero\"", exc .getMessage().startsWith("Size must be equal or greater than zero")); } finally { fin.close(); } } public void testInputStreamToByteArray_ZeroSize() throws Exception { FileInputStream fin = new FileInputStream(m_testFile); try { byte[] out = IOUtils.toByteArray(fin, 0); assertNotNull("Out cannot be null", out); assertEquals("Out length must be 0", 0, out.length); } finally { fin.close(); } } public void testInputStreamToByteArray_IllegalSize() throws Exception { FileInputStream fin = new FileInputStream(m_testFile); try { IOUtils.toByteArray(fin, m_testFile.length() + 1); fail("IOException excepted"); } catch (IOException exc) { assertTrue("Exception message does not start with \"Unexpected readed size\"", exc.getMessage().startsWith("Unexpected readed size")); } finally { fin.close(); } } public void testInputStreamToByteArray_LongSize() throws Exception { FileInputStream fin = new FileInputStream(m_testFile); try { IOUtils.toByteArray(fin, (long) Integer.MAX_VALUE + 1); fail("IOException excepted"); } catch (IllegalArgumentException exc) { assertTrue("Exception message does not start with \"Size cannot be greater than Integer max value\"", exc .getMessage().startsWith("Size cannot be greater than Integer max value")); } finally { fin.close(); } } public void testInputStreamToBufferedInputStream() throws Exception { FileInputStream fin = new FileInputStream(m_testFile); try { InputStream in = IOUtils.toBufferedInputStream(fin); byte[] out = IOUtils.toByteArray(in); assertNotNull(out); assertEquals("Not all bytes were read", 0, fin.available()); assertEquals("Wrong output size", FILE_SIZE, out.length); assertEqualContent(out, m_testFile); } finally { fin.close(); } } @SuppressWarnings("deprecation") // testing deprecated method public void testStringToByteArray() throws Exception { FileReader fin = new FileReader(m_testFile); try { // Create our String. Rely on testReaderToString() to make sure this is valid. String str = IOUtils.toString(fin); byte[] out = IOUtils.toByteArray(str); assertEqualContent(str.getBytes(), out); } finally { fin.close(); } } @SuppressWarnings("deprecation") // testing deprecated method public void testByteArrayToWriter() throws Exception { File destination = newFile("copy7.txt"); FileInputStream fin = new FileInputStream(m_testFile); byte[] in; try { // Create our byte[]. Rely on testInputStreamToByteArray() to make sure this is valid. in = IOUtils.toByteArray(fin); } finally { fin.close(); } FileWriter fout = new FileWriter(destination); try { CopyUtils.copy(in, fout); fout.flush(); checkFile(destination, m_testFile); checkWrite(fout); } finally { fout.close(); } deleteFile(destination); } @SuppressWarnings("deprecation") // testing deprecated method public void testByteArrayToString() throws Exception { FileInputStream fin = new FileInputStream(m_testFile); try { byte[] in = IOUtils.toByteArray(fin); // Create our byte[]. Rely on testInputStreamToByteArray() to make sure this is valid. String str = IOUtils.toString(in); assertEqualContent(in, str.getBytes()); } finally { fin.close(); } } public void testToByteArrayFromURI() throws Exception { URI url = m_testFile.toURI(); byte[] actual = IOUtils.toByteArray(url); Assert.assertEquals(FILE_SIZE, actual.length); } public void testToByteArrayFromURL() throws Exception { URL url = m_testFile.toURI().toURL(); byte[] actual = IOUtils.toByteArray(url); Assert.assertEquals(FILE_SIZE, actual.length); } public void testToByteArrayFromURLConnection() throws Exception { URLConnection urlConn = m_testFile.toURI().toURL().openConnection(); byte[] actual; try { actual = IOUtils.toByteArray(urlConn); } finally { IOUtils.close(urlConn); } Assert.assertEquals(FILE_SIZE, actual.length); } /** * Test for {@link IOUtils#toInputStream(CharSequence)} and {@link IOUtils#toInputStream(CharSequence, String)}. * Note, this test utilizes on {@link IOUtils#toByteArray(java.io.InputStream)} and so relies on * {@link #testInputStreamToByteArray()} to ensure this method functions correctly. * * @throws Exception * on error */ public void testCharSequenceToInputStream() throws Exception { CharSequence csq = new StringBuilder("Abc123Xyz!"); InputStream inStream = IOUtils.toInputStream(csq); byte[] bytes = IOUtils.toByteArray(inStream); assertEqualContent(csq.toString().getBytes(), bytes); inStream = IOUtils.toInputStream(csq, (String) null); bytes = IOUtils.toByteArray(inStream); assertEqualContent(csq.toString().getBytes(), bytes); inStream = IOUtils.toInputStream(csq, "UTF-8"); bytes = IOUtils.toByteArray(inStream); assertEqualContent(csq.toString().getBytes("UTF-8"), bytes); } /** * Test for {@link IOUtils#toInputStream(String)} and {@link IOUtils#toInputStream(String, String)}. Note, this test * utilizes on {@link IOUtils#toByteArray(java.io.InputStream)} and so relies on * {@link #testInputStreamToByteArray()} to ensure this method functions correctly. * * @throws Exception * on error */ public void testStringToInputStream() throws Exception { String str = "Abc123Xyz!"; InputStream inStream = IOUtils.toInputStream(str); byte[] bytes = IOUtils.toByteArray(inStream); assertEqualContent(str.getBytes(), bytes); inStream = IOUtils.toInputStream(str, (String) null); bytes = IOUtils.toByteArray(inStream); assertEqualContent(str.getBytes(), bytes); inStream = IOUtils.toInputStream(str, "UTF-8"); bytes = IOUtils.toByteArray(inStream); assertEqualContent(str.getBytes("UTF-8"), bytes); } @SuppressWarnings("deprecation") // testing deprecated method public void testByteArrayToOutputStream() throws Exception { File destination = newFile("copy8.txt"); FileInputStream fin = new FileInputStream(m_testFile); byte[] in; try { // Create our byte[]. Rely on testInputStreamToByteArray() to make sure this is valid. in = IOUtils.toByteArray(fin); } finally { fin.close(); } FileOutputStream fout = new FileOutputStream(destination); try { CopyUtils.copy(in, fout); fout.flush(); checkFile(destination, m_testFile); checkWrite(fout); } finally { fout.close(); } deleteFile(destination); } public void testInputStreamToCharArray() throws Exception { FileInputStream fin = new FileInputStream(m_testFile); try { char[] out = IOUtils.toCharArray(fin); assertNotNull(out); assertEquals("Not all chars were read", 0, fin.available()); assertEquals("Wrong output size", FILE_SIZE, out.length); assertEqualContent(out, m_testFile); } finally { fin.close(); } } public void testInputStreamToCharArrayWithEncoding() throws Exception { FileInputStream fin = new FileInputStream(m_testFile); try { char[] out = IOUtils.toCharArray(fin, "UTF-8"); assertNotNull(out); assertEquals("Not all chars were read", 0, fin.available()); assertEquals("Wrong output size", FILE_SIZE, out.length); assertEqualContent(out, m_testFile); } finally { fin.close(); } } public void testReaderToCharArray() throws Exception { FileReader fr = new FileReader(m_testFile); try { char[] out = IOUtils.toCharArray(fr); assertNotNull(out); assertEquals("Wrong output size", FILE_SIZE, out.length); assertEqualContent(out, m_testFile); } finally { fr.close(); } } // ----------------------------------------------------------------------- public void testReadLines_InputStream() throws Exception { File file = newFile("lines.txt"); InputStream in = null; try { String[] data = new String[] { "hello", "world", "", "this is", "some text" }; createLineBasedFile(file, data); in = new FileInputStream(file); List lines = IOUtils.readLines(in); assertEquals(Arrays.asList(data), lines); assertEquals(-1, in.read()); } finally { IOUtils.closeQuietly(in); deleteFile(file); } } // ----------------------------------------------------------------------- public void testReadLines_InputStream_String() throws Exception { File file = newFile("lines.txt"); InputStream in = null; try { String[] data = new String[] { "hello", "/u1234", "", "this is", "some text" }; createLineBasedFile(file, data); in = new FileInputStream(file); List lines = IOUtils.readLines(in, "UTF-8"); assertEquals(Arrays.asList(data), lines); assertEquals(-1, in.read()); } finally { IOUtils.closeQuietly(in); deleteFile(file); } } // ----------------------------------------------------------------------- public void testReadLines_Reader() throws Exception { File file = newFile("lines.txt"); Reader in = null; try { String[] data = new String[] { "hello", "/u1234", "", "this is", "some text" }; createLineBasedFile(file, data); in = new InputStreamReader(new FileInputStream(file)); List lines = IOUtils.readLines(in); assertEquals(Arrays.asList(data), lines); assertEquals(-1, in.read()); } finally { IOUtils.closeQuietly(in); deleteFile(file); } } public void testSkipStream() throws Exception { final int size = 1027; InputStream input = new ByteArrayInputStream(new byte[size]); try { IOUtils.skipFully(input, -1); fail("Should have failed with IllegalArgumentException"); } catch (IllegalArgumentException expected) { // expected } IOUtils.skipFully(input, 0); IOUtils.skipFully(input, size - 1); try { IOUtils.skipFully(input, 2); fail("Should have failed with IOException"); } catch (IOException expected) { // expected } IOUtils.closeQuietly(input); } public void testSkipReader() throws Exception { final int size = 1027; Reader input = new CharArrayReader(new char[size]); IOUtils.skipFully(input, 0); IOUtils.skipFully(input, size - 3); try { IOUtils.skipFully(input, -1); fail("Should have failed with IllegalArgumentException"); } catch (IllegalArgumentException expected) { // expected } try { IOUtils.skipFully(input, 5); fail("Should have failed with IOException"); } catch (IOException expected) { // expected } IOUtils.closeQuietly(input); } public void testSkipFileReader() throws Exception { FileReader in = new FileReader(m_testFile); try { assertEquals(FILE_SIZE - 10, IOUtils.skip(in, FILE_SIZE - 10)); assertEquals(10, IOUtils.skip(in, 20)); assertEquals(0, IOUtils.skip(in, 10)); } finally { in.close(); } } public void testSkipFileInput() throws Exception { InputStream in = new FileInputStream(m_testFile); try { assertEquals(FILE_SIZE - 10, IOUtils.skip(in, FILE_SIZE - 10)); assertEquals(10, IOUtils.skip(in, 20)); assertEquals(0, IOUtils.skip(in, 10)); } finally { in.close(); } } private void testURIToString(String encoding) throws Exception { URI url = m_testFile.toURI(); String out = IOUtils.toString(url, encoding); assertNotNull(out); assertEquals("Wrong output size", FILE_SIZE, out.length()); } public void testURIToStringNoEncoding() throws Exception { URI url = m_testFile.toURI(); String out = IOUtils.toString(url); assertNotNull(out); assertEquals("Wrong output size", FILE_SIZE, out.length()); } public void testURIToStringNullEncoding() throws Exception { testURIToString(null); } public void testURIToStringUsAciiEncoding() throws Exception { testURIToString("US-ASCII"); } private void testURLToString(String encoding) throws Exception { URL url = m_testFile.toURI().toURL(); String out = IOUtils.toString(url, encoding); assertNotNull(out); assertEquals("Wrong output size", FILE_SIZE, out.length()); } public void testURLToStringNoEncoding() throws Exception { URL url = m_testFile.toURI().toURL(); String out = IOUtils.toString(url); assertNotNull(out); assertEquals("Wrong output size", FILE_SIZE, out.length()); } public void testURLToStringNullEncoding() throws Exception { testURLToString(null); } public void testURLToStringUsAciiEncoding() throws Exception { testURLToString("US-ASCII"); } public void testContentEqualsIgnoreEOL() throws Exception { Reader r1; Reader r2; r1 = new CharArrayReader("".toCharArray()); r2 = new CharArrayReader("".toCharArray()); assertTrue(IOUtils.contentEqualsIgnoreEOL(r1, r2)); r1 = new CharArrayReader("1".toCharArray()); r2 = new CharArrayReader("1".toCharArray()); assertTrue(IOUtils.contentEqualsIgnoreEOL(r1, r2)); r1 = new CharArrayReader("1".toCharArray()); r2 = new CharArrayReader("2".toCharArray()); assertFalse(IOUtils.contentEqualsIgnoreEOL(r1, r2)); r1 = new CharArrayReader("123\rabc".toCharArray()); r2 = new CharArrayReader("123\nabc".toCharArray()); assertTrue(IOUtils.contentEqualsIgnoreEOL(r1, r2)); r1 = new CharArrayReader("321".toCharArray()); r2 = new CharArrayReader("321\r\n".toCharArray()); assertTrue(IOUtils.contentEqualsIgnoreEOL(r1, r2)); } public void testContentEqualsReaderReader() throws Exception { assertTrue(IOUtils.contentEquals(new StringReader(""), new StringReader(""))); assertTrue(IOUtils.contentEquals(new BufferedReader(new StringReader("")), new BufferedReader(new StringReader("")))); assertTrue(IOUtils.contentEquals(new StringReader("ABC"), new StringReader("ABC"))); assertFalse(IOUtils.contentEquals(new StringReader("ABCD"), new StringReader("ABC"))); assertFalse(IOUtils.contentEquals(new StringReader("ABC"), new StringReader("ABCD"))); } public void testReadStream() throws Exception { final int size = 1027; byte[] buffer = new byte[size]; InputStream input = new ByteArrayInputStream(new byte[size]); try { IOUtils.readFully(input, buffer, 0, -1); fail("Should have failed with IllegalArgumentException"); } catch (IllegalArgumentException expected) { // expected } IOUtils.readFully(input, buffer, 0, 0); IOUtils.readFully(input, buffer, 0, size - 1); try { IOUtils.readFully(input, buffer, 0, 2); fail("Should have failed with EOFxception"); } catch (EOFException expected) { // expected } IOUtils.closeQuietly(input); } public void testReadReader() throws Exception { final int size = 1027; char[] buffer = new char[size]; Reader input = new CharArrayReader(new char[size]); IOUtils.readFully(input, buffer, 0, 0); IOUtils.readFully(input, buffer, 0, size - 3); try { IOUtils.readFully(input, buffer, 0, -1); fail("Should have failed with IllegalArgumentException"); } catch (IllegalArgumentException expected) { // expected } try { IOUtils.readFully(input, buffer, 0, 5); fail("Should have failed with EOFException"); } catch (EOFException expected) { // expected } IOUtils.closeQuietly(input); } public void testReadReaderWithOffset() throws Exception { Reader reader = new StringReader("abcd1234"); char[] buffer = "wx00000000".toCharArray(); IOUtils.readFully(reader, buffer, 2, 8); assertEquals("wxabcd1234", new String(buffer)); IOUtils.closeQuietly(reader); } public void testReadStreamWithOffset() throws Exception { byte[] bytes = "abcd1234".getBytes("UTF-8"); ByteArrayInputStream stream = new ByteArrayInputStream(bytes); byte[] buffer = "wx00000000".getBytes("UTF-8"); IOUtils.readFully(stream, buffer, 2, 8); assertEquals("wxabcd1234", new String(buffer, 0, buffer.length, "UTF-8")); IOUtils.closeQuietly(stream); } // Tests from IO-305 private byte[] iarr = null; public void testNoSkip() throws IOException { ByteArrayInputStream is = null; ByteArrayOutputStream os = null; try { // Create streams is = new ByteArrayInputStream( iarr); os = new ByteArrayOutputStream(); // Test our copy method assertEquals(100, IOUtils.copyLarge( is, os, 0, 100)); byte[] oarr = os.toByteArray(); // check that output length is correct assertEquals( 100, oarr.length ); // check that output data corresponds to input data assertEquals( 1, oarr[1] ); assertEquals( 79, oarr[79] ); assertEquals( -1, oarr[80] ); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } } public void testSkip() throws IOException { ByteArrayInputStream is = null; ByteArrayOutputStream os = null; try { // Create streams is = new ByteArrayInputStream( iarr); os = new ByteArrayOutputStream(); // Test our copy method assertEquals(100, IOUtils.copyLarge( is, os, 10, 100)); byte[] oarr = os.toByteArray(); // check that output length is correct assertEquals( 100, oarr.length ); // check that output data corresponds to input data assertEquals( 11, oarr[1] ); assertEquals( 79, oarr[69] ); assertEquals( -1, oarr[70] ); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } } public void testSkipInvalid() throws IOException { ByteArrayInputStream is = null; ByteArrayOutputStream os = null; try { // Create streams is = new ByteArrayInputStream( iarr); os = new ByteArrayOutputStream(); // Test our copy method IOUtils.copyLarge( is, os, 1000, 100); fail( "Should have thrown EOFException"); } catch( EOFException eofe){ } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } } public void testFullLength() throws IOException { ByteArrayInputStream is = null; ByteArrayOutputStream os = null; try { // Create streams is = new ByteArrayInputStream( iarr); os = new ByteArrayOutputStream(); // Test our copy method assertEquals(200, IOUtils.copyLarge( is, os, 0, -1)); byte[] oarr = os.toByteArray(); // check that output length is correct assertEquals( 200, oarr.length ); // check that output data corresponds to input data assertEquals( 1, oarr[1] ); assertEquals( 79, oarr[79] ); assertEquals( -1, oarr[80] ); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } } public void testExtraLength() throws IOException { ByteArrayInputStream is = null; ByteArrayOutputStream os = null; try { // Create streams is = new ByteArrayInputStream( iarr); os = new ByteArrayOutputStream(); // Test our copy method // for extra length, it reads till EOF assertEquals(200, IOUtils.copyLarge( is, os, 0, 2000)); byte[] oarr = os.toByteArray(); // check that output length is correct assertEquals( 200, oarr.length ); // check that output data corresponds to input data assertEquals( 1, oarr[1] ); assertEquals( 79, oarr[79] ); assertEquals( -1, oarr[80] ); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } } private char[] carr = null; public void testCharNoSkip() throws IOException { CharArrayReader is = null; CharArrayWriter os = null; try { // Create streams is = new CharArrayReader( carr); os = new CharArrayWriter(); // Test our copy method assertEquals(100, IOUtils.copyLarge( is, os, 0, 100)); char[] oarr = os.toCharArray(); // check that output length is correct assertEquals( 100, oarr.length ); // check that output data corresponds to input data assertEquals( 1, oarr[1] ); assertEquals( 79, oarr[79] ); assertEquals((char) -1, oarr[80] ); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } } public void testCharSkip() throws IOException { CharArrayReader is = null; CharArrayWriter os = null; try { // Create streams is = new CharArrayReader( carr); os = new CharArrayWriter(); // Test our copy method assertEquals(100, IOUtils.copyLarge( is, os, 10, 100)); char[] oarr = os.toCharArray(); // check that output length is correct assertEquals( 100, oarr.length ); // check that output data corresponds to input data assertEquals( 11, oarr[1] ); assertEquals( 79, oarr[69] ); assertEquals((char) -1, oarr[70] ); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } } public void testCharSkipInvalid() throws IOException { CharArrayReader is = null; CharArrayWriter os = null; try { // Create streams is = new CharArrayReader( carr); os = new CharArrayWriter(); // Test our copy method IOUtils.copyLarge( is, os, 1000, 100); fail( "Should have thrown EOFException"); } catch( EOFException eofe){ } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } } public void testCharFullLength() throws IOException { CharArrayReader is = null; CharArrayWriter os = null; try { // Create streams is = new CharArrayReader( carr); os = new CharArrayWriter(); // Test our copy method assertEquals(200, IOUtils.copyLarge( is, os, 0, -1)); char[] oarr = os.toCharArray(); // check that output length is correct assertEquals( 200, oarr.length ); // check that output data corresponds to input data assertEquals( 1, oarr[1] ); assertEquals( 79, oarr[79] ); assertEquals((char) -1, oarr[80] ); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } } public void testCharExtraLength() throws IOException { CharArrayReader is = null; CharArrayWriter os = null; try { // Create streams is = new CharArrayReader( carr); os = new CharArrayWriter(); // Test our copy method // for extra length, it reads till EOF assertEquals(200, IOUtils.copyLarge( is, os, 0, 2000)); char[] oarr = os.toCharArray(); // check that output length is correct assertEquals( 200, oarr.length ); // check that output data corresponds to input data assertEquals( 1, oarr[1] ); assertEquals( 79, oarr[79] ); assertEquals((char) -1, oarr[80] ); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/FileUtilsWaitForTestCase.java0000644000175000017500000000353612125050425031613 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.io.File; import org.apache.commons.io.testtools.FileBasedTestCase; /** * This is used to test FileUtils.waitFor() method for correctness. * * @version $Id: FileUtilsWaitForTestCase.java 1302056 2012-03-18 03:03:38Z ggregory $ * @see FileUtils */ public class FileUtilsWaitForTestCase extends FileBasedTestCase { // This class has been broken out from FileUtilsTestCase // to solve issues as per BZ 38927 public FileUtilsWaitForTestCase(String name) { super(name); } /** @see junit.framework.TestCase#setUp() */ @Override protected void setUp() throws Exception { getTestDirectory().mkdirs(); } /** @see junit.framework.TestCase#tearDown() */ @Override protected void tearDown() throws Exception { FileUtils.deleteDirectory(getTestDirectory()); } //----------------------------------------------------------------------- public void testWaitFor() { FileUtils.waitFor(new File(""), -1); FileUtils.waitFor(new File(""), 2); } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/FileUtilsFileNewerTestCase.java0000644000175000017500000001424512125050425032117 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.io.File; import java.util.Date; import org.apache.commons.io.testtools.FileBasedTestCase; /** * This is used to test FileUtils for correctness. */ public class FileUtilsFileNewerTestCase extends FileBasedTestCase { // Test data private static final int FILE1_SIZE = 1; private static final int FILE2_SIZE = 1024 * 4 + 1; private File m_testFile1; private File m_testFile2; public FileUtilsFileNewerTestCase(String name) { super(name); m_testFile1 = new File(getTestDirectory(), "file1-test.txt"); m_testFile2 = new File(getTestDirectory(), "file2-test.txt"); } /** @see junit.framework.TestCase#setUp() */ @Override protected void setUp() throws Exception { getTestDirectory().mkdirs(); createFile(m_testFile1, FILE1_SIZE); createFile(m_testFile2, FILE2_SIZE); } /** @see junit.framework.TestCase#tearDown() */ @Override protected void tearDown() throws Exception { m_testFile1.delete(); m_testFile2.delete(); } /** * Tests the isFileNewer(File, *) methods which a "normal" file. * * @see FileUtils#isFileNewer(File, long) * @see FileUtils#isFileNewer(File, Date) * @see FileUtils#isFileNewer(File, File) */ public void testIsFileNewer() { if (!m_testFile1.exists()) { throw new IllegalStateException("The m_testFile1 should exist"); } long fileLastModified = m_testFile1.lastModified(); final long TWO_SECOND = 2000; testIsFileNewer("two second earlier is not newer" , m_testFile1, fileLastModified + TWO_SECOND, false); testIsFileNewer("same time is not newer" , m_testFile1, fileLastModified, false); testIsFileNewer("two second later is newer" , m_testFile1, fileLastModified - TWO_SECOND, true); } /** * Tests the isFileNewer(File, *) methods which a not existing file. * * @see FileUtils#isFileNewer(File, long) * @see FileUtils#isFileNewer(File, Date) * @see FileUtils#isFileNewer(File, File) */ public void testIsFileNewerImaginaryFile() { File imaginaryFile = new File(getTestDirectory(), "imaginaryFile"); if (imaginaryFile.exists()) { throw new IllegalStateException("The imaginary File exists"); } testIsFileNewer("imaginary file can be newer" , imaginaryFile, m_testFile2.lastModified(), false); } /** * Tests the isFileNewer(File, *) methods which the specified conditions. *

* Creates : *

    *
  • a Date which represents the time reference
  • *
  • a temporary file with the same last modification date than the time reference
  • *
* Then compares (with the needed isFileNewer method) the last modification date of * the specified file with the specified time reference, the created Date and the temporary * file. *
* The test is successfull if the three comparaisons return the specified wanted result. * * @param description describes the tested situation * @param file the file of which the last modification date is compared * @param time the time reference measured in milliseconds since the epoch * * @see FileUtils#isFileNewer(File, long) * @see FileUtils#isFileNewer(File, Date) * @see FileUtils#isFileNewer(File, File) */ protected void testIsFileNewer(String description, File file, long time, boolean wantedResult) { assertEquals(description + " - time", wantedResult, FileUtils.isFileNewer(file, time)); assertEquals(description + " - date", wantedResult, FileUtils.isFileNewer(file, new Date(time))); File temporaryFile = m_testFile2; temporaryFile.setLastModified(time); assertEquals("The temporary file hasn't the right last modification date", time, temporaryFile.lastModified()); assertEquals(description + " - file", wantedResult, FileUtils.isFileNewer(file, temporaryFile)); } /** * Tests the isFileNewer(File, long) method without specifying a File. *
* The test is successfull if the method throws an IllegalArgumentException. */ public void testIsFileNewerNoFile() { try { FileUtils.isFileNewer(null,0); fail("File not specified"); } catch (IllegalArgumentException e) {} } /** * Tests the isFileNewer(File, Date) method without specifying a Date. *
* The test is successfull if the method throws an IllegalArgumentException. */ public void testIsFileNewerNoDate() { try { FileUtils.isFileNewer(m_testFile1, (Date) null); fail("Date not specified"); } catch (IllegalArgumentException e) {} } /** * Tests the isFileNewer(File, File) method without specifying a reference File. *
* The test is successfull if the method throws an IllegalArgumentException. */ public void testIsFileNewerNoFileReference() { try { FileUtils.isFileNewer(m_testFile1, (File) null); fail("Reference file not specified"); } catch (IllegalArgumentException e) {} } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/IOUtilsCopyTestCase.java0000644000175000017500000003414112125050425030576 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.util.Arrays; import org.apache.commons.io.input.NullInputStream; import org.apache.commons.io.input.NullReader; import org.apache.commons.io.output.ByteArrayOutputStream; import org.apache.commons.io.output.NullOutputStream; import org.apache.commons.io.output.NullWriter; import org.apache.commons.io.testtools.FileBasedTestCase; import org.apache.commons.io.testtools.YellOnCloseInputStream; import org.apache.commons.io.testtools.YellOnFlushAndCloseOutputStream; /** * JUnit tests for IOUtils copy methods. * * @version $Id: IOUtilsCopyTestCase.java 1307397 2012-03-30 13:12:16Z ggregory $ * @see IOUtils */ public class IOUtilsCopyTestCase extends FileBasedTestCase { /* * NOTE this is not particularly beautiful code. A better way to check for * flush and close status would be to implement "trojan horse" wrapper * implementations of the various stream classes, which set a flag when * relevant methods are called. (JT) */ private static final int FILE_SIZE = 1024 * 4 + 1; private byte[] inData = generateTestData(FILE_SIZE); public IOUtilsCopyTestCase(String testName) { super(testName); } // ---------------------------------------------------------------- // Setup // ---------------------------------------------------------------- @Override public void setUp() throws Exception { } @Override public void tearDown() throws Exception { } //----------------------------------------------------------------------- public void testCopy_inputStreamToOutputStream() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStream(in); ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStream(baout, false, true); int count = IOUtils.copy(in, out); assertEquals("Not all bytes were read", 0, in.available()); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); assertEquals(inData.length,count); } public void testCopy_inputStreamToOutputStream_nullIn() throws Exception { OutputStream out = new ByteArrayOutputStream(); try { IOUtils.copy((InputStream) null, out); fail(); } catch (NullPointerException ex) {} } public void testCopy_inputStreamToOutputStream_nullOut() throws Exception { InputStream in = new ByteArrayInputStream(inData); try { IOUtils.copy(in, (OutputStream) null); fail(); } catch (NullPointerException ex) {} } /** * Test Copying file > 2GB - see issue# IO-84 */ public void testCopy_inputStreamToOutputStream_IO84() throws Exception { long size = (long)Integer.MAX_VALUE + (long)1; InputStream in = new NullInputStream(size); OutputStream out = new NullOutputStream(); // Test copy() method assertEquals(-1, IOUtils.copy(in, out)); // reset the input in.close(); // Test copyLarge() method assertEquals("copyLarge()", size, IOUtils.copyLarge(in, out)); } //----------------------------------------------------------------------- public void testCopy_inputStreamToWriter() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStream(in); ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); IOUtils.copy(in, writer); out.off(); writer.flush(); assertEquals("Not all bytes were read", 0, in.available()); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); } public void testCopy_inputStreamToWriter_nullIn() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true); Writer writer = new OutputStreamWriter(out, "US-ASCII"); try { IOUtils.copy((InputStream) null, writer); fail(); } catch (NullPointerException ex) {} } public void testCopy_inputStreamToWriter_nullOut() throws Exception { InputStream in = new ByteArrayInputStream(inData); try { IOUtils.copy(in, (Writer) null); fail(); } catch (NullPointerException ex) {} } //----------------------------------------------------------------------- public void testCopy_inputStreamToWriter_Encoding() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStream(in); ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); IOUtils.copy(in, writer, "UTF8"); out.off(); writer.flush(); assertEquals("Not all bytes were read", 0, in.available()); byte[] bytes = baout.toByteArray(); bytes = new String(bytes, "UTF8").getBytes("US-ASCII"); assertTrue("Content differs", Arrays.equals(inData, bytes)); } public void testCopy_inputStreamToWriter_Encoding_nullIn() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true); Writer writer = new OutputStreamWriter(out, "US-ASCII"); try { IOUtils.copy((InputStream) null, writer, "UTF8"); fail(); } catch (NullPointerException ex) {} } public void testCopy_inputStreamToWriter_Encoding_nullOut() throws Exception { InputStream in = new ByteArrayInputStream(inData); try { IOUtils.copy(in, (Writer) null, "UTF8"); fail(); } catch (NullPointerException ex) {} } public void testCopy_inputStreamToWriter_Encoding_nullEncoding() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStream(in); ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); IOUtils.copy(in, writer, (String) null); out.off(); writer.flush(); assertEquals("Not all bytes were read", 0, in.available()); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); } //----------------------------------------------------------------------- public void testCopy_readerToOutputStream() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStream(in); Reader reader = new InputStreamReader(in, "US-ASCII"); ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStream(baout, false, true); IOUtils.copy(reader, out); //Note: this method *does* flush. It is equivalent to: // OutputStreamWriter _out = new OutputStreamWriter(fout); // IOUtils.copy( fin, _out, 4096 ); // copy( Reader, Writer, int ); // _out.flush(); // out = fout; // Note: rely on the method to flush assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); } public void testCopy_readerToOutputStream_nullIn() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true); try { IOUtils.copy((Reader) null, out); fail(); } catch (NullPointerException ex) {} } public void testCopy_readerToOutputStream_nullOut() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStream(in); Reader reader = new InputStreamReader(in, "US-ASCII"); try { IOUtils.copy(reader, (OutputStream) null); fail(); } catch (NullPointerException ex) {} } //----------------------------------------------------------------------- public void testCopy_readerToOutputStream_Encoding() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStream(in); Reader reader = new InputStreamReader(in, "US-ASCII"); ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStream(baout, false, true); IOUtils.copy(reader, out, "UTF16"); // note: this method *does* flush. // note: we don't flush here; this IOUtils method does it for us byte[] bytes = baout.toByteArray(); bytes = new String(bytes, "UTF16").getBytes("US-ASCII"); assertTrue("Content differs", Arrays.equals(inData, bytes)); } public void testCopy_readerToOutputStream_Encoding_nullIn() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true); try { IOUtils.copy((Reader) null, out, "UTF16"); fail(); } catch (NullPointerException ex) {} } public void testCopy_readerToOutputStream_Encoding_nullOut() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStream(in); Reader reader = new InputStreamReader(in, "US-ASCII"); try { IOUtils.copy(reader, (OutputStream) null, "UTF16"); fail(); } catch (NullPointerException ex) {} } public void testCopy_readerToOutputStream_Encoding_nullEncoding() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStream(in); Reader reader = new InputStreamReader(in, "US-ASCII"); ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStream(baout, false, true); IOUtils.copy(reader, out, (String) null); // note: this method *does* flush. // note: we don't flush here; this IOUtils method does it for us assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); } //----------------------------------------------------------------------- public void testCopy_readerToWriter() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStream(in); Reader reader = new InputStreamReader(in, "US-ASCII"); ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); int count = IOUtils.copy(reader, writer); out.off(); writer.flush(); assertEquals("The number of characters returned by copy is wrong", inData.length, count); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); } public void testCopy_readerToWriter_nullIn() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true); Writer writer = new OutputStreamWriter(out, "US-ASCII"); try { IOUtils.copy((Reader) null, writer); fail(); } catch (NullPointerException ex) {} } public void testCopy_readerToWriter_nullOut() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStream(in); Reader reader = new InputStreamReader(in, "US-ASCII"); try { IOUtils.copy(reader, (Writer) null); fail(); } catch (NullPointerException ex) {} } /** * Test Copying file > 2GB - see issue# IO-84 */ public void testCopy_readerToWriter_IO84() throws Exception { long size = (long)Integer.MAX_VALUE + (long)1; Reader reader = new NullReader(size); Writer writer = new NullWriter(); // Test copy() method assertEquals(-1, IOUtils.copy(reader, writer)); // reset the input reader.close(); // Test copyLarge() method assertEquals("copyLarge()", size, IOUtils.copyLarge(reader, writer)); } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/LineIteratorTestCase.java0000644000175000017500000003500612125050425031015 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.nio.charset.UnsupportedCharsetException; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; import org.apache.commons.io.testtools.FileBasedTestCase; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * This is used to test LineIterator for correctness. * * @version $Id: LineIteratorTestCase.java 1308109 2012-04-01 13:31:20Z ggregory $ */ public class LineIteratorTestCase extends FileBasedTestCase { public LineIteratorTestCase(String name) { super(name); } private void assertLines(List lines, LineIterator iterator) { try { for (int i = 0; i < lines.size(); i++) { String line = iterator.nextLine(); assertEquals("nextLine() line " + i, lines.get(i), line); } assertFalse("No more expected", iterator.hasNext()); } finally { LineIterator.closeQuietly(iterator); } } /** * Creates a test file with a specified number of lines. */ private List createLinesFile(File file, int lineCount) throws Exception { List lines = createStringLines(lineCount); FileUtils.writeLines(file, lines); return lines; } /** * Creates a test file with a specified number of lines. */ private List createLinesFile(File file, String encoding, int lineCount) throws Exception { List lines = createStringLines(lineCount); FileUtils.writeLines(file, encoding, lines); return lines; } /** * Creates String data lines. * * @param lineCount * @return a new lines list. */ private List createStringLines(int lineCount) { List lines = new ArrayList(); for (int i = 0; i < lineCount; i++) { lines.add("LINE " + i); } return lines; } /** @see junit.framework.TestCase#setUp() */ @Override @Before protected void setUp() throws Exception { File dir = getTestDirectory(); if (dir.exists()) { FileUtils.deleteDirectory(dir); } dir.mkdirs(); } /** @see junit.framework.TestCase#tearDown() */ @Override @After protected void tearDown() throws Exception { FileUtils.deleteDirectory(getTestDirectory()); } // ----------------------------------------------------------------------- /** * Test constructor. */ @Test public void testConstructor() throws Exception { try { new LineIterator((Reader) null); fail(); } catch (IllegalArgumentException ex) { // expected } } /** * Test a file with no lines. */ @Test public void testZeroLines() throws Exception { doTestFileWithSpecifiedLines(0); } /** * Test a file with 1 line. */ @Test public void testOneLines() throws Exception { doTestFileWithSpecifiedLines(1); } /** * Test a file with 2 lines. */ @Test public void testTwoLines() throws Exception { doTestFileWithSpecifiedLines(2); } /** * Test a file with 3 lines. */ @Test public void testThreeLines() throws Exception { doTestFileWithSpecifiedLines(3); } /** * Test a missing File. */ @Test public void testMissingFile() throws Exception { File testFile = new File(getTestDirectory(), "dummy-missing-file.txt"); LineIterator iterator = null; try { iterator = FileUtils.lineIterator(testFile, "UTF-8"); fail("Expected FileNotFoundException"); } catch (FileNotFoundException expected) { // ignore, expected result } finally { LineIterator.closeQuietly(iterator); } } /** * Test a file with a Valid encoding. */ @Test public void testValidEncoding() throws Exception { String encoding = "UTF-8"; File testFile = new File(getTestDirectory(), "LineIterator-validEncoding.txt"); createLinesFile(testFile, encoding, 3); LineIterator iterator = FileUtils.lineIterator(testFile, encoding); try { int count = 0; while (iterator.hasNext()) { assertNotNull(iterator.next()); count++; } assertEquals(3, count); } finally { LineIterator.closeQuietly(iterator); } } /** * Test a file with an Invalid encoding. */ @Test public void testInvalidEncoding() throws Exception { String encoding = "XXXXXXXX"; File testFile = new File(getTestDirectory(), "LineIterator-invalidEncoding.txt"); createLinesFile(testFile, "UTF-8", 3); LineIterator iterator = null; try { iterator = FileUtils.lineIterator(testFile, encoding); fail("Expected UnsupportedCharsetException"); } catch (UnsupportedCharsetException expected) { // ignore, expected result } finally { LineIterator.closeQuietly(iterator); } } /** * Test the iterator using only the nextLine() method. */ @Test public void testNextLineOnlyDefaultEncoding() throws Exception { File testFile = new File(getTestDirectory(), "LineIterator-nextOnly.txt"); List lines = createLinesFile(testFile, 3); LineIterator iterator = FileUtils.lineIterator(testFile); assertLines(lines, iterator); } /** * Test the iterator using only the nextLine() method. */ @Test public void testNextLineOnlyNullEncoding() throws Exception { String encoding = null; File testFile = new File(getTestDirectory(), "LineIterator-nextOnly.txt"); List lines = createLinesFile(testFile, encoding, 3); LineIterator iterator = FileUtils.lineIterator(testFile, encoding); assertLines(lines, iterator); } /** * Test the iterator using only the nextLine() method. */ @Test public void testNextLineOnlyUtf8Encoding() throws Exception { String encoding = "UTF-8"; File testFile = new File(getTestDirectory(), "LineIterator-nextOnly.txt"); List lines = createLinesFile(testFile, encoding, 3); LineIterator iterator = FileUtils.lineIterator(testFile, encoding); assertLines(lines, iterator); } /** * Test the iterator using only the next() method. */ @Test public void testNextOnly() throws Exception { String encoding = null; File testFile = new File(getTestDirectory(), "LineIterator-nextOnly.txt"); List lines = createLinesFile(testFile, encoding, 3); LineIterator iterator = FileUtils.lineIterator(testFile, encoding); try { for (int i = 0; i < lines.size(); i++) { String line = iterator.next(); assertEquals("next() line " + i, lines.get(i), line); } assertEquals("No more expected", false, iterator.hasNext()); } finally { LineIterator.closeQuietly(iterator); } } /** * Tests hasNext when it throws an exception. */ @Test public void testNextWithException() throws Exception { Reader reader = new BufferedReader(new StringReader("")) { @Override public String readLine() throws IOException { throw new IOException("hasNext"); } }; try { new LineIterator(reader).hasNext(); fail("Expected IllegalStateException"); } catch (IllegalStateException e) { // expected } } /** * Test closing the iterator before all the file has been processed. */ @Test public void testCloseEarly() throws Exception { String encoding = "UTF-8"; File testFile = new File(getTestDirectory(), "LineIterator-closeEarly.txt"); createLinesFile(testFile, encoding, 3); LineIterator iterator = FileUtils.lineIterator(testFile, encoding); try { // get assertNotNull("Line expected", iterator.next()); assertTrue("More expected", iterator.hasNext()); // close iterator.close(); assertFalse("No more expected", iterator.hasNext()); try { iterator.next(); fail(); } catch (NoSuchElementException ex) { // expected } try { iterator.nextLine(); fail(); } catch (NoSuchElementException ex) { // expected } // try closing again iterator.close(); try { iterator.next(); fail(); } catch (NoSuchElementException ex) { // expected } try { iterator.nextLine(); fail(); } catch (NoSuchElementException ex) { // expected } } finally { LineIterator.closeQuietly(iterator); } } /** * Utility method to create and test a file with a specified number of lines. */ private void doTestFileWithSpecifiedLines(int lineCount) throws Exception { String encoding = "UTF-8"; String fileName = "LineIterator-" + lineCount + "-test.txt"; File testFile = new File(getTestDirectory(), fileName); List lines = createLinesFile(testFile, encoding, lineCount); LineIterator iterator = FileUtils.lineIterator(testFile, encoding); try { try { iterator.remove(); fail("Remove is unsupported"); } catch (UnsupportedOperationException ex) { // expected } int idx = 0; while (iterator.hasNext()) { String line = iterator.next(); assertEquals("Comparing line " + idx, lines.get(idx), line); assertTrue("Exceeded expected idx=" + idx + " size=" + lines.size(), idx < lines.size()); idx++; } assertEquals("Line Count doesn't match", idx, lines.size()); // try calling next() after file processed try { iterator.next(); fail("Expected NoSuchElementException"); } catch (NoSuchElementException expected) { // ignore, expected result } try { iterator.nextLine(); fail("Expected NoSuchElementException"); } catch (NoSuchElementException expected) { // ignore, expected result } } finally { LineIterator.closeQuietly(iterator); } } // ----------------------------------------------------------------------- @Test public void testFilteringFileReader() throws Exception { String encoding = "UTF-8"; String fileName = "LineIterator-Filter-test.txt"; File testFile = new File(getTestDirectory(), fileName); List lines = createLinesFile(testFile, encoding, 9); Reader reader = new FileReader(testFile); this.testFiltering(lines, reader); } @Test public void testFilteringBufferedReader() throws Exception { String encoding = "UTF-8"; String fileName = "LineIterator-Filter-test.txt"; File testFile = new File(getTestDirectory(), fileName); List lines = createLinesFile(testFile, encoding, 9); Reader reader = new BufferedReader(new FileReader(testFile)); this.testFiltering(lines, reader); } private void testFiltering(List lines, Reader reader) { LineIterator iterator = new LineIterator(reader) { @Override protected boolean isValidLine(String line) { char c = line.charAt(line.length() - 1); return (c - 48) % 3 != 1; } }; try { try { iterator.remove(); fail("Remove is unsupported"); } catch (UnsupportedOperationException ex) { // expected } int idx = 0; int actualLines = 0; while (iterator.hasNext()) { String line = iterator.next(); actualLines++; assertEquals("Comparing line " + idx, lines.get(idx), line); assertTrue("Exceeded expected idx=" + idx + " size=" + lines.size(), idx < lines.size()); idx++; if (idx % 3 == 1) { idx++; } } assertEquals("Line Count doesn't match", 9, lines.size()); assertEquals("Line Count doesn't match", 9, idx); assertEquals("Line Count doesn't match", 6, actualLines); // try calling next() after file processed try { iterator.next(); fail("Expected NoSuchElementException"); } catch (NoSuchElementException expected) { // ignore, expected result } try { iterator.nextLine(); fail("Expected NoSuchElementException"); } catch (NoSuchElementException expected) { // ignore, expected result } } finally { LineIterator.closeQuietly(iterator); } } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/comparator/0000755000175000017500000000000012125050425026260 5ustar ebourgebourg././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/comparator/SizeFileComparatorTest.javalibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/comparator/SizeFileComparatorTest.ja0000644000175000017500000000553012125050425033201 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.comparator; import java.io.File; /** * Test case for {@link SizeFileComparator}. */ public class SizeFileComparatorTest extends ComparatorAbstractTestCase { private File smallerDir; private File largerDir; private File smallerFile; private File largerFile; /** * Construct a new test case with the specified name. * * @param name Name of the test */ public SizeFileComparatorTest(String name) { super(name); } /** @see junit.framework.TestCase#setUp() */ @Override protected void setUp() throws Exception { super.setUp(); comparator = (AbstractFileComparator)SizeFileComparator.SIZE_COMPARATOR; reverse = SizeFileComparator.SIZE_REVERSE; File dir = getTestDirectory(); smallerDir = new File(dir, "smallerdir"); largerDir = new File(dir, "largerdir"); smallerFile = new File(smallerDir, "smaller.txt"); File equalFile = new File(dir, "equal.txt"); largerFile = new File(largerDir, "larger.txt"); smallerDir.mkdir(); largerDir.mkdir(); createFile(smallerFile, 32); createFile(equalFile, 48); createFile(largerFile, 64); equalFile1 = equalFile; equalFile2 = equalFile; lessFile = smallerFile; moreFile = largerFile; } /** * Test a file which doesn't exist. */ public void testNonexistantFile() { File nonexistantFile = new File(new File("."), "nonexistant.txt"); assertFalse(nonexistantFile.exists()); assertTrue("less", comparator.compare(nonexistantFile, moreFile) < 0); } /** * Test a file which doesn't exist. */ public void testCompareDirectorySizes() { assertEquals("sumDirectoryContents=false", 0, comparator.compare(smallerDir, largerDir)); assertEquals("less", -1, SizeFileComparator.SIZE_SUMDIR_COMPARATOR.compare(smallerDir, largerDir)); assertEquals("less", 1, SizeFileComparator.SIZE_SUMDIR_REVERSE.compare(smallerDir, largerDir)); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/comparator/NameFileComparatorTest.javalibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/comparator/NameFileComparatorTest.ja0000644000175000017500000000515312125050425033150 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.comparator; import java.io.File; import java.util.Comparator; /** * Test case for {@link NameFileComparator}. */ public class NameFileComparatorTest extends ComparatorAbstractTestCase { /** * Construct a new test case with the specified name. * * @param name Name of the test */ public NameFileComparatorTest(String name) { super(name); } /** @see junit.framework.TestCase#setUp() */ @Override protected void setUp() throws Exception { super.setUp(); comparator = (AbstractFileComparator)NameFileComparator.NAME_INSENSITIVE_COMPARATOR; reverse = NameFileComparator.NAME_REVERSE; equalFile1 = new File("a/foo.txt"); equalFile2 = new File("b/foo.txt"); lessFile = new File("c/ABC.txt"); moreFile = new File("d/XYZ.txt"); } /** Test case sensitivity */ public void testCaseSensitivity() { File file3 = new File("a/FOO.txt"); Comparator sensitive = new NameFileComparator(null); /* test null as well */ assertTrue("sensitive file1 & file2 = 0", sensitive.compare(equalFile1, equalFile2) == 0); assertTrue("sensitive file1 & file3 > 0", sensitive.compare(equalFile1, file3) > 0); assertTrue("sensitive file1 & less > 0", sensitive.compare(equalFile1, lessFile) > 0); Comparator insensitive = NameFileComparator.NAME_INSENSITIVE_COMPARATOR; assertTrue("insensitive file1 & file2 = 0", insensitive.compare(equalFile1, equalFile2) == 0); assertTrue("insensitive file1 & file3 = 0", insensitive.compare(equalFile1, file3) == 0); assertTrue("insensitive file1 & file4 > 0", insensitive.compare(equalFile1, lessFile) > 0); assertTrue("insensitive file3 & less > 0", insensitive.compare(file3, lessFile) > 0); } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/comparator/CompositeFileComparatorTest.javalibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/comparator/CompositeFileComparatorTe0000644000175000017500000000653612125050425033300 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.comparator; import java.io.File; import java.util.ArrayList; import java.util.Comparator; import java.util.List; /** * Test case for {@link CompositeFileComparator}. */ public class CompositeFileComparatorTest extends ComparatorAbstractTestCase { /** * Construct a new test case with the specified name. * * @param name Name of the test */ public CompositeFileComparatorTest(String name) { super(name); } /** @see junit.framework.TestCase#setUp() */ @Override protected void setUp() throws Exception { super.setUp(); comparator = new CompositeFileComparator(SizeFileComparator.SIZE_COMPARATOR, ExtensionFileComparator.EXTENSION_COMPARATOR); reverse = new ReverseComparator(comparator); File dir = getTestDirectory(); lessFile = new File(dir, "xyz.txt"); equalFile1 = new File(dir, "foo.txt"); equalFile2 = new File(dir, "bar.txt"); moreFile = new File(dir, "foo.xyz"); createFile(lessFile, 32); createFile(equalFile1, 48); createFile(equalFile2, 48); createFile(moreFile, 48); } /** * Test Constructor with null Iterable */ public void testConstructorIterable() { List> list = new ArrayList>(); list.add(SizeFileComparator.SIZE_COMPARATOR); list.add(ExtensionFileComparator.EXTENSION_COMPARATOR); Comparator c = new CompositeFileComparator(list); assertEquals("equal", 0, c.compare(equalFile1, equalFile2)); assertTrue("less", c.compare(lessFile, moreFile) < 0); assertTrue("more", c.compare(moreFile, lessFile) > 0); } /** * Test Constructor with null Iterable */ public void testConstructorIterableNull() { Comparator c = new CompositeFileComparator((Iterable>)null); assertEquals("less,more", 0, c.compare(lessFile, moreFile)); assertEquals("more,less", 0, c.compare(moreFile, lessFile)); assertEquals("toString", "CompositeFileComparator{}", c.toString()); } /** * Test Constructor with null array */ public void testConstructorArrayNull() { Comparator c = new CompositeFileComparator((Comparator[])null); assertEquals("less,more", 0, c.compare(lessFile, moreFile)); assertEquals("more,less", 0, c.compare(moreFile, lessFile)); assertEquals("toString", "CompositeFileComparator{}", c.toString()); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/comparator/PathFileComparatorTest.javalibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/comparator/PathFileComparatorTest.ja0000644000175000017500000000515612125050425033167 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.comparator; import java.io.File; import java.util.Comparator; /** * Test case for {@link PathFileComparator}. */ public class PathFileComparatorTest extends ComparatorAbstractTestCase { /** * Construct a new test case with the specified name. * * @param name Name of the test */ public PathFileComparatorTest(String name) { super(name); } /** @see junit.framework.TestCase#setUp() */ @Override protected void setUp() throws Exception { super.setUp(); comparator = (AbstractFileComparator)PathFileComparator.PATH_COMPARATOR; reverse = PathFileComparator.PATH_REVERSE; equalFile1 = new File("foo/file.txt"); equalFile2 = new File("foo/file.txt"); lessFile = new File("abc/file.txt"); moreFile = new File("xyz/file.txt"); } /** Test case sensitivity */ public void testCaseSensitivity() { File file3 = new File("FOO/file.txt"); Comparator sensitive = new PathFileComparator(null); /* test null as well */ assertTrue("sensitive file1 & file2 = 0", sensitive.compare(equalFile1, equalFile2) == 0); assertTrue("sensitive file1 & file3 > 0", sensitive.compare(equalFile1, file3) > 0); assertTrue("sensitive file1 & less > 0", sensitive.compare(equalFile1, lessFile) > 0); Comparator insensitive = PathFileComparator.PATH_INSENSITIVE_COMPARATOR; assertTrue("insensitive file1 & file2 = 0", insensitive.compare(equalFile1, equalFile2) == 0); assertTrue("insensitive file1 & file3 = 0", insensitive.compare(equalFile1, file3) == 0); assertTrue("insensitive file1 & file4 > 0", insensitive.compare(equalFile1, lessFile) > 0); assertTrue("insensitive file3 & less > 0", insensitive.compare(file3, lessFile) > 0); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/comparator/DefaultFileComparatorTest.javalibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/comparator/DefaultFileComparatorTest0000644000175000017500000000314412125050425033261 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.comparator; import java.io.File; /** * Test case for {@link DefaultFileComparator}. */ public class DefaultFileComparatorTest extends ComparatorAbstractTestCase { /** * Construct a new test case with the specified name. * * @param name Name of the test */ public DefaultFileComparatorTest(String name) { super(name); } /** @see junit.framework.TestCase#setUp() */ @Override protected void setUp() throws Exception { super.setUp(); comparator = (AbstractFileComparator)DefaultFileComparator.DEFAULT_COMPARATOR; reverse = DefaultFileComparator.DEFAULT_REVERSE; equalFile1 = new File("foo"); equalFile2 = new File("foo"); lessFile = new File("abc"); moreFile = new File("xyz"); } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/comparator/ExtensionFileComparatorTest.javalibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/comparator/ExtensionFileComparatorTe0000644000175000017500000000520712125050425033304 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.comparator; import java.io.File; import java.util.Comparator; /** * Test case for {@link ExtensionFileComparator}. */ public class ExtensionFileComparatorTest extends ComparatorAbstractTestCase { /** * Construct a new test case with the specified name. * * @param name Name of the test */ public ExtensionFileComparatorTest(String name) { super(name); } /** @see junit.framework.TestCase#setUp() */ @Override protected void setUp() throws Exception { super.setUp(); comparator = (AbstractFileComparator)ExtensionFileComparator.EXTENSION_COMPARATOR; reverse = ExtensionFileComparator.EXTENSION_REVERSE; equalFile1 = new File("abc.foo"); equalFile2 = new File("def.foo"); lessFile = new File("abc.abc"); moreFile = new File("abc.xyz"); } /** Test case sensitivity */ public void testCaseSensitivity() { File file3 = new File("abc.FOO"); Comparator sensitive = new ExtensionFileComparator(null); /* test null as well */ assertTrue("sensitive file1 & file2 = 0", sensitive.compare(equalFile1, equalFile2) == 0); assertTrue("sensitive file1 & file3 > 0", sensitive.compare(equalFile1, file3) > 0); assertTrue("sensitive file1 & less > 0", sensitive.compare(equalFile1, lessFile) > 0); Comparator insensitive = ExtensionFileComparator.EXTENSION_INSENSITIVE_COMPARATOR; assertTrue("insensitive file1 & file2 = 0", insensitive.compare(equalFile1, equalFile2) == 0); assertTrue("insensitive file1 & file3 = 0", insensitive.compare(equalFile1, file3) == 0); assertTrue("insensitive file1 & file4 > 0", insensitive.compare(equalFile1, lessFile) > 0); assertTrue("insensitive file3 & less > 0", insensitive.compare(file3, lessFile) > 0); } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/comparator/DirectoryFileComparatorTest.javalibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/comparator/DirectoryFileComparatorTe0000644000175000017500000000375112125050425033276 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.comparator; import java.io.File; /** * Test case for {@link DirectoryFileComparator}. */ public class DirectoryFileComparatorTest extends ComparatorAbstractTestCase { /** * Construct a new test case with the specified name. * * @param name Name of the test */ public DirectoryFileComparatorTest(String name) { super(name); } /** @see junit.framework.TestCase#setUp() */ @Override protected void setUp() throws Exception { super.setUp(); comparator = (AbstractFileComparator)DirectoryFileComparator.DIRECTORY_COMPARATOR; reverse = DirectoryFileComparator.DIRECTORY_REVERSE; File currentDir = new File("."); equalFile1 = new File(currentDir, "src"); equalFile2 = new File(currentDir, "src/site/xdoc"); lessFile = new File(currentDir, "src"); moreFile = new File(currentDir, "pom.xml"); } /** * Test the comparator array sort. */ @Override public void testSortArray() { // skip sort test } /** * Test the comparator array sort. */ @Override public void testSortList() { // skip sort test } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/comparator/LastModifiedFileComparatorTest.javalibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/comparator/LastModifiedFileComparato0000644000175000017500000000475212125050425033225 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.comparator; import java.io.File; /** * Test case for {@link LastModifiedFileComparator}. */ public class LastModifiedFileComparatorTest extends ComparatorAbstractTestCase { /** * Construct a new test case with the specified name. * * @param name Name of the test */ public LastModifiedFileComparatorTest(String name) { super(name); } /** @see junit.framework.TestCase#setUp() */ @Override protected void setUp() throws Exception { super.setUp(); comparator = (AbstractFileComparator)LastModifiedFileComparator.LASTMODIFIED_COMPARATOR; reverse = LastModifiedFileComparator.LASTMODIFIED_REVERSE; File dir = getTestDirectory(); File olderFile = new File(dir, "older.txt"); createFile(olderFile, 0); File equalFile = new File(dir, "equal.txt"); createFile(equalFile, 0); do { try { Thread.sleep(300); } catch(InterruptedException ie) { // ignore } equalFile.setLastModified(System.currentTimeMillis()); } while( olderFile.lastModified() == equalFile.lastModified() ); File newerFile = new File(dir, "newer.txt"); createFile(newerFile, 0); do { try { Thread.sleep(300); } catch(InterruptedException ie) { // ignore } newerFile.setLastModified(System.currentTimeMillis()); } while( equalFile.lastModified() == newerFile.lastModified() ); equalFile1 = equalFile; equalFile2 = equalFile; lessFile = olderFile; moreFile = newerFile; } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/comparator/ComparatorAbstractTestCase.javalibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/comparator/ComparatorAbstractTestCas0000644000175000017500000001057012125050425033270 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.comparator; import java.io.File; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import org.apache.commons.io.FileUtils; import org.apache.commons.io.testtools.FileBasedTestCase; /** * Base Test case for Comparator implementations. */ public abstract class ComparatorAbstractTestCase extends FileBasedTestCase { /** comparator instance */ protected AbstractFileComparator comparator; /** reverse comparator instance */ protected Comparator reverse; /** File which compares equal to "equalFile2" */ protected File equalFile1; /** File which compares equal to "equalFile1" */ protected File equalFile2; /** File which is less than the "moreFile" */ protected File lessFile; /** File which is more than the "lessFile" */ protected File moreFile; /** * Construct a new test case with the specified name * @param name Name of the test */ public ComparatorAbstractTestCase(String name) { super(name); } /** @see junit.framework.TestCase#setUp() */ @Override protected void setUp() throws Exception { comparator = (AbstractFileComparator)DefaultFileComparator.DEFAULT_COMPARATOR; reverse = DefaultFileComparator.DEFAULT_REVERSE; } /** @see junit.framework.TestCase#tearDown() */ @Override protected void tearDown() throws Exception { comparator = null; reverse = null; equalFile1 = null; equalFile2 = null; lessFile = null; moreFile = null; FileUtils.deleteDirectory(getTestDirectory()); } /** * Test the comparator. */ public void testComparator() { assertEquals("equal", 0, comparator.compare(equalFile1, equalFile2)); assertTrue("less", comparator.compare(lessFile, moreFile) < 0); assertTrue("more", comparator.compare(moreFile, lessFile) > 0); } /** * Test the comparator reversed. */ public void testReverseComparator() { assertEquals("equal", 0, reverse.compare(equalFile1, equalFile2)); assertTrue("less", reverse.compare(moreFile, lessFile) < 0); assertTrue("more", reverse.compare(lessFile, moreFile) > 0); } /** * Test comparator array sort is null safe. */ public void testSortArrayNull() { assertNull(comparator.sort((File[])null)); } /** * Test the comparator array sort. */ public void testSortArray() { File[] files = new File[3]; files[0] = equalFile1; files[1] = moreFile; files[2] = lessFile; comparator.sort(files); assertSame("equal", lessFile, files[0]); assertSame("less", equalFile1, files[1]); assertSame("more", moreFile, files[2]); } /** * Test the comparator array sort. */ public void testSortList() { List files = new ArrayList(); files.add(equalFile1); files.add(moreFile); files.add(lessFile); comparator.sort(files); assertSame("equal", lessFile, files.get(0)); assertSame("less", equalFile1, files.get(1)); assertSame("more", moreFile, files.get(2)); } /** * Test comparator list sort is null safe. */ public void testSortListNull() { assertNull(comparator.sort((List)null)); } /** * Test comparator toString. */ public void testToString() { assertNotNull("comparator", comparator.toString()); assertTrue("reverse", reverse.toString().startsWith("ReverseComparator[")); } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/IOCaseTestCase.java0000644000175000017500000004015412125050425027517 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import org.apache.commons.io.testtools.FileBasedTestCase; /** * This is used to test IOCase for correctness. * * @version $Id: IOCaseTestCase.java 1302748 2012-03-20 01:35:32Z ggregory $ */ public class IOCaseTestCase extends FileBasedTestCase { private static final boolean WINDOWS = File.separatorChar == '\\'; public IOCaseTestCase(String name) { super(name); } @Override protected void setUp() throws Exception { } @Override protected void tearDown() throws Exception { } //----------------------------------------------------------------------- public void test_forName() throws Exception { assertEquals(IOCase.SENSITIVE, IOCase.forName("Sensitive")); assertEquals(IOCase.INSENSITIVE, IOCase.forName("Insensitive")); assertEquals(IOCase.SYSTEM, IOCase.forName("System")); try { IOCase.forName("Blah"); fail(); } catch (IllegalArgumentException ex) {} try { IOCase.forName(null); fail(); } catch (IllegalArgumentException ex) {} } public void test_serialization() throws Exception { assertSame(IOCase.SENSITIVE, serialize(IOCase.SENSITIVE)); assertSame(IOCase.INSENSITIVE, serialize(IOCase.INSENSITIVE)); assertSame(IOCase.SYSTEM, serialize(IOCase.SYSTEM)); } public void test_getName() throws Exception { assertEquals("Sensitive", IOCase.SENSITIVE.getName()); assertEquals("Insensitive", IOCase.INSENSITIVE.getName()); assertEquals("System", IOCase.SYSTEM.getName()); } public void test_toString() throws Exception { assertEquals("Sensitive", IOCase.SENSITIVE.toString()); assertEquals("Insensitive", IOCase.INSENSITIVE.toString()); assertEquals("System", IOCase.SYSTEM.toString()); } public void test_isCaseSensitive() throws Exception { assertTrue(IOCase.SENSITIVE.isCaseSensitive()); assertFalse(IOCase.INSENSITIVE.isCaseSensitive()); assertEquals(!WINDOWS, IOCase.SYSTEM.isCaseSensitive()); } //----------------------------------------------------------------------- public void test_checkCompare_functionality() throws Exception { assertTrue(IOCase.SENSITIVE.checkCompareTo("ABC", "") > 0); assertTrue(IOCase.SENSITIVE.checkCompareTo("", "ABC") < 0); assertTrue(IOCase.SENSITIVE.checkCompareTo("ABC", "DEF") < 0); assertTrue(IOCase.SENSITIVE.checkCompareTo("DEF", "ABC") > 0); assertEquals(0, IOCase.SENSITIVE.checkCompareTo("ABC", "ABC")); assertEquals(0, IOCase.SENSITIVE.checkCompareTo("", "")); try { IOCase.SENSITIVE.checkCompareTo("ABC", null); fail(); } catch (NullPointerException ex) {} try { IOCase.SENSITIVE.checkCompareTo(null, "ABC"); fail(); } catch (NullPointerException ex) {} try { IOCase.SENSITIVE.checkCompareTo(null, null); fail(); } catch (NullPointerException ex) {} } public void test_checkCompare_case() throws Exception { assertEquals(0, IOCase.SENSITIVE.checkCompareTo("ABC", "ABC")); assertTrue(IOCase.SENSITIVE.checkCompareTo("ABC", "abc") < 0); assertTrue(IOCase.SENSITIVE.checkCompareTo("abc", "ABC") > 0); assertEquals(0, IOCase.INSENSITIVE.checkCompareTo("ABC", "ABC")); assertEquals(0, IOCase.INSENSITIVE.checkCompareTo("ABC", "abc")); assertEquals(0, IOCase.INSENSITIVE.checkCompareTo("abc", "ABC")); assertEquals(0, IOCase.SYSTEM.checkCompareTo("ABC", "ABC")); assertEquals(WINDOWS, IOCase.SYSTEM.checkCompareTo("ABC", "abc") == 0); assertEquals(WINDOWS, IOCase.SYSTEM.checkCompareTo("abc", "ABC") == 0); } //----------------------------------------------------------------------- public void test_checkEquals_functionality() throws Exception { assertFalse(IOCase.SENSITIVE.checkEquals("ABC", "")); assertFalse(IOCase.SENSITIVE.checkEquals("ABC", "A")); assertFalse(IOCase.SENSITIVE.checkEquals("ABC", "AB")); assertTrue(IOCase.SENSITIVE.checkEquals("ABC", "ABC")); assertFalse(IOCase.SENSITIVE.checkEquals("ABC", "BC")); assertFalse(IOCase.SENSITIVE.checkEquals("ABC", "C")); assertFalse(IOCase.SENSITIVE.checkEquals("ABC", "ABCD")); assertFalse(IOCase.SENSITIVE.checkEquals("", "ABC")); assertTrue(IOCase.SENSITIVE.checkEquals("", "")); try { IOCase.SENSITIVE.checkEquals("ABC", null); fail(); } catch (NullPointerException ex) {} try { IOCase.SENSITIVE.checkEquals(null, "ABC"); fail(); } catch (NullPointerException ex) {} try { IOCase.SENSITIVE.checkEquals(null, null); fail(); } catch (NullPointerException ex) {} } public void test_checkEquals_case() throws Exception { assertTrue(IOCase.SENSITIVE.checkEquals("ABC", "ABC")); assertFalse(IOCase.SENSITIVE.checkEquals("ABC", "Abc")); assertTrue(IOCase.INSENSITIVE.checkEquals("ABC", "ABC")); assertTrue(IOCase.INSENSITIVE.checkEquals("ABC", "Abc")); assertTrue(IOCase.SYSTEM.checkEquals("ABC", "ABC")); assertEquals(WINDOWS, IOCase.SYSTEM.checkEquals("ABC", "Abc")); } //----------------------------------------------------------------------- public void test_checkStartsWith_functionality() throws Exception { assertTrue(IOCase.SENSITIVE.checkStartsWith("ABC", "")); assertTrue(IOCase.SENSITIVE.checkStartsWith("ABC", "A")); assertTrue(IOCase.SENSITIVE.checkStartsWith("ABC", "AB")); assertTrue(IOCase.SENSITIVE.checkStartsWith("ABC", "ABC")); assertFalse(IOCase.SENSITIVE.checkStartsWith("ABC", "BC")); assertFalse(IOCase.SENSITIVE.checkStartsWith("ABC", "C")); assertFalse(IOCase.SENSITIVE.checkStartsWith("ABC", "ABCD")); assertFalse(IOCase.SENSITIVE.checkStartsWith("", "ABC")); assertTrue(IOCase.SENSITIVE.checkStartsWith("", "")); try { IOCase.SENSITIVE.checkStartsWith("ABC", null); fail(); } catch (NullPointerException ex) {} try { IOCase.SENSITIVE.checkStartsWith(null, "ABC"); fail(); } catch (NullPointerException ex) {} try { IOCase.SENSITIVE.checkStartsWith(null, null); fail(); } catch (NullPointerException ex) {} } public void test_checkStartsWith_case() throws Exception { assertTrue(IOCase.SENSITIVE.checkStartsWith("ABC", "AB")); assertFalse(IOCase.SENSITIVE.checkStartsWith("ABC", "Ab")); assertTrue(IOCase.INSENSITIVE.checkStartsWith("ABC", "AB")); assertTrue(IOCase.INSENSITIVE.checkStartsWith("ABC", "Ab")); assertTrue(IOCase.SYSTEM.checkStartsWith("ABC", "AB")); assertEquals(WINDOWS, IOCase.SYSTEM.checkStartsWith("ABC", "Ab")); } //----------------------------------------------------------------------- public void test_checkEndsWith_functionality() throws Exception { assertTrue(IOCase.SENSITIVE.checkEndsWith("ABC", "")); assertFalse(IOCase.SENSITIVE.checkEndsWith("ABC", "A")); assertFalse(IOCase.SENSITIVE.checkEndsWith("ABC", "AB")); assertTrue(IOCase.SENSITIVE.checkEndsWith("ABC", "ABC")); assertTrue(IOCase.SENSITIVE.checkEndsWith("ABC", "BC")); assertTrue(IOCase.SENSITIVE.checkEndsWith("ABC", "C")); assertFalse(IOCase.SENSITIVE.checkEndsWith("ABC", "ABCD")); assertFalse(IOCase.SENSITIVE.checkEndsWith("", "ABC")); assertTrue(IOCase.SENSITIVE.checkEndsWith("", "")); try { IOCase.SENSITIVE.checkEndsWith("ABC", null); fail(); } catch (NullPointerException ex) {} try { IOCase.SENSITIVE.checkEndsWith(null, "ABC"); fail(); } catch (NullPointerException ex) {} try { IOCase.SENSITIVE.checkEndsWith(null, null); fail(); } catch (NullPointerException ex) {} } public void test_checkEndsWith_case() throws Exception { assertTrue(IOCase.SENSITIVE.checkEndsWith("ABC", "BC")); assertFalse(IOCase.SENSITIVE.checkEndsWith("ABC", "Bc")); assertTrue(IOCase.INSENSITIVE.checkEndsWith("ABC", "BC")); assertTrue(IOCase.INSENSITIVE.checkEndsWith("ABC", "Bc")); assertTrue(IOCase.SYSTEM.checkEndsWith("ABC", "BC")); assertEquals(WINDOWS, IOCase.SYSTEM.checkEndsWith("ABC", "Bc")); } //----------------------------------------------------------------------- public void test_checkIndexOf_functionality() throws Exception { // start assertEquals(0, IOCase.SENSITIVE.checkIndexOf("ABCDEFGHIJ", 0, "A")); assertEquals(-1, IOCase.SENSITIVE.checkIndexOf("ABCDEFGHIJ", 1, "A")); assertEquals(0, IOCase.SENSITIVE.checkIndexOf("ABCDEFGHIJ", 0, "AB")); assertEquals(-1, IOCase.SENSITIVE.checkIndexOf("ABCDEFGHIJ", 1, "AB")); assertEquals(0, IOCase.SENSITIVE.checkIndexOf("ABCDEFGHIJ", 0, "ABC")); assertEquals(-1, IOCase.SENSITIVE.checkIndexOf("ABCDEFGHIJ", 1, "ABC")); // middle assertEquals(3, IOCase.SENSITIVE.checkIndexOf("ABCDEFGHIJ", 0, "D")); assertEquals(3, IOCase.SENSITIVE.checkIndexOf("ABCDEFGHIJ", 3, "D")); assertEquals(-1, IOCase.SENSITIVE.checkIndexOf("ABCDEFGHIJ", 4, "D")); assertEquals(3, IOCase.SENSITIVE.checkIndexOf("ABCDEFGHIJ", 0, "DE")); assertEquals(3, IOCase.SENSITIVE.checkIndexOf("ABCDEFGHIJ", 3, "DE")); assertEquals(-1, IOCase.SENSITIVE.checkIndexOf("ABCDEFGHIJ", 4, "DE")); assertEquals(3, IOCase.SENSITIVE.checkIndexOf("ABCDEFGHIJ", 0, "DEF")); assertEquals(3, IOCase.SENSITIVE.checkIndexOf("ABCDEFGHIJ", 3, "DEF")); assertEquals(-1, IOCase.SENSITIVE.checkIndexOf("ABCDEFGHIJ", 4, "DEF")); // end assertEquals(9, IOCase.SENSITIVE.checkIndexOf("ABCDEFGHIJ", 0, "J")); assertEquals(9, IOCase.SENSITIVE.checkIndexOf("ABCDEFGHIJ", 8, "J")); assertEquals(9, IOCase.SENSITIVE.checkIndexOf("ABCDEFGHIJ", 9, "J")); assertEquals(8, IOCase.SENSITIVE.checkIndexOf("ABCDEFGHIJ", 0, "IJ")); assertEquals(8, IOCase.SENSITIVE.checkIndexOf("ABCDEFGHIJ", 8, "IJ")); assertEquals(-1, IOCase.SENSITIVE.checkIndexOf("ABCDEFGHIJ", 9, "IJ")); assertEquals(7, IOCase.SENSITIVE.checkIndexOf("ABCDEFGHIJ", 6, "HIJ")); assertEquals(7, IOCase.SENSITIVE.checkIndexOf("ABCDEFGHIJ", 7, "HIJ")); assertEquals(-1, IOCase.SENSITIVE.checkIndexOf("ABCDEFGHIJ", 8, "HIJ")); // not found assertEquals(-1, IOCase.SENSITIVE.checkIndexOf("ABCDEFGHIJ", 0, "DED")); // too long assertEquals(-1, IOCase.SENSITIVE.checkIndexOf("DEF", 0, "ABCDEFGHIJ")); try { IOCase.SENSITIVE.checkIndexOf("ABC", 0, null); fail(); } catch (NullPointerException ex) {} try { IOCase.SENSITIVE.checkIndexOf(null, 0, "ABC"); fail(); } catch (NullPointerException ex) {} try { IOCase.SENSITIVE.checkIndexOf(null, 0, null); fail(); } catch (NullPointerException ex) {} } public void test_checkIndexOf_case() throws Exception { assertEquals(1, IOCase.SENSITIVE.checkIndexOf("ABC", 0, "BC")); assertEquals(-1, IOCase.SENSITIVE.checkIndexOf("ABC", 0, "Bc")); assertEquals(1, IOCase.INSENSITIVE.checkIndexOf("ABC", 0, "BC")); assertEquals(1, IOCase.INSENSITIVE.checkIndexOf("ABC", 0, "Bc")); assertEquals(1, IOCase.SYSTEM.checkIndexOf("ABC", 0, "BC")); assertEquals(WINDOWS ? 1 : -1, IOCase.SYSTEM.checkIndexOf("ABC", 0, "Bc")); } //----------------------------------------------------------------------- public void test_checkRegionMatches_functionality() throws Exception { assertTrue(IOCase.SENSITIVE.checkRegionMatches("ABC", 0, "")); assertTrue(IOCase.SENSITIVE.checkRegionMatches("ABC", 0, "A")); assertTrue(IOCase.SENSITIVE.checkRegionMatches("ABC", 0, "AB")); assertTrue(IOCase.SENSITIVE.checkRegionMatches("ABC", 0, "ABC")); assertFalse(IOCase.SENSITIVE.checkRegionMatches("ABC", 0, "BC")); assertFalse(IOCase.SENSITIVE.checkRegionMatches("ABC", 0, "C")); assertFalse(IOCase.SENSITIVE.checkRegionMatches("ABC", 0, "ABCD")); assertFalse(IOCase.SENSITIVE.checkRegionMatches("", 0, "ABC")); assertTrue(IOCase.SENSITIVE.checkRegionMatches("", 0, "")); assertTrue(IOCase.SENSITIVE.checkRegionMatches("ABC", 1, "")); assertFalse(IOCase.SENSITIVE.checkRegionMatches("ABC", 1, "A")); assertFalse(IOCase.SENSITIVE.checkRegionMatches("ABC", 1, "AB")); assertFalse(IOCase.SENSITIVE.checkRegionMatches("ABC", 1, "ABC")); assertTrue(IOCase.SENSITIVE.checkRegionMatches("ABC", 1, "BC")); assertFalse(IOCase.SENSITIVE.checkRegionMatches("ABC", 1, "C")); assertFalse(IOCase.SENSITIVE.checkRegionMatches("ABC", 1, "ABCD")); assertFalse(IOCase.SENSITIVE.checkRegionMatches("", 1, "ABC")); assertFalse(IOCase.SENSITIVE.checkRegionMatches("", 1, "")); try { IOCase.SENSITIVE.checkRegionMatches("ABC", 0, null); fail(); } catch (NullPointerException ex) {} try { IOCase.SENSITIVE.checkRegionMatches(null, 0, "ABC"); fail(); } catch (NullPointerException ex) {} try { IOCase.SENSITIVE.checkRegionMatches(null, 0, null); fail(); } catch (NullPointerException ex) {} try { IOCase.SENSITIVE.checkRegionMatches("ABC", 1, null); fail(); } catch (NullPointerException ex) {} try { IOCase.SENSITIVE.checkRegionMatches(null, 1, "ABC"); fail(); } catch (NullPointerException ex) {} try { IOCase.SENSITIVE.checkRegionMatches(null, 1, null); fail(); } catch (NullPointerException ex) {} } public void test_checkRegionMatches_case() throws Exception { assertTrue(IOCase.SENSITIVE.checkRegionMatches("ABC", 0, "AB")); assertFalse(IOCase.SENSITIVE.checkRegionMatches("ABC", 0, "Ab")); assertTrue(IOCase.INSENSITIVE.checkRegionMatches("ABC", 0, "AB")); assertTrue(IOCase.INSENSITIVE.checkRegionMatches("ABC", 0, "Ab")); assertTrue(IOCase.SYSTEM.checkRegionMatches("ABC", 0, "AB")); assertEquals(WINDOWS, IOCase.SYSTEM.checkRegionMatches("ABC", 0, "Ab")); } //----------------------------------------------------------------------- private IOCase serialize(IOCase value) throws Exception { ByteArrayOutputStream buf = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(buf); out.writeObject(value); out.flush(); out.close(); ByteArrayInputStream bufin = new ByteArrayInputStream(buf.toByteArray()); ObjectInputStream in = new ObjectInputStream(bufin); return (IOCase) in.readObject(); } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/FileUtilsListFilesTestCase.java0000644000175000017500000002031712125050425032132 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import org.apache.commons.io.filefilter.FileFilterUtils; import org.apache.commons.io.filefilter.IOFileFilter; import org.apache.commons.io.testtools.FileBasedTestCase; /** * Test cases for FileUtils.listFiles() methods. */ public class FileUtilsListFilesTestCase extends FileBasedTestCase { public FileUtilsListFilesTestCase(String name) { super(name); } private File getLocalTestDirectory() { return new File(getTestDirectory(), "list-files"); } /** * @see junit.framework.TestCase#setUp() */ @Override protected void setUp() throws Exception { File dir = getLocalTestDirectory(); if (dir.exists()) { FileUtils.deleteDirectory(dir); } dir.mkdirs(); File file = new File(dir, "dummy-build.xml"); FileUtils.touch(file); file = new File(dir, "README"); FileUtils.touch(file); dir = new File(dir, "subdir1"); dir.mkdirs(); file = new File(dir, "dummy-build.xml"); FileUtils.touch(file); file = new File(dir, "dummy-readme.txt"); FileUtils.touch(file); dir = new File(dir, "subsubdir1"); dir.mkdirs(); file = new File(dir, "dummy-file.txt"); FileUtils.touch(file); file = new File(dir, "dummy-index.html"); FileUtils.touch(file); dir = dir.getParentFile(); dir = new File(dir, "CVS"); dir.mkdirs(); file = new File(dir, "Entries"); FileUtils.touch(file); file = new File(dir, "Repository"); FileUtils.touch(file); } /** * @see junit.framework.TestCase#tearDown() */ @Override protected void tearDown() throws Exception { File dir = getLocalTestDirectory(); FileUtils.deleteDirectory(dir); } private Collection filesToFilenames(Collection files) { Collection filenames = new ArrayList(files.size()); for (File file : files) { filenames.add(file.getName()); } return filenames; } private Collection filesToFilenames(Iterator files) { Collection filenames = new ArrayList(); while (files.hasNext()) { filenames.add(files.next().getName()); } return filenames; } public void testIterateFilesByExtension() throws Exception { String[] extensions = { "xml", "txt" }; Iterator files = FileUtils.iterateFiles(getLocalTestDirectory(), extensions, false); Collection filenames = filesToFilenames(files); assertEquals(1, filenames.size()); assertTrue(filenames.contains("dummy-build.xml")); assertFalse(filenames.contains("README")); assertFalse(filenames.contains("dummy-file.txt")); files = FileUtils.iterateFiles(getLocalTestDirectory(), extensions, true); filenames = filesToFilenames(files); assertEquals(4, filenames.size()); assertTrue(filenames.contains("dummy-file.txt")); assertFalse(filenames.contains("dummy-index.html")); files = FileUtils.iterateFiles(getLocalTestDirectory(), null, false); filenames = filesToFilenames(files); assertEquals(2, filenames.size()); assertTrue(filenames.contains("dummy-build.xml")); assertTrue(filenames.contains("README")); assertFalse(filenames.contains("dummy-file.txt")); } public void testListFilesByExtension() throws Exception { String[] extensions = {"xml", "txt"}; Collection files = FileUtils.listFiles(getLocalTestDirectory(), extensions, false); assertEquals(1, files.size()); Collection filenames = filesToFilenames(files); assertTrue(filenames.contains("dummy-build.xml")); assertFalse(filenames.contains("README")); assertFalse(filenames.contains("dummy-file.txt")); files = FileUtils.listFiles(getLocalTestDirectory(), extensions, true); filenames = filesToFilenames(files); assertEquals(4, filenames.size()); assertTrue(filenames.contains("dummy-file.txt")); assertFalse(filenames.contains("dummy-index.html")); files = FileUtils.listFiles(getLocalTestDirectory(), null, false); assertEquals(2, files.size()); filenames = filesToFilenames(files); assertTrue(filenames.contains("dummy-build.xml")); assertTrue(filenames.contains("README")); assertFalse(filenames.contains("dummy-file.txt")); } public void testListFiles() throws Exception { Collection files; Collection filenames; IOFileFilter fileFilter; IOFileFilter dirFilter; //First, find non-recursively fileFilter = FileFilterUtils.trueFileFilter(); files = FileUtils.listFiles(getLocalTestDirectory(), fileFilter, (IOFileFilter)null); filenames = filesToFilenames(files); assertTrue("'dummy-build.xml' is missing", filenames.contains("dummy-build.xml")); assertFalse("'dummy-index.html' shouldn't be found", filenames.contains("dummy-index.html")); assertFalse("'Entries' shouldn't be found", filenames.contains("Entries")); //Second, find recursively fileFilter = FileFilterUtils.trueFileFilter(); dirFilter = FileFilterUtils.notFileFilter(FileFilterUtils.nameFileFilter("CVS")); files = FileUtils.listFiles(getLocalTestDirectory(), fileFilter, dirFilter); filenames = filesToFilenames(files); assertTrue("'dummy-build.xml' is missing", filenames.contains("dummy-build.xml")); assertTrue("'dummy-index.html' is missing", filenames.contains("dummy-index.html")); assertFalse("'Entries' shouldn't be found", filenames.contains("Entries")); //Do the same as above but now with the filter coming from FileFilterUtils fileFilter = FileFilterUtils.trueFileFilter(); dirFilter = FileFilterUtils.makeCVSAware(null); files = FileUtils.listFiles(getLocalTestDirectory(), fileFilter, dirFilter); filenames = filesToFilenames(files); assertTrue("'dummy-build.xml' is missing", filenames.contains("dummy-build.xml")); assertTrue("'dummy-index.html' is missing", filenames.contains("dummy-index.html")); assertFalse("'Entries' shouldn't be found", filenames.contains("Entries")); //Again with the CVS filter but now with a non-null parameter fileFilter = FileFilterUtils.trueFileFilter(); dirFilter = FileFilterUtils.prefixFileFilter("sub"); dirFilter = FileFilterUtils.makeCVSAware(dirFilter); files = FileUtils.listFiles(getLocalTestDirectory(), fileFilter, dirFilter); filenames = filesToFilenames(files); assertTrue("'dummy-build.xml' is missing", filenames.contains("dummy-build.xml")); assertTrue("'dummy-index.html' is missing", filenames.contains("dummy-index.html")); assertFalse("'Entries' shouldn't be found", filenames.contains("Entries")); try { FileUtils.listFiles(getLocalTestDirectory(), (IOFileFilter)null, (IOFileFilter)null); fail("Expected error about null parameter"); } catch (NullPointerException e) { // expected } } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/HexDumpTest.java0000644000175000017500000002261512125050425027174 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.io.IOException; import junit.framework.TestCase; import org.apache.commons.io.output.ByteArrayOutputStream; /** * @version $Id: HexDumpTest.java 1302056 2012-03-18 03:03:38Z ggregory $ */ public class HexDumpTest extends TestCase { /** * Creates new HexDumpTest * * @param name */ public HexDumpTest(String name) { super(name); } private char toHex(int n) { char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; return hexChars[n % 16]; } /** * test dump method * * @exception IOException */ public void testDump() throws IOException { byte[] testArray = new byte[256]; for (int j = 0; j < 256; j++) { testArray[j] = (byte) j; } ByteArrayOutputStream stream = new ByteArrayOutputStream(); HexDump.dump(testArray, 0, stream, 0); byte[] outputArray = new byte[16 * (73 + HexDump.EOL.length())]; for (int j = 0; j < 16; j++) { int offset = (73 + HexDump.EOL.length()) * j; outputArray[offset++] = (byte) '0'; outputArray[offset++] = (byte) '0'; outputArray[offset++] = (byte) '0'; outputArray[offset++] = (byte) '0'; outputArray[offset++] = (byte) '0'; outputArray[offset++] = (byte) '0'; outputArray[offset++] = (byte) toHex(j); outputArray[offset++] = (byte) '0'; outputArray[offset++] = (byte) ' '; for (int k = 0; k < 16; k++) { outputArray[offset++] = (byte) toHex(j); outputArray[offset++] = (byte) toHex(k); outputArray[offset++] = (byte) ' '; } for (int k = 0; k < 16; k++) { outputArray[offset++] = (byte) toAscii((j * 16) + k); } System.arraycopy(HexDump.EOL.getBytes(), 0, outputArray, offset, HexDump.EOL.getBytes().length); } byte[] actualOutput = stream.toByteArray(); assertEquals("array size mismatch", outputArray.length, actualOutput.length); for (int j = 0; j < outputArray.length; j++) { assertEquals("array[ " + j + "] mismatch", outputArray[j], actualOutput[j]); } // verify proper behavior with non-zero offset stream = new ByteArrayOutputStream(); HexDump.dump(testArray, 0x10000000, stream, 0); outputArray = new byte[16 * (73 + HexDump.EOL.length())]; for (int j = 0; j < 16; j++) { int offset = (73 + HexDump.EOL.length()) * j; outputArray[offset++] = (byte) '1'; outputArray[offset++] = (byte) '0'; outputArray[offset++] = (byte) '0'; outputArray[offset++] = (byte) '0'; outputArray[offset++] = (byte) '0'; outputArray[offset++] = (byte) '0'; outputArray[offset++] = (byte) toHex(j); outputArray[offset++] = (byte) '0'; outputArray[offset++] = (byte) ' '; for (int k = 0; k < 16; k++) { outputArray[offset++] = (byte) toHex(j); outputArray[offset++] = (byte) toHex(k); outputArray[offset++] = (byte) ' '; } for (int k = 0; k < 16; k++) { outputArray[offset++] = (byte) toAscii((j * 16) + k); } System.arraycopy(HexDump.EOL.getBytes(), 0, outputArray, offset, HexDump.EOL.getBytes().length); } actualOutput = stream.toByteArray(); assertEquals("array size mismatch", outputArray.length, actualOutput.length); for (int j = 0; j < outputArray.length; j++) { assertEquals("array[ " + j + "] mismatch", outputArray[j], actualOutput[j]); } // verify proper behavior with negative offset stream = new ByteArrayOutputStream(); HexDump.dump(testArray, 0xFF000000, stream, 0); outputArray = new byte[16 * (73 + HexDump.EOL.length())]; for (int j = 0; j < 16; j++) { int offset = (73 + HexDump.EOL.length()) * j; outputArray[offset++] = (byte) 'F'; outputArray[offset++] = (byte) 'F'; outputArray[offset++] = (byte) '0'; outputArray[offset++] = (byte) '0'; outputArray[offset++] = (byte) '0'; outputArray[offset++] = (byte) '0'; outputArray[offset++] = (byte) toHex(j); outputArray[offset++] = (byte) '0'; outputArray[offset++] = (byte) ' '; for (int k = 0; k < 16; k++) { outputArray[offset++] = (byte) toHex(j); outputArray[offset++] = (byte) toHex(k); outputArray[offset++] = (byte) ' '; } for (int k = 0; k < 16; k++) { outputArray[offset++] = (byte) toAscii((j * 16) + k); } System.arraycopy(HexDump.EOL.getBytes(), 0, outputArray, offset, HexDump.EOL.getBytes().length); } actualOutput = stream.toByteArray(); assertEquals("array size mismatch", outputArray.length, actualOutput.length); for (int j = 0; j < outputArray.length; j++) { assertEquals("array[ " + j + "] mismatch", outputArray[j], actualOutput[j]); } // verify proper behavior with non-zero index stream = new ByteArrayOutputStream(); HexDump.dump(testArray, 0x10000000, stream, 0x81); outputArray = new byte[(8 * (73 + HexDump.EOL.length())) - 1]; for (int j = 0; j < 8; j++) { int offset = (73 + HexDump.EOL.length()) * j; outputArray[offset++] = (byte) '1'; outputArray[offset++] = (byte) '0'; outputArray[offset++] = (byte) '0'; outputArray[offset++] = (byte) '0'; outputArray[offset++] = (byte) '0'; outputArray[offset++] = (byte) '0'; outputArray[offset++] = (byte) toHex(j + 8); outputArray[offset++] = (byte) '1'; outputArray[offset++] = (byte) ' '; for (int k = 0; k < 16; k++) { int index = 0x81 + (j * 16) + k; if (index < 0x100) { outputArray[offset++] = (byte) toHex(index / 16); outputArray[offset++] = (byte) toHex(index); } else { outputArray[offset++] = (byte) ' '; outputArray[offset++] = (byte) ' '; } outputArray[offset++] = (byte) ' '; } for (int k = 0; k < 16; k++) { int index = 0x81 + (j * 16) + k; if (index < 0x100) { outputArray[offset++] = (byte) toAscii(index); } } System.arraycopy(HexDump.EOL.getBytes(), 0, outputArray, offset, HexDump.EOL.getBytes().length); } actualOutput = stream.toByteArray(); assertEquals("array size mismatch", outputArray.length, actualOutput.length); for (int j = 0; j < outputArray.length; j++) { assertEquals("array[ " + j + "] mismatch", outputArray[j], actualOutput[j]); } // verify proper behavior with negative index try { HexDump.dump(testArray, 0x10000000, new ByteArrayOutputStream(), -1); fail("should have caught ArrayIndexOutOfBoundsException on negative index"); } catch (ArrayIndexOutOfBoundsException ignored_exception) { // as expected } // verify proper behavior with index that is too large try { HexDump.dump(testArray, 0x10000000, new ByteArrayOutputStream(), testArray.length); fail("should have caught ArrayIndexOutOfBoundsException on large index"); } catch (ArrayIndexOutOfBoundsException ignored_exception) { // as expected } // verify proper behavior with null stream try { HexDump.dump(testArray, 0x10000000, null, 0); fail("should have caught IllegalArgumentException on negative index"); } catch (IllegalArgumentException ignored_exception) { // as expected } } private char toAscii(int c) { char rval = '.'; if ((c >= 32) && (c <= 126)) { rval = (char) c; } return rval; } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/FileDeleteStrategyTestCase.java0000644000175000017500000001102712125050425032136 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.io.File; import java.io.IOException; import org.apache.commons.io.testtools.FileBasedTestCase; /** * Test for FileDeleteStrategy. * * @version $Id: FileDeleteStrategyTestCase.java 1302056 2012-03-18 03:03:38Z ggregory $ * @see FileDeleteStrategy */ public class FileDeleteStrategyTestCase extends FileBasedTestCase { public FileDeleteStrategyTestCase(String name) { super(name); } @Override protected void setUp() throws Exception { super.setUp(); } @Override protected void tearDown() throws Exception { super.tearDown(); } //----------------------------------------------------------------------- public void testDeleteNormal() throws Exception { File baseDir = getTestDirectory(); File subDir = new File(baseDir, "test"); assertTrue(subDir.mkdir()); File subFile = new File(subDir, "a.txt"); createFile(subFile, 16); assertTrue(subDir.exists()); assertTrue(subFile.exists()); // delete dir try { FileDeleteStrategy.NORMAL.delete(subDir); fail(); } catch (IOException ex) { // expected } assertTrue(subDir.exists()); assertTrue(subFile.exists()); // delete file FileDeleteStrategy.NORMAL.delete(subFile); assertTrue(subDir.exists()); assertFalse(subFile.exists()); // delete dir FileDeleteStrategy.NORMAL.delete(subDir); assertFalse(subDir.exists()); // delete dir FileDeleteStrategy.NORMAL.delete(subDir); // no error assertFalse(subDir.exists()); } public void testDeleteQuietlyNormal() throws Exception { File baseDir = getTestDirectory(); File subDir = new File(baseDir, "test"); assertTrue(subDir.mkdir()); File subFile = new File(subDir, "a.txt"); createFile(subFile, 16); assertTrue(subDir.exists()); assertTrue(subFile.exists()); // delete dir assertFalse(FileDeleteStrategy.NORMAL.deleteQuietly(subDir)); assertTrue(subDir.exists()); assertTrue(subFile.exists()); // delete file assertTrue(FileDeleteStrategy.NORMAL.deleteQuietly(subFile)); assertTrue(subDir.exists()); assertFalse(subFile.exists()); // delete dir assertTrue(FileDeleteStrategy.NORMAL.deleteQuietly(subDir)); assertFalse(subDir.exists()); // delete dir assertTrue(FileDeleteStrategy.NORMAL.deleteQuietly(subDir)); // no error assertFalse(subDir.exists()); } public void testDeleteForce() throws Exception { File baseDir = getTestDirectory(); File subDir = new File(baseDir, "test"); assertTrue(subDir.mkdir()); File subFile = new File(subDir, "a.txt"); createFile(subFile, 16); assertTrue(subDir.exists()); assertTrue(subFile.exists()); // delete dir FileDeleteStrategy.FORCE.delete(subDir); assertFalse(subDir.exists()); assertFalse(subFile.exists()); // delete dir FileDeleteStrategy.FORCE.delete(subDir); // no error assertFalse(subDir.exists()); } public void testDeleteNull() throws Exception { try { FileDeleteStrategy.NORMAL.delete((File) null); fail(); } catch (NullPointerException ex) { // expected } assertTrue(FileDeleteStrategy.NORMAL.deleteQuietly((File) null)); } public void testToString() { assertEquals("FileDeleteStrategy[Normal]", FileDeleteStrategy.NORMAL.toString()); assertEquals("FileDeleteStrategy[Force]", FileDeleteStrategy.FORCE.toString()); } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/SelectorAdapter.java0000644000175000017500000000361212125050425030037 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.io.IOException; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.spi.SelectorProvider; import java.util.Set; /** * Extends {@link Selector} with no-ops for testing. * * @version $Id: SelectorAdapter.java 1302382 2012-03-19 11:50:35Z sebb $ */ public class SelectorAdapter extends Selector { @Override public boolean isOpen() { return false; } @Override public SelectorProvider provider() { return null; } @Override public Set keys() { return null; } @Override public Set selectedKeys() { return null; } @Override public int selectNow() throws IOException { return 0; } @Override public int select(long timeout) throws IOException { return 0; } @Override public int select() throws IOException { return 0; } @Override public Selector wakeup() { return null; } @Override public void close() throws IOException { } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/FilenameUtilsWildcardTestCase.java0000644000175000017500000002730112125050425032626 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.io.File; import java.util.Locale; import junit.framework.TestCase; public class FilenameUtilsWildcardTestCase extends TestCase { private static final boolean WINDOWS = File.separatorChar == '\\'; public FilenameUtilsWildcardTestCase(String name) { super(name); } //----------------------------------------------------------------------- // Testing: // FilenameUtils.wildcardMatch(String,String) public void testMatch() { assertFalse(FilenameUtils.wildcardMatch(null, "Foo")); assertFalse(FilenameUtils.wildcardMatch("Foo", null)); assertTrue(FilenameUtils.wildcardMatch(null, null)); assertTrue(FilenameUtils.wildcardMatch("Foo", "Foo")); assertTrue(FilenameUtils.wildcardMatch("", "")); assertTrue(FilenameUtils.wildcardMatch("", "*")); assertFalse(FilenameUtils.wildcardMatch("", "?")); assertTrue(FilenameUtils.wildcardMatch("Foo", "Fo*")); assertTrue(FilenameUtils.wildcardMatch("Foo", "Fo?")); assertTrue(FilenameUtils.wildcardMatch("Foo Bar and Catflap", "Fo*")); assertTrue(FilenameUtils.wildcardMatch("New Bookmarks", "N?w ?o?k??r?s")); assertFalse(FilenameUtils.wildcardMatch("Foo", "Bar")); assertTrue(FilenameUtils.wildcardMatch("Foo Bar Foo", "F*o Bar*")); assertTrue(FilenameUtils.wildcardMatch("Adobe Acrobat Installer", "Ad*er")); assertTrue(FilenameUtils.wildcardMatch("Foo", "*Foo")); assertTrue(FilenameUtils.wildcardMatch("BarFoo", "*Foo")); assertTrue(FilenameUtils.wildcardMatch("Foo", "Foo*")); assertTrue(FilenameUtils.wildcardMatch("FooBar", "Foo*")); assertFalse(FilenameUtils.wildcardMatch("FOO", "*Foo")); assertFalse(FilenameUtils.wildcardMatch("BARFOO", "*Foo")); assertFalse(FilenameUtils.wildcardMatch("FOO", "Foo*")); assertFalse(FilenameUtils.wildcardMatch("FOOBAR", "Foo*")); } public void testMatchOnSystem() { assertFalse(FilenameUtils.wildcardMatchOnSystem(null, "Foo")); assertFalse(FilenameUtils.wildcardMatchOnSystem("Foo", null)); assertTrue(FilenameUtils.wildcardMatchOnSystem(null, null)); assertTrue(FilenameUtils.wildcardMatchOnSystem("Foo", "Foo")); assertTrue(FilenameUtils.wildcardMatchOnSystem("", "")); assertTrue(FilenameUtils.wildcardMatchOnSystem("Foo", "Fo*")); assertTrue(FilenameUtils.wildcardMatchOnSystem("Foo", "Fo?")); assertTrue(FilenameUtils.wildcardMatchOnSystem("Foo Bar and Catflap", "Fo*")); assertTrue(FilenameUtils.wildcardMatchOnSystem("New Bookmarks", "N?w ?o?k??r?s")); assertFalse(FilenameUtils.wildcardMatchOnSystem("Foo", "Bar")); assertTrue(FilenameUtils.wildcardMatchOnSystem("Foo Bar Foo", "F*o Bar*")); assertTrue(FilenameUtils.wildcardMatchOnSystem("Adobe Acrobat Installer", "Ad*er")); assertTrue(FilenameUtils.wildcardMatchOnSystem("Foo", "*Foo")); assertTrue(FilenameUtils.wildcardMatchOnSystem("BarFoo", "*Foo")); assertTrue(FilenameUtils.wildcardMatchOnSystem("Foo", "Foo*")); assertTrue(FilenameUtils.wildcardMatchOnSystem("FooBar", "Foo*")); assertEquals(WINDOWS, FilenameUtils.wildcardMatchOnSystem("FOO", "*Foo")); assertEquals(WINDOWS, FilenameUtils.wildcardMatchOnSystem("BARFOO", "*Foo")); assertEquals(WINDOWS, FilenameUtils.wildcardMatchOnSystem("FOO", "Foo*")); assertEquals(WINDOWS, FilenameUtils.wildcardMatchOnSystem("FOOBAR", "Foo*")); } public void testMatchCaseSpecified() { assertFalse(FilenameUtils.wildcardMatch(null, "Foo", IOCase.SENSITIVE)); assertFalse(FilenameUtils.wildcardMatch("Foo", null, IOCase.SENSITIVE)); assertTrue(FilenameUtils.wildcardMatch(null, null, IOCase.SENSITIVE)); assertTrue(FilenameUtils.wildcardMatch("Foo", "Foo", IOCase.SENSITIVE)); assertTrue(FilenameUtils.wildcardMatch("", "", IOCase.SENSITIVE)); assertTrue(FilenameUtils.wildcardMatch("Foo", "Fo*", IOCase.SENSITIVE)); assertTrue(FilenameUtils.wildcardMatch("Foo", "Fo?", IOCase.SENSITIVE)); assertTrue(FilenameUtils.wildcardMatch("Foo Bar and Catflap", "Fo*", IOCase.SENSITIVE)); assertTrue(FilenameUtils.wildcardMatch("New Bookmarks", "N?w ?o?k??r?s", IOCase.SENSITIVE)); assertFalse(FilenameUtils.wildcardMatch("Foo", "Bar", IOCase.SENSITIVE)); assertTrue(FilenameUtils.wildcardMatch("Foo Bar Foo", "F*o Bar*", IOCase.SENSITIVE)); assertTrue(FilenameUtils.wildcardMatch("Adobe Acrobat Installer", "Ad*er", IOCase.SENSITIVE)); assertTrue(FilenameUtils.wildcardMatch("Foo", "*Foo", IOCase.SENSITIVE)); assertTrue(FilenameUtils.wildcardMatch("Foo", "Foo*", IOCase.SENSITIVE)); assertTrue(FilenameUtils.wildcardMatch("Foo", "*Foo", IOCase.SENSITIVE)); assertTrue(FilenameUtils.wildcardMatch("BarFoo", "*Foo", IOCase.SENSITIVE)); assertTrue(FilenameUtils.wildcardMatch("Foo", "Foo*", IOCase.SENSITIVE)); assertTrue(FilenameUtils.wildcardMatch("FooBar", "Foo*", IOCase.SENSITIVE)); assertFalse(FilenameUtils.wildcardMatch("FOO", "*Foo", IOCase.SENSITIVE)); assertFalse(FilenameUtils.wildcardMatch("BARFOO", "*Foo", IOCase.SENSITIVE)); assertFalse(FilenameUtils.wildcardMatch("FOO", "Foo*", IOCase.SENSITIVE)); assertFalse(FilenameUtils.wildcardMatch("FOOBAR", "Foo*", IOCase.SENSITIVE)); assertTrue(FilenameUtils.wildcardMatch("FOO", "*Foo", IOCase.INSENSITIVE)); assertTrue(FilenameUtils.wildcardMatch("BARFOO", "*Foo", IOCase.INSENSITIVE)); assertTrue(FilenameUtils.wildcardMatch("FOO", "Foo*", IOCase.INSENSITIVE)); assertTrue(FilenameUtils.wildcardMatch("FOOBAR", "Foo*", IOCase.INSENSITIVE)); assertEquals(WINDOWS, FilenameUtils.wildcardMatch("FOO", "*Foo", IOCase.SYSTEM)); assertEquals(WINDOWS, FilenameUtils.wildcardMatch("BARFOO", "*Foo", IOCase.SYSTEM)); assertEquals(WINDOWS, FilenameUtils.wildcardMatch("FOO", "Foo*", IOCase.SYSTEM)); assertEquals(WINDOWS, FilenameUtils.wildcardMatch("FOOBAR", "Foo*", IOCase.SYSTEM)); } public void testSplitOnTokens() { assertArrayEquals( new String[] { "Ad", "*", "er" }, FilenameUtils.splitOnTokens("Ad*er") ); assertArrayEquals( new String[] { "Ad", "?", "er" }, FilenameUtils.splitOnTokens("Ad?er") ); assertArrayEquals( new String[] { "Test", "*", "?", "One" }, FilenameUtils.splitOnTokens("Test*?One") ); assertArrayEquals( new String[] { "Test", "?", "*", "One" }, FilenameUtils.splitOnTokens("Test?*One") ); assertArrayEquals( new String[] { "*" }, FilenameUtils.splitOnTokens("****") ); assertArrayEquals( new String[] { "*", "?", "?", "*" }, FilenameUtils.splitOnTokens("*??*") ); assertArrayEquals( new String[] { "*", "?", "*", "?", "*" }, FilenameUtils.splitOnTokens("*?**?*") ); assertArrayEquals( new String[] { "h", "?", "?", "*" }, FilenameUtils.splitOnTokens("h??*") ); assertArrayEquals( new String[] { "" }, FilenameUtils.splitOnTokens("") ); } private void assertArrayEquals(Object[] a1, Object[] a2) { assertEquals(a1.length, a2.length); for(int i=0; i= 0 || osName.indexOf("aix") >= 0) { cmd = new String[] {"df", "-P", "/"}; } else if (osName.indexOf("sunos") >= 0 || osName.indexOf("sun os") >= 0 || osName.indexOf("solaris") >= 0) { cmd = new String[] {"/usr/xpg4/bin/df", "-P", "/"}; } else { cmd = new String[] {"df", "/"}; } Process proc = Runtime.getRuntime().exec(cmd); boolean kilobyteBlock = true; BufferedReader r = null; try { r = new BufferedReader(new InputStreamReader(proc.getInputStream())); String line = r.readLine(); Assert.assertNotNull("Unexpected null line", line); if (line.indexOf("512") >= 0) { kilobyteBlock = false; } } finally { IOUtils.closeQuietly(r); } // now perform the test @SuppressWarnings("deprecation") long free = FileSystemUtils.freeSpace("/"); long kb = FileSystemUtils.freeSpaceKb("/"); if (kilobyteBlock) { assertEquals(free, kb, 256d); } else { assertEquals(free / 2d, kb, 256d); } } else { @SuppressWarnings("deprecation") long bytes = FileSystemUtils.freeSpace(""); long kb = FileSystemUtils.freeSpaceKb(""); assertEquals((double) bytes / 1024, kb, 256d); } } //----------------------------------------------------------------------- public void testGetFreeSpaceOS_String_NullPath() throws Exception { FileSystemUtils fsu = new FileSystemUtils(); try { fsu.freeSpaceOS(null, 1, false, -1); fail(); } catch (IllegalArgumentException ex) {} try { fsu.freeSpaceOS(null, 1, true, -1); fail(); } catch (IllegalArgumentException ex) {} } public void testGetFreeSpaceOS_String_InitError() throws Exception { FileSystemUtils fsu = new FileSystemUtils(); try { fsu.freeSpaceOS("", -1, false, -1); fail(); } catch (IllegalStateException ex) {} try { fsu.freeSpaceOS("", -1, true, -1); fail(); } catch (IllegalStateException ex) {} } public void testGetFreeSpaceOS_String_Other() throws Exception { FileSystemUtils fsu = new FileSystemUtils(); try { fsu.freeSpaceOS("", 0, false, -1); fail(); } catch (IllegalStateException ex) {} try { fsu.freeSpaceOS("", 0, true, -1); fail(); } catch (IllegalStateException ex) {} } public void testGetFreeSpaceOS_String_Windows() throws Exception { FileSystemUtils fsu = new FileSystemUtils() { @Override protected long freeSpaceWindows(String path, long timeout) throws IOException { return 12345L; } }; assertEquals(12345L, fsu.freeSpaceOS("", 1, false, -1)); assertEquals(12345L / 1024, fsu.freeSpaceOS("", 1, true, -1)); } public void testGetFreeSpaceOS_String_Unix() throws Exception { FileSystemUtils fsu = new FileSystemUtils() { @Override protected long freeSpaceUnix(String path, boolean kb, boolean posix, long timeout) throws IOException { return kb ? 12345L : 54321; } }; assertEquals(54321L, fsu.freeSpaceOS("", 2, false, -1)); assertEquals(12345L, fsu.freeSpaceOS("", 2, true, -1)); } //----------------------------------------------------------------------- public void testGetFreeSpaceWindows_String_ParseCommaFormatBytes() throws Exception { // this is the format of response when calling dir /c // we have now switched to dir /-c, so we should never get this String lines = " Volume in drive C is HDD\n" + " Volume Serial Number is XXXX-YYYY\n" + "\n" + " Directory of C:\\Documents and Settings\\Xxxx\n" + "\n" + "19/08/2005 22:43 .\n" + "19/08/2005 22:43 ..\n" + "11/08/2005 01:07 81 build.properties\n" + "17/08/2005 21:44 Desktop\n" + " 7 File(s) 180,260 bytes\n" + " 10 Dir(s) 41,411,551,232 bytes free"; FileSystemUtils fsu = new MockFileSystemUtils(0, lines); assertEquals(41411551232L, fsu.freeSpaceWindows("", -1)); } //----------------------------------------------------------------------- public void testGetFreeSpaceWindows_String_EmptyPath() throws Exception { String lines = " Volume in drive C is HDD\n" + " Volume Serial Number is XXXX-YYYY\n" + "\n" + " Directory of C:\\Documents and Settings\\Xxxx\n" + "\n" + "19/08/2005 22:43 .\n" + "19/08/2005 22:43 ..\n" + "11/08/2005 01:07 81 build.properties\n" + "17/08/2005 21:44 Desktop\n" + " 7 File(s) 180260 bytes\n" + " 10 Dir(s) 41411551232 bytes free"; FileSystemUtils fsu = new MockFileSystemUtils(0, lines, "dir /a /-c "); assertEquals(41411551232L, fsu.freeSpaceWindows("", -1)); } public void testGetFreeSpaceWindows_String_NormalResponse() throws Exception { String lines = " Volume in drive C is HDD\n" + " Volume Serial Number is XXXX-YYYY\n" + "\n" + " Directory of C:\\Documents and Settings\\Xxxx\n" + "\n" + "19/08/2005 22:43 .\n" + "19/08/2005 22:43 ..\n" + "11/08/2005 01:07 81 build.properties\n" + "17/08/2005 21:44 Desktop\n" + " 7 File(s) 180260 bytes\n" + " 10 Dir(s) 41411551232 bytes free"; FileSystemUtils fsu = new MockFileSystemUtils(0, lines, "dir /a /-c \"C:\""); assertEquals(41411551232L, fsu.freeSpaceWindows("C:", -1)); } public void testGetFreeSpaceWindows_String_StripDrive() throws Exception { String lines = " Volume in drive C is HDD\n" + " Volume Serial Number is XXXX-YYYY\n" + "\n" + " Directory of C:\\Documents and Settings\\Xxxx\n" + "\n" + "19/08/2005 22:43 .\n" + "19/08/2005 22:43 ..\n" + "11/08/2005 01:07 81 build.properties\n" + "17/08/2005 21:44 Desktop\n" + " 7 File(s) 180260 bytes\n" + " 10 Dir(s) 41411551232 bytes free"; FileSystemUtils fsu = new MockFileSystemUtils(0, lines, "dir /a /-c \"C:\\somedir\""); assertEquals(41411551232L, fsu.freeSpaceWindows("C:\\somedir", -1)); } public void testGetFreeSpaceWindows_String_quoted() throws Exception { String lines = " Volume in drive C is HDD\n" + " Volume Serial Number is XXXX-YYYY\n" + "\n" + " Directory of C:\\Documents and Settings\\Xxxx\n" + "\n" + "19/08/2005 22:43 .\n" + "19/08/2005 22:43 ..\n" + "11/08/2005 01:07 81 build.properties\n" + "17/08/2005 21:44 Desktop\n" + " 7 File(s) 180260 bytes\n" + " 10 Dir(s) 41411551232 bytes free"; FileSystemUtils fsu = new MockFileSystemUtils(0, lines, "dir /a /-c \"C:\\somedir\""); assertEquals(41411551232L, fsu.freeSpaceWindows("\"C:\\somedir\"", -1)); } public void testGetFreeSpaceWindows_String_EmptyResponse() throws Exception { String lines = ""; FileSystemUtils fsu = new MockFileSystemUtils(0, lines); try { fsu.freeSpaceWindows("C:", -1); fail(); } catch (IOException ex) {} } public void testGetFreeSpaceWindows_String_EmptyMultiLineResponse() throws Exception { String lines = "\n\n"; FileSystemUtils fsu = new MockFileSystemUtils(0, lines); try { fsu.freeSpaceWindows("C:", -1); fail(); } catch (IOException ex) {} } public void testGetFreeSpaceWindows_String_InvalidTextResponse() throws Exception { String lines = "BlueScreenOfDeath"; FileSystemUtils fsu = new MockFileSystemUtils(0, lines); try { fsu.freeSpaceWindows("C:", -1); fail(); } catch (IOException ex) {} } public void testGetFreeSpaceWindows_String_NoSuchDirectoryResponse() throws Exception { String lines = " Volume in drive C is HDD\n" + " Volume Serial Number is XXXX-YYYY\n" + "\n" + " Directory of C:\\Documents and Settings\\empty" + "\n"; FileSystemUtils fsu = new MockFileSystemUtils(1, lines); try { fsu.freeSpaceWindows("C:", -1); fail(); } catch (IOException ex) {} } //----------------------------------------------------------------------- public void testGetFreeSpaceUnix_String_EmptyPath() throws Exception { String lines = "Filesystem 1K-blocks Used Available Use% Mounted on\n" + "xxx:/home/users/s 14428928 12956424 1472504 90% /home/users/s"; FileSystemUtils fsu = new MockFileSystemUtils(0, lines); try { fsu.freeSpaceUnix("", false, false, -1); fail(); } catch (IllegalArgumentException ex) {} try { fsu.freeSpaceUnix("", true, false, -1); fail(); } catch (IllegalArgumentException ex) {} try { fsu.freeSpaceUnix("", true, true, -1); fail(); } catch (IllegalArgumentException ex) {} try { fsu.freeSpaceUnix("", false, true, -1); fail(); } catch (IllegalArgumentException ex) {} } public void testGetFreeSpaceUnix_String_NormalResponseLinux() throws Exception { // from Sourceforge 'GNU bash, version 2.05b.0(1)-release (i386-redhat-linux-gnu)' String lines = "Filesystem 1K-blocks Used Available Use% Mounted on\n" + "/dev/xxx 497944 308528 189416 62% /"; FileSystemUtils fsu = new MockFileSystemUtils(0, lines); assertEquals(189416L, fsu.freeSpaceUnix("/", false, false, -1)); } public void testGetFreeSpaceUnix_String_NormalResponseFreeBSD() throws Exception { // from Apache 'FreeBSD 6.1-RELEASE (SMP-turbo)' String lines = "Filesystem 1K-blocks Used Avail Capacity Mounted on\n" + "/dev/xxxxxx 128990 102902 15770 87% /"; FileSystemUtils fsu = new MockFileSystemUtils(0, lines); assertEquals(15770L, fsu.freeSpaceUnix("/", false, false, -1)); } //----------------------------------------------------------------------- public void testGetFreeSpaceUnix_String_NormalResponseKbLinux() throws Exception { // from Sourceforge 'GNU bash, version 2.05b.0(1)-release (i386-redhat-linux-gnu)' // df, df -k and df -kP are all identical String lines = "Filesystem 1K-blocks Used Available Use% Mounted on\n" + "/dev/xxx 497944 308528 189416 62% /"; FileSystemUtils fsu = new MockFileSystemUtils(0, lines); assertEquals(189416L, fsu.freeSpaceUnix("/", true, false, -1)); } public void testGetFreeSpaceUnix_String_NormalResponseKbFreeBSD() throws Exception { // from Apache 'FreeBSD 6.1-RELEASE (SMP-turbo)' // df and df -k are identical, but df -kP uses 512 blocks (not relevant as not used) String lines = "Filesystem 1K-blocks Used Avail Capacity Mounted on\n" + "/dev/xxxxxx 128990 102902 15770 87% /"; FileSystemUtils fsu = new MockFileSystemUtils(0, lines); assertEquals(15770L, fsu.freeSpaceUnix("/", true, false, -1)); } public void testGetFreeSpaceUnix_String_NormalResponseKbSolaris() throws Exception { // from IO-91 - ' SunOS et 5.10 Generic_118822-25 sun4u sparc SUNW,Ultra-4' // non-kb response does not contain free space - see IO-91 String lines = "Filesystem kbytes used avail capacity Mounted on\n" + "/dev/dsk/x0x0x0x0 1350955 815754 481163 63%"; FileSystemUtils fsu = new MockFileSystemUtils(0, lines); assertEquals(481163L, fsu.freeSpaceUnix("/dev/dsk/x0x0x0x0", true, false, -1)); } public void testGetFreeSpaceUnix_String_LongResponse() throws Exception { String lines = "Filesystem 1K-blocks Used Available Use% Mounted on\n" + "xxx-yyyyyyy-zzz:/home/users/s\n" + " 14428928 12956424 1472504 90% /home/users/s"; FileSystemUtils fsu = new MockFileSystemUtils(0, lines); assertEquals(1472504L, fsu.freeSpaceUnix("/home/users/s", false, false, -1)); } public void testGetFreeSpaceUnix_String_LongResponseKb() throws Exception { String lines = "Filesystem 1K-blocks Used Available Use% Mounted on\n" + "xxx-yyyyyyy-zzz:/home/users/s\n" + " 14428928 12956424 1472504 90% /home/users/s"; FileSystemUtils fsu = new MockFileSystemUtils(0, lines); assertEquals(1472504L, fsu.freeSpaceUnix("/home/users/s", true, false, -1)); } public void testGetFreeSpaceUnix_String_EmptyResponse() throws Exception { String lines = ""; FileSystemUtils fsu = new MockFileSystemUtils(0, lines); try { fsu.freeSpaceUnix("/home/users/s", false, false, -1); fail(); } catch (IOException ex) {} try { fsu.freeSpaceUnix("/home/users/s", true, false, -1); fail(); } catch (IOException ex) {} try { fsu.freeSpaceUnix("/home/users/s", false, true, -1); fail(); } catch (IOException ex) {} try { fsu.freeSpaceUnix("/home/users/s", true, true, -1); fail(); } catch (IOException ex) {} } public void testGetFreeSpaceUnix_String_InvalidResponse1() throws Exception { String lines = "Filesystem 1K-blocks Used Available Use% Mounted on\n" + " 14428928 12956424 100"; FileSystemUtils fsu = new MockFileSystemUtils(0, lines); try { fsu.freeSpaceUnix("/home/users/s", false, false, -1); fail(); } catch (IOException ex) {} try { fsu.freeSpaceUnix("/home/users/s", true, false, -1); fail(); } catch (IOException ex) {} try { fsu.freeSpaceUnix("/home/users/s", false, true, -1); fail(); } catch (IOException ex) {} try { fsu.freeSpaceUnix("/home/users/s", true, true, -1); fail(); } catch (IOException ex) {} } public void testGetFreeSpaceUnix_String_InvalidResponse2() throws Exception { String lines = "Filesystem 1K-blocks Used Available Use% Mounted on\n" + "xxx:/home/users/s 14428928 12956424 nnnnnnn 90% /home/users/s"; FileSystemUtils fsu = new MockFileSystemUtils(0, lines); try { fsu.freeSpaceUnix("/home/users/s", false, false, -1); fail(); } catch (IOException ex) {} try { fsu.freeSpaceUnix("/home/users/s", true, false, -1); fail(); } catch (IOException ex) {} try { fsu.freeSpaceUnix("/home/users/s", false, true, -1); fail(); } catch (IOException ex) {} try { fsu.freeSpaceUnix("/home/users/s", true, true, -1); fail(); } catch (IOException ex) {} } public void testGetFreeSpaceUnix_String_InvalidResponse3() throws Exception { String lines = "Filesystem 1K-blocks Used Available Use% Mounted on\n" + "xxx:/home/users/s 14428928 12956424 -1 90% /home/users/s"; FileSystemUtils fsu = new MockFileSystemUtils(0, lines); try { fsu.freeSpaceUnix("/home/users/s", false, false, -1); fail(); } catch (IOException ex) {} try { fsu.freeSpaceUnix("/home/users/s", true, false, -1); fail(); } catch (IOException ex) {} try { fsu.freeSpaceUnix("/home/users/s", false, true, -1); fail(); } catch (IOException ex) {} try { fsu.freeSpaceUnix("/home/users/s", true, true, -1); fail(); } catch (IOException ex) {} } public void testGetFreeSpaceUnix_String_InvalidResponse4() throws Exception { String lines = "Filesystem 1K-blocks Used Available Use% Mounted on\n" + "xxx-yyyyyyy-zzz:/home/users/s"; FileSystemUtils fsu = new MockFileSystemUtils(0, lines); try { fsu.freeSpaceUnix("/home/users/s", false, false, -1); fail(); } catch (IOException ex) {} try { fsu.freeSpaceUnix("/home/users/s", true, false, -1); fail(); } catch (IOException ex) {} try { fsu.freeSpaceUnix("/home/users/s", false, true, -1); fail(); } catch (IOException ex) {} try { fsu.freeSpaceUnix("/home/users/s", true, true, -1); fail(); } catch (IOException ex) {} } //----------------------------------------------------------------------- static class MockFileSystemUtils extends FileSystemUtils { private final int exitCode; private final byte[] bytes; private final String cmd; public MockFileSystemUtils(int exitCode, String lines) { this(exitCode, lines, null); } public MockFileSystemUtils(int exitCode, String lines, String cmd) { this.exitCode = exitCode; this.bytes = lines.getBytes(); this.cmd = cmd; } @Override Process openProcess(String[] params) { if (cmd != null) { assertEquals(cmd, params[params.length - 1]); } return new Process() { @Override public InputStream getErrorStream() { return null; } @Override public InputStream getInputStream() { return new ByteArrayInputStream(bytes); } @Override public OutputStream getOutputStream() { return null; } @Override public int waitFor() throws InterruptedException { return exitCode; } @Override public int exitValue() { return exitCode; } @Override public void destroy() { } }; } } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/CopyUtilsTest.java0000644000175000017500000002104412125050425027550 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; import java.util.Arrays; import org.apache.commons.io.output.ByteArrayOutputStream; import org.apache.commons.io.testtools.FileBasedTestCase; import org.apache.commons.io.testtools.YellOnCloseInputStream; import org.apache.commons.io.testtools.YellOnFlushAndCloseOutputStream; @SuppressWarnings("deprecation") // these are test cases for the deprecated CopyUtils /** * JUnit tests for CopyUtils. * * @version $Id: CopyUtilsTest.java 1302056 2012-03-18 03:03:38Z ggregory $ * @see CopyUtils */ public class CopyUtilsTest extends FileBasedTestCase { /* * NOTE this is not particularly beautiful code. A better way to check for * flush and close status would be to implement "trojan horse" wrapper * implementations of the various stream classes, which set a flag when * relevant methods are called. (JT) */ private static final int FILE_SIZE = 1024 * 4 + 1; private byte[] inData = generateTestData(FILE_SIZE); public CopyUtilsTest(String testName) { super(testName); } // ---------------------------------------------------------------- // Setup // ---------------------------------------------------------------- @Override public void setUp() throws Exception { } @Override public void tearDown() throws Exception { } // ---------------------------------------------------------------- // Tests // ---------------------------------------------------------------- public void testCtor() { new CopyUtils(); // Nothing to assert, the constructor is public and does not blow up. } public void testCopy_byteArrayToOutputStream() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStream(baout, false, true); CopyUtils.copy(inData, out); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); } public void testCopy_byteArrayToWriter() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStream(baout, false, true); Writer writer = new java.io.OutputStreamWriter(out, "US-ASCII"); CopyUtils.copy(inData, writer); writer.flush(); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); } public void testCopy_byteArrayToWriterWithEncoding() throws Exception { String inDataStr = "data"; String charsetName = "UTF-8"; StringWriter writer = new StringWriter(); CopyUtils.copy(inDataStr.getBytes(charsetName), writer, charsetName); assertEquals(inDataStr, writer.toString()); } public void testCopy_inputStreamToOutputStream() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStream(in); ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStream(baout, false, true); int count = CopyUtils.copy(in, out); assertEquals("Not all bytes were read", 0, in.available()); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); assertEquals(inData.length, count); } public void testCopy_inputStreamToWriter() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStream(in); ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStream(baout, false, true); Writer writer = new java.io.OutputStreamWriter(out, "US-ASCII"); CopyUtils.copy(in, writer); writer.flush(); assertEquals("Not all bytes were read", 0, in.available()); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); } public void testCopy_inputStreamToWriterWithEncoding() throws Exception { String inDataStr = "data"; String charsetName = "UTF-8"; StringWriter writer = new StringWriter(); CopyUtils.copy(new ByteArrayInputStream(inDataStr.getBytes(charsetName)), writer, charsetName); assertEquals(inDataStr, writer.toString()); } public void testCopy_readerToOutputStream() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStream(in); Reader reader = new java.io.InputStreamReader(in, "US-ASCII"); ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStream(baout, false, true); CopyUtils.copy(reader, out); //Note: this method *does* flush. It is equivalent to: // OutputStreamWriter _out = new OutputStreamWriter(fout); // IOUtils.copy( fin, _out, 4096 ); // copy( Reader, Writer, int ); // _out.flush(); // out = fout; // Note: rely on the method to flush assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); } public void testCopy_readerToWriter() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStream(in); Reader reader = new java.io.InputStreamReader(in, "US-ASCII"); ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStream(baout, false, true); Writer writer = new java.io.OutputStreamWriter(out, "US-ASCII"); int count = CopyUtils.copy(reader, writer); writer.flush(); assertEquals( "The number of characters returned by copy is wrong", inData.length, count); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); } public void testCopy_stringToOutputStream() throws Exception { String str = new String(inData, "US-ASCII"); ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStream(baout, false, true); CopyUtils.copy(str, out); //Note: this method *does* flush. It is equivalent to: // OutputStreamWriter _out = new OutputStreamWriter(fout); // IOUtils.copy( str, _out, 4096 ); // copy( Reader, Writer, int ); // _out.flush(); // out = fout; // note: we don't flush here; this IOUtils method does it for us assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); } public void testCopy_stringToWriter() throws Exception { String str = new String(inData, "US-ASCII"); ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStream(baout, false, true); Writer writer = new java.io.OutputStreamWriter(out, "US-ASCII"); CopyUtils.copy(str, writer); writer.flush(); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); } } // CopyUtilsTest libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/ThreadMonitorTestCase.java0000644000175000017500000000464612125050425031201 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import junit.framework.TestCase; /** * Tests for {@link ThreadMonitor}. */ public class ThreadMonitorTestCase extends TestCase { public ThreadMonitorTestCase(String name) { super(name); } /** * Test timeout. */ public void testTimeout() { try { Thread monitor = ThreadMonitor.start(100); Thread.sleep(200); ThreadMonitor.stop(monitor); fail("Expected InterruptedException"); } catch (InterruptedException e) { // expected result - timout } } /** * Test task completed before timeout. */ public void testCompletedWithoutTimeout() { try { Thread monitor = ThreadMonitor.start(200); Thread.sleep(100); ThreadMonitor.stop(monitor); } catch (InterruptedException e) { fail("Timed Out"); } } /** * Test No timeout. */ public void testNoTimeout() { // timeout = -1 try { Thread monitor = ThreadMonitor.start(-1); assertNull("Timeout -1, Monitor should be null", monitor); Thread.sleep(100); ThreadMonitor.stop(monitor); } catch (Exception e) { fail("Timeout -1, threw " + e); } // timeout = 0 try { Thread monitor = ThreadMonitor.start(0); assertNull("Timeout 0, Monitor should be null", monitor); Thread.sleep(100); ThreadMonitor.stop(monitor); } catch (Exception e) { fail("Timeout 0, threw " + e); } } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/output/0000755000175000017500000000000012125050425025451 5ustar ebourgebourg././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/output/FileWriterWithEncodingTest.javalibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/output/FileWriterWithEncodingTest.ja0000644000175000017500000001641612125050425033214 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.output; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.charset.Charset; import junit.framework.AssertionFailedError; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.io.testtools.FileBasedTestCase; /** * Tests that the encoding is actually set and used. * * @version $Id: FileWriterWithEncodingTest.java 1302056 2012-03-18 03:03:38Z ggregory $ */ public class FileWriterWithEncodingTest extends FileBasedTestCase { private String defaultEncoding; private File file1; private File file2; private String textContent; public FileWriterWithEncodingTest(String name) { super(name); } @Override public void setUp() { File encodingFinder = new File(getTestDirectory(), "finder.txt"); OutputStreamWriter out = null; try { out = new OutputStreamWriter(new FileOutputStream(encodingFinder)); defaultEncoding = out.getEncoding(); } catch (IOException ex) { throw new RuntimeException(ex.getMessage()); } finally { IOUtils.closeQuietly(out); } file1 = new File(getTestDirectory(), "testfile1.txt"); file2 = new File(getTestDirectory(), "testfile2.txt"); char[] arr = new char[1024]; for (int i = 0; i < arr.length; i++) { arr[i] = (char) i; } textContent = new String(arr); } @Override public void tearDown() throws Exception { FileUtils.deleteDirectory(getTestDirectory()); defaultEncoding = null; textContent = null; } //----------------------------------------------------------------------- public void testSameEncoding() throws Exception { FileWriter fw1 = null; FileWriterWithEncoding fw2 = null; try { fw1 = new FileWriter(file1); // default encoding fw2 = new FileWriterWithEncoding(file2, defaultEncoding); assertTrue(file1.exists()); assertTrue(file2.exists()); fw1.write(textContent); fw2.write(textContent); fw1.flush(); fw2.flush(); checkFile(file1, file2); } finally { IOUtils.closeQuietly(fw1); IOUtils.closeQuietly(fw2); } assertTrue(file1.exists()); assertTrue(file2.exists()); } public void testDifferentEncoding() throws Exception { if (Charset.isSupported("UTF-16BE")) { FileWriter fw1 = null; FileWriterWithEncoding fw2 = null; try { fw1 = new FileWriter(file1); // default encoding fw2 = new FileWriterWithEncoding(file2, defaultEncoding); assertTrue(file1.exists()); assertTrue(file2.exists()); fw1.write(textContent); fw2.write(textContent); fw1.flush(); fw2.flush(); try { checkFile(file1, file2); fail(); } catch (AssertionFailedError ex) { // success } } finally { IOUtils.closeQuietly(fw1); IOUtils.closeQuietly(fw2); } assertTrue(file1.exists()); assertTrue(file2.exists()); } if (Charset.isSupported("UTF-16LE")) { FileWriter fw1 = null; FileWriterWithEncoding fw2 = null; try { fw1 = new FileWriter(file1); // default encoding fw2 = new FileWriterWithEncoding(file2, defaultEncoding); assertTrue(file1.exists()); assertTrue(file2.exists()); fw1.write(textContent); fw2.write(textContent); fw1.flush(); fw2.flush(); try { checkFile(file1, file2); fail(); } catch (AssertionFailedError ex) { // success } } finally { IOUtils.closeQuietly(fw1); IOUtils.closeQuietly(fw2); } assertTrue(file1.exists()); assertTrue(file2.exists()); } } //----------------------------------------------------------------------- public void testConstructor_File_encoding_badEncoding() { Writer writer = null; try { writer = new FileWriterWithEncoding(file1, "BAD-ENCODE"); fail(); } catch (IOException ex) { // expected assertFalse(file1.exists()); } finally { IOUtils.closeQuietly(writer); } assertFalse(file1.exists()); } //----------------------------------------------------------------------- public void testConstructor_File_directory() { Writer writer = null; try { writer = new FileWriterWithEncoding(getTestDirectory(), defaultEncoding); fail(); } catch (IOException ex) { // expected assertFalse(file1.exists()); } finally { IOUtils.closeQuietly(writer); } assertFalse(file1.exists()); } //----------------------------------------------------------------------- public void testConstructor_File_nullFile() throws IOException { Writer writer = null; try { writer = new FileWriterWithEncoding((File) null, defaultEncoding); fail(); } catch (NullPointerException ex) { // expected assertFalse(file1.exists()); } finally { IOUtils.closeQuietly(writer); } assertFalse(file1.exists()); } //----------------------------------------------------------------------- public void testConstructor_fileName_nullFile() throws IOException { Writer writer = null; try { writer = new FileWriterWithEncoding((String) null, defaultEncoding); fail(); } catch (NullPointerException ex) { // expected assertFalse(file1.exists()); } finally { IOUtils.closeQuietly(writer); } assertFalse(file1.exists()); } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/output/StringBuilderWriterTest.java0000644000175000017500000001224012125050425033125 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.output; import java.io.IOException; import java.io.Writer; import junit.framework.TestCase; /** * Test case for {@link StringBuilderWriter}. * * @version $Id: StringBuilderWriterTest.java 1302056 2012-03-18 03:03:38Z ggregory $ */ public class StringBuilderWriterTest extends TestCase { private static final char[] FOOBAR_CHARS = new char[] {'F', 'o', 'o', 'B', 'a', 'r'}; /** * Contruct a new test case. * @param name The name of the test */ public StringBuilderWriterTest(String name) { super(name); } /** Test {@link StringBuilderWriter} constructor. */ public void testAppendConstructCapacity() throws IOException { Writer writer = new StringBuilderWriter(100); writer.append("Foo"); assertEquals("Foo", writer.toString()); } /** Test {@link StringBuilderWriter} constructor. */ public void testAppendConstructStringBuilder() { StringBuilder builder = new StringBuilder("Foo"); StringBuilderWriter writer = new StringBuilderWriter(builder); writer.append("Bar"); assertEquals("FooBar", writer.toString()); assertSame(builder, writer.getBuilder()); } /** Test {@link StringBuilderWriter} constructor. */ public void testAppendConstructNull() throws IOException { Writer writer = new StringBuilderWriter((StringBuilder)null); writer.append("Foo"); assertEquals("Foo", writer.toString()); } /** Test {@link Writer#append(char)}. */ public void testAppendChar() throws IOException { Writer writer = new StringBuilderWriter(); writer.append('F').append('o').append('o'); assertEquals("Foo", writer.toString()); } /** Test {@link Writer#append(CharSequence)}. */ public void testAppendCharSequence() throws IOException { Writer writer = new StringBuilderWriter(); writer.append("Foo").append("Bar"); assertEquals("FooBar", writer.toString()); } /** Test {@link Writer#append(CharSequence, int, int)}. */ public void testAppendCharSequencePortion() throws IOException { Writer writer = new StringBuilderWriter(); writer.append("FooBar", 3, 6).append(new StringBuffer("FooBar"), 0, 3); assertEquals("BarFoo", writer.toString()); } /** Test {@link Writer#close()}. */ public void testClose() { Writer writer = new StringBuilderWriter(); try { writer.append("Foo"); writer.close(); writer.append("Bar"); } catch (Throwable t) { fail("Threw: " + t); } assertEquals("FooBar", writer.toString()); } /** Test {@link Writer#write(int)}. */ public void testWriteChar() throws IOException { Writer writer = new StringBuilderWriter(); writer.write('F'); assertEquals("F", writer.toString()); writer.write('o'); assertEquals("Fo", writer.toString()); writer.write('o'); assertEquals("Foo", writer.toString()); } /** Test {@link Writer#write(char[])}. */ public void testWriteCharArray() throws IOException { Writer writer = new StringBuilderWriter(); writer.write(new char[] {'F', 'o', 'o'}); assertEquals("Foo", writer.toString()); writer.write(new char[] {'B', 'a', 'r'}); assertEquals("FooBar", writer.toString()); } /** Test {@link Writer#write(char[], int, int)}. */ public void testWriteCharArrayPortion() throws IOException { Writer writer = new StringBuilderWriter(); writer.write(FOOBAR_CHARS, 3, 3); assertEquals("Bar", writer.toString()); writer.write(FOOBAR_CHARS, 0, 3); assertEquals("BarFoo", writer.toString()); } /** Test {@link Writer#write(String)}. */ public void testWriteString() throws IOException { Writer writer = new StringBuilderWriter(); writer.write("Foo"); assertEquals("Foo", writer.toString()); writer.write("Bar"); assertEquals("FooBar", writer.toString()); } /** Test {@link Writer#write(String, int, int)}. */ public void testWriteStringPortion() throws IOException { Writer writer = new StringBuilderWriter(); writer.write("FooBar", 3, 3); assertEquals("Bar", writer.toString()); writer.write("FooBar", 0, 3); assertEquals("BarFoo", writer.toString()); } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/output/CountingOutputStreamTest.java0000644000175000017500000000766712125050425033357 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.output; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import junit.framework.TestCase; import org.apache.commons.io.IOUtils; import org.apache.commons.io.input.NullInputStream; /** * @version $Id: CountingOutputStreamTest.java 1302056 2012-03-18 03:03:38Z ggregory $ */ public class CountingOutputStreamTest extends TestCase { public CountingOutputStreamTest(String name) { super(name); } public void testCounting() throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); CountingOutputStream cos = new CountingOutputStream(baos); for(int i = 0; i < 20; i++) { cos.write(i); } assertByteArrayEquals("CountingOutputStream.write(int)", baos.toByteArray(), 0, 20); assertEquals("CountingOutputStream.getCount()", cos.getCount(), 20); byte[] array = new byte[10]; for(int i = 20; i < 30; i++) { array[i-20] = (byte)i; } cos.write(array); assertByteArrayEquals("CountingOutputStream.write(byte[])", baos.toByteArray(), 0, 30); assertEquals("CountingOutputStream.getCount()", cos.getCount(), 30); for(int i = 25; i < 35; i++) { array[i-25] = (byte)i; } cos.write(array, 5, 5); assertByteArrayEquals("CountingOutputStream.write(byte[], int, int)", baos.toByteArray(), 0, 35); assertEquals("CountingOutputStream.getCount()", cos.getCount(), 35); int count = cos.resetCount(); assertEquals("CountingOutputStream.resetCount()", count, 35); for(int i = 0; i < 10; i++) { cos.write(i); } assertByteArrayEquals("CountingOutputStream.write(int)", baos.toByteArray(), 35, 45); assertEquals("CountingOutputStream.getCount()", cos.getCount(), 10); } /** * Test for files > 2GB in size - see issue IO-84 */ public void testLargeFiles_IO84() throws Exception { long size = (long)Integer.MAX_VALUE + (long)1; NullInputStream mock = new NullInputStream(size); OutputStream nos = new NullOutputStream(); CountingOutputStream cos = new CountingOutputStream(nos); // Test integer methods IOUtils.copyLarge(mock, cos); try { cos.getCount(); fail("Expected getCount() to throw an ArithmeticException"); } catch (ArithmeticException ae) { // expected result } try { cos.resetCount(); fail("Expected resetCount() to throw an ArithmeticException"); } catch (ArithmeticException ae) { // expected result } mock.close(); // Test long methods IOUtils.copyLarge(mock, cos); assertEquals("getByteCount()", size, cos.getByteCount()); assertEquals("resetByteCount()", size, cos.resetByteCount()); } private void assertByteArrayEquals(String msg, byte[] array, int start, int end) { for (int i = start; i < end; i++) { assertEquals(msg+": array[" + i + "] mismatch", array[i], i-start); } } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/output/CloseShieldOutputStreamTest.javalibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/output/CloseShieldOutputStreamTest.j0000644000175000017500000000357612125050425033272 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.output; import java.io.IOException; import java.io.OutputStream; import junit.framework.TestCase; /** * JUnit Test Case for {@link CloseShieldOutputStream}. */ public class CloseShieldOutputStreamTest extends TestCase { private ByteArrayOutputStream original; private OutputStream shielded; private boolean closed; @Override protected void setUp() { original = new ByteArrayOutputStream() { @Override public void close() { closed = true; } }; shielded = new CloseShieldOutputStream(original); closed = false; } /** * Test the close() method. */ public void testClose() throws IOException { shielded.close(); assertFalse("closed", closed); try { shielded.write('x'); fail("write(b)"); } catch (IOException e) { // expected } original.write('y'); assertEquals(1, original.size()); assertEquals('y', original.toByteArray()[0]); } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/output/NullOutputStreamTest.java0000644000175000017500000000304312125050425032463 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.output; import java.io.IOException; import junit.framework.TestCase; /** * Really not a lot to do here, but checking that no * Exceptions are thrown. * * @version $Id: NullOutputStreamTest.java 1302056 2012-03-18 03:03:38Z ggregory $ */ public class NullOutputStreamTest extends TestCase { public NullOutputStreamTest(String name) { super(name); } public void testNull() throws IOException { NullOutputStream nos = new NullOutputStream(); nos.write("string".getBytes()); nos.write("some string".getBytes(), 3, 5); nos.write(1); nos.write(0x0f); nos.flush(); nos.close(); nos.write("allowed".getBytes()); nos.write(255); } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/output/TeeOutputStreamTest.java0000644000175000017500000001030312125050425032263 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.output; import java.io.ByteArrayOutputStream; import java.io.IOException; import junit.framework.TestCase; import org.junit.Assert; /** * @version $Id: TeeOutputStreamTest.java 1302056 2012-03-18 03:03:38Z ggregory $ */ public class TeeOutputStreamTest extends TestCase { private static class ExceptionOnCloseByteArrayOutputStream extends ByteArrayOutputStream { @Override public void close() throws IOException { throw new IOException(); } } private static class RecordCloseByteArrayOutputStream extends ByteArrayOutputStream { boolean closed; @Override public void close() throws IOException { super.close(); closed = true; } } public TeeOutputStreamTest(String name) { super(name); } /** * Tests that the branch {@code OutputStream} is closed when closing the main {@code OutputStream} throws an * exception on {@link TeeOutputStream#close()}. */ public void testCloseBranchIOException() { ByteArrayOutputStream badOs = new ExceptionOnCloseByteArrayOutputStream(); RecordCloseByteArrayOutputStream goodOs = new RecordCloseByteArrayOutputStream(); TeeOutputStream tos = new TeeOutputStream(goodOs, badOs); try { tos.close(); Assert.fail("Expected " + IOException.class.getName()); } catch (IOException e) { Assert.assertTrue(goodOs.closed); } } /** * Tests that the main {@code OutputStream} is closed when closing the branch {@code OutputStream} throws an * exception on {@link TeeOutputStream#close()}. */ public void testCloseMainIOException() { ByteArrayOutputStream badOs = new ExceptionOnCloseByteArrayOutputStream(); RecordCloseByteArrayOutputStream goodOs = new RecordCloseByteArrayOutputStream(); TeeOutputStream tos = new TeeOutputStream(badOs, goodOs); try { tos.close(); Assert.fail("Expected " + IOException.class.getName()); } catch (IOException e) { Assert.assertTrue(goodOs.closed); } } public void testTee() throws IOException { ByteArrayOutputStream baos1 = new ByteArrayOutputStream(); ByteArrayOutputStream baos2 = new ByteArrayOutputStream(); TeeOutputStream tos = new TeeOutputStream(baos1, baos2); for (int i = 0; i < 20; i++) { tos.write(i); } assertByteArrayEquals("TeeOutputStream.write(int)", baos1.toByteArray(), baos2.toByteArray()); byte[] array = new byte[10]; for (int i = 20; i < 30; i++) { array[i - 20] = (byte) i; } tos.write(array); assertByteArrayEquals("TeeOutputStream.write(byte[])", baos1.toByteArray(), baos2.toByteArray()); for (int i = 25; i < 35; i++) { array[i - 25] = (byte) i; } tos.write(array, 5, 5); assertByteArrayEquals("TeeOutputStream.write(byte[], int, int)", baos1.toByteArray(), baos2.toByteArray()); tos.flush(); tos.close(); } private void assertByteArrayEquals(String msg, byte[] array1, byte[] array2) { assertEquals(msg + ": array size mismatch", array1.length, array2.length); for (int i = 0; i < array1.length; i++) { assertEquals(msg + ": array[ " + i + "] mismatch", array1[i], array2[i]); } } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/output/TaggedOutputStreamTest.java0000644000175000017500000001000412125050425032737 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.output; import java.io.IOException; import java.io.OutputStream; import java.util.UUID; import junit.framework.TestCase; import org.apache.commons.io.TaggedIOException; /** * JUnit Test Case for {@link TaggedOutputStream}. */ public class TaggedOutputStreamTest extends TestCase { public void testNormalStream() { try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); OutputStream stream = new TaggedOutputStream(buffer); stream.write('a'); stream.write(new byte[] { 'b' }); stream.write(new byte[] { 'c' }, 0, 1); stream.flush(); stream.close(); assertEquals(3, buffer.size()); assertEquals('a', buffer.toByteArray()[0]); assertEquals('b', buffer.toByteArray()[1]); assertEquals('c', buffer.toByteArray()[2]); } catch (IOException e) { fail("Unexpected exception thrown"); } } public void testBrokenStream() { IOException exception = new IOException("test exception"); TaggedOutputStream stream = new TaggedOutputStream(new BrokenOutputStream(exception)); // Test the write() method try { stream.write('x'); fail("Expected exception not thrown."); } catch (IOException e) { assertTrue(stream.isCauseOf(e)); try { stream.throwIfCauseOf(e); fail("Expected exception not thrown."); } catch (IOException e2) { assertEquals(exception, e2); } } // Test the flush() method try { stream.flush(); fail("Expected exception not thrown."); } catch (IOException e) { assertTrue(stream.isCauseOf(e)); try { stream.throwIfCauseOf(e); fail("Expected exception not thrown."); } catch (IOException e2) { assertEquals(exception, e2); } } // Test the close() method try { stream.close(); fail("Expected exception not thrown."); } catch (IOException e) { assertTrue(stream.isCauseOf(e)); try { stream.throwIfCauseOf(e); fail("Expected exception not thrown."); } catch (IOException e2) { assertEquals(exception, e2); } } } public void testOtherException() { IOException exception = new IOException("test exception"); OutputStream closed = new ClosedOutputStream(); TaggedOutputStream stream = new TaggedOutputStream(closed); assertFalse(stream.isCauseOf(exception)); assertFalse(stream.isCauseOf( new TaggedIOException(exception, UUID.randomUUID()))); try { stream.throwIfCauseOf(exception); } catch (IOException e) { fail("Unexpected exception thrown"); } try { stream.throwIfCauseOf( new TaggedIOException(exception, UUID.randomUUID())); } catch (IOException e) { fail("Unexpected exception thrown"); } } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/output/ByteArrayOutputStreamTestCase.javalibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/output/ByteArrayOutputStreamTestCase0000644000175000017500000001203012125050425033323 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.output; import java.io.ByteArrayInputStream; import junit.framework.TestCase; /** * Basic unit tests for the alternative ByteArrayOutputStream implementation. */ public class ByteArrayOutputStreamTestCase extends TestCase { private static final byte[] DATA; static { DATA = new byte[64]; for (byte i = 0; i < 64; i++) { DATA[i] = i; } } public ByteArrayOutputStreamTestCase(String name) { super(name); } private int writeData(ByteArrayOutputStream baout, java.io.ByteArrayOutputStream ref, int count) { if (count > DATA.length) { throw new IllegalArgumentException("Requesting too many bytes"); } if (count == 0) { baout.write(100); ref.write(100); return 1; } else { baout.write(DATA, 0, count); ref.write(DATA, 0, count); return count; } } private int writeData(ByteArrayOutputStream baout, java.io.ByteArrayOutputStream ref, int[] instructions) { int written = 0; for (int instruction : instructions) { written += writeData(baout, ref, instruction); } return written; } private static boolean byteCmp(byte[] src, byte[] cmp) { for (int i = 0; i < cmp.length; i++) { if (src[i] != cmp[i]) { return false; } } return true; } private void checkByteArrays(byte[] expected, byte[] actual) { if (expected.length != actual.length) { fail("Resulting byte arrays are not equally long"); } if (!byteCmp(expected, actual)) { fail("Resulting byte arrays are not equal"); } } private void checkStreams( ByteArrayOutputStream actual, java.io.ByteArrayOutputStream expected) { assertEquals("Sizes are not equal", expected.size(), actual.size()); byte[] buf = actual.toByteArray(); byte[] refbuf = expected.toByteArray(); checkByteArrays(buf, refbuf); } public void testStream() throws Exception { int written; //The ByteArrayOutputStream is initialized with 32 bytes to match //the original more closely for this test. ByteArrayOutputStream baout = new ByteArrayOutputStream(32); java.io.ByteArrayOutputStream ref = new java.io.ByteArrayOutputStream(); //First three writes written = writeData(baout, ref, new int[] {4, 10, 22}); assertEquals(36, written); checkStreams(baout, ref); //Another two writes to see if there are any bad effects after toByteArray() written = writeData(baout, ref, new int[] {20, 12}); assertEquals(32, written); checkStreams(baout, ref); //Now reset the streams baout.reset(); ref.reset(); //Test again to see if reset() had any bad effects written = writeData(baout, ref, new int[] {5, 47, 33, 60, 1, 0, 8}); assertEquals(155, written); checkStreams(baout, ref); //Test the readFrom(InputStream) method baout.reset(); written = baout.write(new ByteArrayInputStream(ref.toByteArray())); assertEquals(155, written); checkStreams(baout, ref); //Write the commons Byte[]OutputStream to a java.io.Byte[]OutputStream //and vice-versa to test the writeTo() method. ByteArrayOutputStream baout1 = new ByteArrayOutputStream(32); ref.writeTo(baout1); java.io.ByteArrayOutputStream ref1 = new java.io.ByteArrayOutputStream(); baout.writeTo(ref1); checkStreams(baout1, ref1); //Testing toString(String) String baoutString = baout.toString("ASCII"); String refString = ref.toString("ASCII"); assertEquals("ASCII decoded String must be equal", refString, baoutString); //Make sure that empty ByteArrayOutputStreams really don't create garbage //on toByteArray() assertSame(new ByteArrayOutputStream().toByteArray(), new ByteArrayOutputStream().toByteArray()); } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/output/BrokenOutputStreamTest.java0000644000175000017500000000441012125050425032770 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.output; import java.io.IOException; import java.io.OutputStream; import junit.framework.TestCase; /** * JUnit Test Case for {@link BrokenOutputStream}. */ public class BrokenOutputStreamTest extends TestCase { private IOException exception; private OutputStream stream; @Override protected void setUp() { exception = new IOException("test exception"); stream = new BrokenOutputStream(exception); } public void testWrite() { try { stream.write(1); fail("Expected exception not thrown."); } catch (IOException e) { assertEquals(exception, e); } try { stream.write(new byte[1]); fail("Expected exception not thrown."); } catch (IOException e) { assertEquals(exception, e); } try { stream.write(new byte[1], 0, 1); fail("Expected exception not thrown."); } catch (IOException e) { assertEquals(exception, e); } } public void testFlush() { try { stream.flush(); fail("Expected exception not thrown."); } catch (IOException e) { assertEquals(exception, e); } } public void testClose() { try { stream.close(); fail("Expected exception not thrown."); } catch (IOException e) { assertEquals(exception, e); } } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/output/LockableFileWriterTest.java0000644000175000017500000002003712125050425032667 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.output; import java.io.File; import java.io.IOException; import java.io.Writer; import java.nio.charset.UnsupportedCharsetException; import org.apache.commons.io.IOUtils; import org.apache.commons.io.testtools.FileBasedTestCase; /** * Tests that files really lock, although no writing is done as * the locking is tested only on construction. * * @version $Id: LockableFileWriterTest.java 1307431 2012-03-30 14:10:33Z ggregory $ */ public class LockableFileWriterTest extends FileBasedTestCase { private File file; private File lockDir; private File lockFile; private File altLockDir; private File altLockFile; public LockableFileWriterTest(String name) { super(name); } @Override public void setUp() { file = new File(getTestDirectory(), "testlockfile"); lockDir = new File(System.getProperty("java.io.tmpdir")); lockFile = new File(lockDir, file.getName() + ".lck"); altLockDir = getTestDirectory(); altLockFile = new File(altLockDir, file.getName() + ".lck"); } @Override public void tearDown() { file.delete(); lockFile.delete(); altLockFile.delete(); } //----------------------------------------------------------------------- public void testFileLocked() throws IOException { LockableFileWriter lfw1 = null; LockableFileWriter lfw2 = null; LockableFileWriter lfw3 = null; try { // open a valid locakable writer lfw1 = new LockableFileWriter(file); assertTrue(file.exists()); assertTrue(lockFile.exists()); // try to open a second writer try { lfw2 = new LockableFileWriter(file); fail("Somehow able to open a locked file. "); } catch(IOException ioe) { String msg = ioe.getMessage(); assertTrue( "Exception message does not start correctly. ", msg.startsWith("Can't write file, lock ") ); assertTrue(file.exists()); assertTrue(lockFile.exists()); } // try to open a third writer try { lfw3 = new LockableFileWriter(file); fail("Somehow able to open a locked file. "); } catch(IOException ioe) { String msg = ioe.getMessage(); assertTrue( "Exception message does not start correctly. ", msg.startsWith("Can't write file, lock ") ); assertTrue(file.exists()); assertTrue(lockFile.exists()); } } finally { IOUtils.closeQuietly(lfw1); IOUtils.closeQuietly(lfw2); IOUtils.closeQuietly(lfw3); } assertTrue(file.exists()); assertFalse(lockFile.exists()); } //----------------------------------------------------------------------- public void testAlternateLockDir() throws IOException { LockableFileWriter lfw1 = null; LockableFileWriter lfw2 = null; try { // open a valid locakable writer lfw1 = new LockableFileWriter(file, true, altLockDir.getAbsolutePath()); assertTrue(file.exists()); assertTrue(altLockFile.exists()); // try to open a second writer try { lfw2 = new LockableFileWriter(file, true, altLockDir.getAbsolutePath()); fail("Somehow able to open a locked file. "); } catch(IOException ioe) { String msg = ioe.getMessage(); assertTrue( "Exception message does not start correctly. ", msg.startsWith("Can't write file, lock ") ); assertTrue(file.exists()); assertTrue(altLockFile.exists()); } } finally { IOUtils.closeQuietly(lfw1); IOUtils.closeQuietly(lfw2); } assertTrue(file.exists()); assertFalse(altLockFile.exists()); } //----------------------------------------------------------------------- public void testFileNotLocked() throws IOException { // open a valid locakable writer LockableFileWriter lfw1 = null; try { lfw1 = new LockableFileWriter(file); assertTrue(file.exists()); assertTrue(lockFile.exists()); } finally { IOUtils.closeQuietly(lfw1); } assertTrue(file.exists()); assertFalse(lockFile.exists()); // open a second valid writer on the same file LockableFileWriter lfw2 = null; try { lfw2 = new LockableFileWriter(file); assertTrue(file.exists()); assertTrue(lockFile.exists()); } finally { IOUtils.closeQuietly(lfw2); } assertTrue(file.exists()); assertFalse(lockFile.exists()); } //----------------------------------------------------------------------- public void testConstructor_File_encoding_badEncoding() throws IOException { Writer writer = null; try { writer = new LockableFileWriter(file, "BAD-ENCODE"); fail(); } catch (UnsupportedCharsetException ex) { // expected assertFalse(file.exists()); assertFalse(lockFile.exists()); } finally { IOUtils.closeQuietly(writer); } assertFalse(file.exists()); assertFalse(lockFile.exists()); } //----------------------------------------------------------------------- public void testConstructor_File_directory() { Writer writer = null; try { writer = new LockableFileWriter(getTestDirectory()); fail(); } catch (IOException ex) { // expected assertFalse(file.exists()); assertFalse(lockFile.exists()); } finally { IOUtils.closeQuietly(writer); } assertFalse(file.exists()); assertFalse(lockFile.exists()); } //----------------------------------------------------------------------- public void testConstructor_File_nullFile() throws IOException { Writer writer = null; try { writer = new LockableFileWriter((File) null); fail(); } catch (NullPointerException ex) { // expected assertFalse(file.exists()); assertFalse(lockFile.exists()); } finally { IOUtils.closeQuietly(writer); } assertFalse(file.exists()); assertFalse(lockFile.exists()); } //----------------------------------------------------------------------- public void testConstructor_fileName_nullFile() throws IOException { Writer writer = null; try { writer = new LockableFileWriter((String) null); fail(); } catch (NullPointerException ex) { // expected assertFalse(file.exists()); assertFalse(lockFile.exists()); } finally { IOUtils.closeQuietly(writer); } assertFalse(file.exists()); assertFalse(lockFile.exists()); } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/output/WriterOutputStreamTest.java0000644000175000017500000001062112125050425033025 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.output; import java.io.IOException; import java.io.StringWriter; import java.util.Random; import junit.framework.TestCase; public class WriterOutputStreamTest extends TestCase { private static final String TEST_STRING = "\u00e0 peine arriv\u00e9s nous entr\u00e2mes dans sa chambre"; private static final String LARGE_TEST_STRING; static { StringBuilder buffer = new StringBuilder(); for (int i=0; i<100; i++) { buffer.append(TEST_STRING); } LARGE_TEST_STRING = buffer.toString(); } private Random random = new Random(); private void testWithSingleByteWrite(String testString, String charsetName) throws IOException { byte[] bytes = testString.getBytes(charsetName); StringWriter writer = new StringWriter(); WriterOutputStream out = new WriterOutputStream(writer, charsetName); for (byte b : bytes) { out.write(b); } out.close(); assertEquals(testString, writer.toString()); } private void testWithBufferedWrite(String testString, String charsetName) throws IOException { byte[] expected = testString.getBytes(charsetName); StringWriter writer = new StringWriter(); WriterOutputStream out = new WriterOutputStream(writer, charsetName); int offset = 0; while (offset < expected.length) { int length = Math.min(random.nextInt(128), expected.length-offset); out.write(expected, offset, length); offset += length; } out.close(); assertEquals(testString, writer.toString()); } public void testUTF8WithSingleByteWrite() throws IOException { testWithSingleByteWrite(TEST_STRING, "UTF-8"); } public void testLargeUTF8WithSingleByteWrite() throws IOException { testWithSingleByteWrite(LARGE_TEST_STRING, "UTF-8"); } public void testUTF8WithBufferedWrite() throws IOException { testWithBufferedWrite(TEST_STRING, "UTF-8"); } public void testLargeUTF8WithBufferedWrite() throws IOException { testWithBufferedWrite(LARGE_TEST_STRING, "UTF-8"); } public void testUTF16WithSingleByteWrite() throws IOException { testWithSingleByteWrite(TEST_STRING, "UTF-16"); } public void testUTF16WithBufferedWrite() throws IOException { testWithBufferedWrite(TEST_STRING, "UTF-16"); } public void testUTF16BEWithSingleByteWrite() throws IOException { testWithSingleByteWrite(TEST_STRING, "UTF-16BE"); } public void testUTF16BEWithBufferedWrite() throws IOException { testWithBufferedWrite(TEST_STRING, "UTF-16BE"); } public void testUTF16LEWithSingleByteWrite() throws IOException { testWithSingleByteWrite(TEST_STRING, "UTF-16LE"); } public void testUTF16LEWithBufferedWrite() throws IOException { testWithBufferedWrite(TEST_STRING, "UTF-16LE"); } public void testFlush() throws IOException { StringWriter writer = new StringWriter(); WriterOutputStream out = new WriterOutputStream(writer, "us-ascii", 1024, false); out.write("abc".getBytes("us-ascii")); assertEquals(0, writer.getBuffer().length()); out.flush(); assertEquals("abc", writer.toString()); } public void testWriteImmediately() throws IOException { StringWriter writer = new StringWriter(); WriterOutputStream out = new WriterOutputStream(writer, "us-ascii", 1024, true); out.write("abc".getBytes("us-ascii")); assertEquals("abc", writer.toString()); } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/output/ProxyWriterTest.java0000644000175000017500000001041612125050425031474 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.output; import junit.framework.TestCase; /** * Test {@link ProxyWriter}. * * @version $Id: ProxyWriterTest.java 1302056 2012-03-18 03:03:38Z ggregory $ */ public class ProxyWriterTest extends TestCase { public ProxyWriterTest(String name) { super(name); } /** Test Appending a CharSequence */ public void testAppendCharSequence() { StringBuilderWriter writer = new StringBuilderWriter(); ProxyWriter proxy = new ProxyWriter(writer); try { proxy.append("ABC"); } catch(Exception e) { fail("Appending CharSequence threw " + e); } assertEquals("ABC", writer.toString()); } /** Test Writing a String */ public void testWriteString() { StringBuilderWriter writer = new StringBuilderWriter(); ProxyWriter proxy = new ProxyWriter(writer); try { proxy.write("ABC"); } catch(Exception e) { fail("Writing String threw " + e); } assertEquals("ABC", writer.toString()); } /** Test Writing a Partial String */ public void testWriteStringPartial() { StringBuilderWriter writer = new StringBuilderWriter(); ProxyWriter proxy = new ProxyWriter(writer); try { proxy.write("ABC", 1, 2); } catch(Exception e) { fail("Writing String threw " + e); } assertEquals("BC", writer.toString()); } /** Test Writing a Char array */ public void testWriteCharArray() { StringBuilderWriter writer = new StringBuilderWriter(); ProxyWriter proxy = new ProxyWriter(writer); try { proxy.write(new char[] {'A', 'B', 'C'}); } catch(Exception e) { fail("Writing char[] threw " + e); } assertEquals("ABC", writer.toString()); } /** Test Writing a Partial Char array */ public void testWriteCharArrayPartial() { StringBuilderWriter writer = new StringBuilderWriter(); ProxyWriter proxy = new ProxyWriter(writer); try { proxy.write(new char[] {'A', 'B', 'C'}, 1, 2); } catch(Exception e) { fail("Writing char[] threw " + e); } assertEquals("BC", writer.toString()); } /** Test writing Null String */ public void testNullString() { ProxyWriter proxy = new ProxyWriter(new NullWriter()); try { proxy.write((String)null); } catch(Exception e) { fail("Writing null String threw " + e); } try { proxy.write((String)null, 0, 0); } catch(Exception e) { fail("Writing null String threw " + e); } } /** Test writing Null Char array */ public void testNullCharArray() { ProxyWriter proxy = new ProxyWriter(new NullWriter()); try { proxy.write((char[])null); } catch(Exception e) { fail("Writing null char[] threw " + e); } try { proxy.write((char[])null, 0, 0); } catch(Exception e) { fail("Writing null char[] threw " + e); } } /** Test appending Null CharSequence */ public void testNullCharSequencec() { ProxyWriter proxy = new ProxyWriter(new NullWriter()); try { proxy.append((String)null); } catch(Exception e) { fail("Appending null CharSequence threw " + e); } } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/output/XmlStreamWriterTest.java0000644000175000017500000001147412125050425032274 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.output; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Arrays; import junit.framework.TestCase; /** * @version $Id: XmlStreamWriterTest.java 1302748 2012-03-20 01:35:32Z ggregory $ */ public class XmlStreamWriterTest extends TestCase { /** french */ private static final String TEXT_LATIN1 = "eacute: \u00E9"; /** greek */ private static final String TEXT_LATIN7 = "alpha: \u03B1"; /** euro support */ private static final String TEXT_LATIN15 = "euro: \u20AC"; /** japanese */ private static final String TEXT_EUC_JP = "hiragana A: \u3042"; /** Unicode: support everything */ private static final String TEXT_UNICODE = TEXT_LATIN1 + ", " + TEXT_LATIN7 + ", " + TEXT_LATIN15 + ", " + TEXT_EUC_JP; private static String createXmlContent(String text, String encoding) { String xmlDecl = ""; if (encoding != null) { xmlDecl = ""; } String xml = xmlDecl + "\n" + text + ""; return xml; } private static void checkXmlContent(String xml, String encoding, String defaultEncoding) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); XmlStreamWriter writer = new XmlStreamWriter(out, defaultEncoding); writer.write(xml); writer.close(); byte[] xmlContent = out.toByteArray(); assertEquals(encoding, writer.getEncoding()); assertTrue(Arrays.equals(xml.getBytes(encoding), xmlContent)); } private static void checkXmlWriter(String text, String encoding) throws IOException { checkXmlWriter(text, encoding, null); } private static void checkXmlWriter(String text, String encoding, String defaultEncoding) throws IOException { String xml = createXmlContent(text, encoding); String effectiveEncoding = encoding; if (effectiveEncoding == null) { effectiveEncoding = defaultEncoding == null ? "UTF-8" : defaultEncoding; } checkXmlContent(xml, effectiveEncoding, defaultEncoding); } public void testNoXmlHeader() throws IOException { String xml = "text with no XML header"; checkXmlContent(xml, "UTF-8", null); } public void testEmpty() throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); XmlStreamWriter writer = new XmlStreamWriter(out); writer.flush(); writer.write(""); writer.flush(); writer.write("."); writer.flush(); writer.close(); } public void testDefaultEncoding() throws IOException { checkXmlWriter(TEXT_UNICODE, null, null); checkXmlWriter(TEXT_UNICODE, null, "UTF-8"); checkXmlWriter(TEXT_UNICODE, null, "UTF-16"); checkXmlWriter(TEXT_UNICODE, null, "UTF-16BE"); checkXmlWriter(TEXT_UNICODE, null, "ISO-8859-1"); } public void testUTF8Encoding() throws IOException { checkXmlWriter(TEXT_UNICODE, "UTF-8"); } public void testUTF16Encoding() throws IOException { checkXmlWriter(TEXT_UNICODE, "UTF-16"); } public void testUTF16BEEncoding() throws IOException { checkXmlWriter(TEXT_UNICODE, "UTF-16BE"); } public void testUTF16LEEncoding() throws IOException { checkXmlWriter(TEXT_UNICODE, "UTF-16LE"); } public void testLatin1Encoding() throws IOException { checkXmlWriter(TEXT_LATIN1, "ISO-8859-1"); } public void testLatin7Encoding() throws IOException { checkXmlWriter(TEXT_LATIN7, "ISO-8859-7"); } public void testLatin15Encoding() throws IOException { checkXmlWriter(TEXT_LATIN15, "ISO-8859-15"); } public void testEUC_JPEncoding() throws IOException { checkXmlWriter(TEXT_EUC_JP, "EUC-JP"); } public void testEBCDICEncoding() throws IOException { checkXmlWriter("simple text in EBCDIC", "CP1047"); } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/output/ClosedOutputStreamTest.java0000644000175000017500000000240312125050425032761 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.output; import java.io.IOException; import junit.framework.TestCase; /** * JUnit Test Case for {@link ClosedOutputStream}. */ public class ClosedOutputStreamTest extends TestCase { /** * Test the write(b) method. */ public void testRead() { try { new ClosedOutputStream().write('x'); fail("write(b)"); } catch (IOException e) { // expected } } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/output/DeferredFileOutputStreamTest.javalibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/output/DeferredFileOutputStreamTest.0000644000175000017500000002752412125050425033241 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.output; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Arrays; import junit.framework.TestCase; /** * Unit tests for the DeferredFileOutputStream class. * * @version $Id: DeferredFileOutputStreamTest.java 1302056 2012-03-18 03:03:38Z ggregory $ */ public class DeferredFileOutputStreamTest extends TestCase { /** * The test data as a string (which is the simplest form). */ private String testString = "0123456789"; /** * The test data as a byte array, derived from the string. */ private byte[] testBytes = testString.getBytes(); /** * Standard JUnit test case constructor. * * @param name The name of the test case. */ public DeferredFileOutputStreamTest(String name) { super(name); } /** * Tests the case where the amount of data falls below the threshold, and * is therefore confined to memory. */ public void testBelowThreshold() { DeferredFileOutputStream dfos = new DeferredFileOutputStream(testBytes.length + 42, null); try { dfos.write(testBytes, 0, testBytes.length); dfos.close(); } catch (IOException e) { fail("Unexpected IOException"); } assertTrue(dfos.isInMemory()); byte[] resultBytes = dfos.getData(); assertEquals(testBytes.length, resultBytes.length); assertTrue(Arrays.equals(resultBytes, testBytes)); } /** * Tests the case where the amount of data is exactly the same as the * threshold. The behavior should be the same as that for the amount of * data being below (i.e. not exceeding) the threshold. */ public void testAtThreshold() { DeferredFileOutputStream dfos = new DeferredFileOutputStream(testBytes.length, null); try { dfos.write(testBytes, 0, testBytes.length); dfos.close(); } catch (IOException e) { fail("Unexpected IOException"); } assertTrue(dfos.isInMemory()); byte[] resultBytes = dfos.getData(); assertEquals(testBytes.length, resultBytes.length); assertTrue(Arrays.equals(resultBytes, testBytes)); } /** * Tests the case where the amount of data exceeds the threshold, and is * therefore written to disk. The actual data written to disk is verified, * as is the file itself. */ public void testAboveThreshold() { File testFile = new File("testAboveThreshold.dat"); // Ensure that the test starts from a clean base. testFile.delete(); DeferredFileOutputStream dfos = new DeferredFileOutputStream(testBytes.length - 5, testFile); try { dfos.write(testBytes, 0, testBytes.length); dfos.close(); } catch (IOException e) { fail("Unexpected IOException"); } assertFalse(dfos.isInMemory()); assertNull(dfos.getData()); verifyResultFile(testFile); // Ensure that the test starts from a clean base. testFile.delete(); } /** * Tests the case where there are multiple writes beyond the threshold, to * ensure that the thresholdReached() method is only called * once, as the threshold is crossed for the first time. */ public void testThresholdReached() { File testFile = new File("testThresholdReached.dat"); // Ensure that the test starts from a clean base. testFile.delete(); DeferredFileOutputStream dfos = new DeferredFileOutputStream(testBytes.length / 2, testFile); int chunkSize = testBytes.length / 3; try { dfos.write(testBytes, 0, chunkSize); dfos.write(testBytes, chunkSize, chunkSize); dfos.write(testBytes, chunkSize * 2, testBytes.length - chunkSize * 2); dfos.close(); } catch (IOException e) { fail("Unexpected IOException"); } assertFalse(dfos.isInMemory()); assertNull(dfos.getData()); verifyResultFile(testFile); // Ensure that the test starts from a clean base. testFile.delete(); } /** * Test wether writeTo() properly writes small content. */ public void testWriteToSmall(){ File testFile = new File("testWriteToMem.dat"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // Ensure that the test starts from a clean base. testFile.delete(); DeferredFileOutputStream dfos = new DeferredFileOutputStream(testBytes.length *2, testFile); try{ dfos.write(testBytes); assertFalse(testFile.exists()); assertTrue(dfos.isInMemory()); try { dfos.writeTo(baos); fail("Should not have been able to write before closing"); } catch (IOException ioe) { // ok, as expected } dfos.close(); dfos.writeTo(baos); } catch (IOException ioe) { fail("Unexpected IOException"); } byte[] copiedBytes = baos.toByteArray(); assertTrue(Arrays.equals(testBytes, copiedBytes)); testFile.delete(); } /** * Test wether writeTo() properly writes large content. */ public void testWriteToLarge(){ File testFile = new File("testWriteToFile.dat"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // Ensure that the test starts from a clean base. testFile.delete(); DeferredFileOutputStream dfos = new DeferredFileOutputStream(testBytes.length / 2, testFile); try{ dfos.write(testBytes); assertTrue(testFile.exists()); assertFalse(dfos.isInMemory()); try { dfos.writeTo(baos); fail("Should not have been able to write before closeing"); } catch (IOException ioe) { // ok, as expected } dfos.close(); dfos.writeTo(baos); } catch (IOException ioe) { fail("Unexpected IOException"); } byte[] copiedBytes = baos.toByteArray(); assertTrue(Arrays.equals(testBytes, copiedBytes)); verifyResultFile(testFile); testFile.delete(); } /** * Test specifying a temporary file and the threshold not reached. */ public void testTempFileBelowThreshold() { String prefix = "commons-io-test"; String suffix = ".out"; File tempDir = new File("."); DeferredFileOutputStream dfos = new DeferredFileOutputStream(testBytes.length + 42, prefix, suffix, tempDir); assertNull("Check file is null-A", dfos.getFile()); try { dfos.write(testBytes, 0, testBytes.length); dfos.close(); } catch (IOException e) { fail("Unexpected IOException"); } assertTrue(dfos.isInMemory()); assertNull("Check file is null-B", dfos.getFile()); } /** * Test specifying a temporary file and the threshold is reached. */ public void testTempFileAboveThreshold() { String prefix = "commons-io-test"; String suffix = ".out"; File tempDir = new File("."); DeferredFileOutputStream dfos = new DeferredFileOutputStream(testBytes.length - 5, prefix, suffix, tempDir); assertNull("Check file is null-A", dfos.getFile()); try { dfos.write(testBytes, 0, testBytes.length); dfos.close(); } catch (IOException e) { fail("Unexpected IOException"); } assertFalse(dfos.isInMemory()); assertNull(dfos.getData()); assertNotNull("Check file not null", dfos.getFile()); assertTrue("Check file exists", dfos.getFile().exists()); assertTrue("Check prefix", dfos.getFile().getName().startsWith(prefix)); assertTrue("Check suffix", dfos.getFile().getName().endsWith(suffix)); assertEquals("Check dir", tempDir.getPath(), dfos.getFile().getParent()); verifyResultFile(dfos.getFile()); // Delete the temporary file. dfos.getFile().delete(); } /** * Test specifying a temporary file and the threshold is reached. */ public void testTempFileAboveThresholdPrefixOnly() { String prefix = "commons-io-test"; String suffix = null; File tempDir = null; DeferredFileOutputStream dfos = new DeferredFileOutputStream(testBytes.length - 5, prefix, suffix, tempDir); assertNull("Check file is null-A", dfos.getFile()); try { dfos.write(testBytes, 0, testBytes.length); dfos.close(); } catch (IOException e) { fail("Unexpected IOException"); } assertFalse(dfos.isInMemory()); assertNull(dfos.getData()); assertNotNull("Check file not null", dfos.getFile()); assertTrue("Check file exists", dfos.getFile().exists()); assertTrue("Check prefix", dfos.getFile().getName().startsWith(prefix)); assertTrue("Check suffix", dfos.getFile().getName().endsWith(".tmp")); // ".tmp" is default verifyResultFile(dfos.getFile()); // Delete the temporary file. dfos.getFile().delete(); } /** * Test specifying a temporary file and the threshold is reached. */ public void testTempFileError() { String prefix = null; String suffix = ".out"; File tempDir = new File("."); try { new DeferredFileOutputStream(testBytes.length - 5, prefix, suffix, tempDir); fail("Expected IllegalArgumentException "); } catch (IllegalArgumentException e) { // expected } } /** * Verifies that the specified file contains the same data as the original * test data. * * @param testFile The file containing the test output. */ private void verifyResultFile(File testFile) { try { FileInputStream fis = new FileInputStream(testFile); assertEquals(testBytes.length, fis.available()); byte[] resultBytes = new byte[testBytes.length]; assertEquals(testBytes.length, fis.read(resultBytes)); assertTrue(Arrays.equals(resultBytes, testBytes)); assertEquals(-1, fis.read(resultBytes)); try { fis.close(); } catch (IOException e) { // Ignore an exception on close } } catch (FileNotFoundException e) { fail("Unexpected FileNotFoundException"); } catch (IOException e) { fail("Unexpected IOException"); } } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/output/NullWriterTest.java0000644000175000017500000000275412125050425031273 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.output; import junit.framework.TestCase; /** * Really not a lot to do here, but checking that no * Exceptions are thrown. * * @version $Id: NullWriterTest.java 1302056 2012-03-18 03:03:38Z ggregory $ */ public class NullWriterTest extends TestCase { public NullWriterTest(String name) { super(name); } public void testNull() { char[] chars = new char[] {'A', 'B', 'C'}; NullWriter writer = new NullWriter(); writer.write(1); writer.write(chars); writer.write(chars, 1, 1); writer.write("some string"); writer.write("some string", 2, 2); writer.flush(); writer.close(); } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/output/ProxyOutputStreamTest.java0000644000175000017500000000342112125050425032672 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.output; import java.io.IOException; import java.io.OutputStream; import junit.framework.TestCase; /** * JUnit Test Case for {@link CloseShieldOutputStream}. */ public class ProxyOutputStreamTest extends TestCase { private ByteArrayOutputStream original; private OutputStream proxied; @Override protected void setUp() { original = new ByteArrayOutputStream(){ @Override public void write(byte[] ba) throws IOException { if (ba != null){ super.write(ba); } } }; proxied = new ProxyOutputStream(original); } public void testWrite() throws Exception { proxied.write('y'); assertEquals(1, original.size()); assertEquals('y', original.toByteArray()[0]); } public void testWriteNullBaSucceeds() throws Exception { byte[] ba = null; original.write(ba); proxied.write(ba); } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/testtools/0000755000175000017500000000000012125050425026151 5ustar ebourgebourglibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/testtools/FileBasedTestCase.java0000644000175000017500000001763012125050425032275 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.testtools; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Reader; import java.io.Writer; import java.util.Arrays; import junit.framework.AssertionFailedError; import junit.framework.TestCase; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.io.output.ByteArrayOutputStream; /** * Base class for testcases doing tests with files. */ public abstract class FileBasedTestCase extends TestCase { private static volatile File testDir; public FileBasedTestCase(String name) { super(name); } public static File getTestDirectory() { if (testDir == null) { testDir = new File("test/io/").getAbsoluteFile(); } testDir.mkdirs(); return testDir; } protected void createFile(File file, long size) throws IOException { if (!file.getParentFile().exists()) { throw new IOException("Cannot create file " + file + " as the parent directory does not exist"); } BufferedOutputStream output = new BufferedOutputStream(new java.io.FileOutputStream(file)); try { generateTestData(output, size); } finally { IOUtils.closeQuietly(output); } } protected byte[] generateTestData(long size) { try { ByteArrayOutputStream baout = new ByteArrayOutputStream(); generateTestData(baout, size); return baout.toByteArray(); } catch (IOException ioe) { throw new RuntimeException("This should never happen: " + ioe.getMessage()); } } protected void generateTestData(OutputStream out, long size) throws IOException { for (int i = 0; i < size; i++) { //output.write((byte)'X'); // nice varied byte pattern compatible with Readers and Writers out.write( (byte)( (i % 127) + 1) ); } } protected void createLineBasedFile(File file, String[] data) throws IOException { if (file.getParentFile() != null && !file.getParentFile().exists()) { throw new IOException("Cannot create file " + file + " as the parent directory does not exist"); } PrintWriter output = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8")); try { for (String element : data) { output.println(element); } } finally { IOUtils.closeQuietly(output); } } protected File newFile(String filename) throws IOException { File destination = new File( getTestDirectory(), filename ); /* assertTrue( filename + "Test output data file shouldn't previously exist", !destination.exists() ); */ if (destination.exists()) { FileUtils.forceDelete(destination); } return destination; } protected void checkFile( File file, File referenceFile ) throws Exception { assertTrue( "Check existence of output file", file.exists() ); assertEqualContent( referenceFile, file ); } /** Assert that the content of two files is the same. */ private void assertEqualContent( File f0, File f1 ) throws IOException { /* This doesn't work because the filesize isn't updated until the file * is closed. assertTrue( "The files " + f0 + " and " + f1 + " have differing file sizes (" + f0.length() + " vs " + f1.length() + ")", ( f0.length() == f1.length() ) ); */ InputStream is0 = new java.io.FileInputStream( f0 ); try { InputStream is1 = new java.io.FileInputStream( f1 ); try { byte[] buf0 = new byte[ 1024 ]; byte[] buf1 = new byte[ 1024 ]; int n0 = 0; int n1 = 0; while( -1 != n0 ) { n0 = is0.read( buf0 ); n1 = is1.read( buf1 ); assertTrue( "The files " + f0 + " and " + f1 + " have differing number of bytes available (" + n0 + " vs " + n1 + ")", ( n0 == n1 ) ); assertTrue( "The files " + f0 + " and " + f1 + " have different content", Arrays.equals( buf0, buf1 ) ); } } finally { is1.close(); } } finally { is0.close(); } } /** Assert that the content of a file is equal to that in a byte[]. */ protected void assertEqualContent(byte[] b0, File file) throws IOException { InputStream is = new java.io.FileInputStream(file); int count = 0, numRead = 0; byte[] b1 = new byte[b0.length]; try { while (count < b0.length && numRead >= 0) { numRead = is.read(b1, count, b0.length); count += numRead; } assertEquals("Different number of bytes: ", b0.length, count); for (int i = 0; i < count; i++) { assertEquals("byte " + i + " differs", b0[i], b1[i]); } } finally { is.close(); } } /** Assert that the content of a file is equal to that in a char[]. */ protected void assertEqualContent(char[] c0, File file) throws IOException { Reader ir = new java.io.FileReader(file); int count = 0, numRead = 0; char[] c1 = new char[c0.length]; try { while (count < c0.length && numRead >= 0) { numRead = ir.read(c1, count, c0.length); count += numRead; } assertEquals("Different number of chars: ", c0.length, count); for (int i = 0; i < count; i++) { assertEquals("char " + i + " differs", c0[i], c1[i]); } } finally { ir.close(); } } protected void checkWrite(OutputStream output) throws Exception { try { new java.io.PrintStream(output).write(0); } catch (Throwable t) { throw new AssertionFailedError( "The copy() method closed the stream " + "when it shouldn't have. " + t.getMessage()); } } protected void checkWrite(Writer output) throws Exception { try { new java.io.PrintWriter(output).write('a'); } catch (Throwable t) { throw new AssertionFailedError( "The copy() method closed the stream " + "when it shouldn't have. " + t.getMessage()); } } protected void deleteFile( File file ) throws Exception { if (file.exists()) { assertTrue("Couldn't delete file: " + file, file.delete()); } } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/testtools/YellOnCloseInputStream.javalibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/testtools/YellOnCloseInputStream.jav0000644000175000017500000000267412125050425033250 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.testtools; import java.io.IOException; import java.io.InputStream; import junit.framework.AssertionFailedError; import org.apache.commons.io.input.ProxyInputStream; /** * Helper class for checking behaviour of IO classes. */ public class YellOnCloseInputStream extends ProxyInputStream { /** * @param proxy InputStream to delegate to. */ public YellOnCloseInputStream(InputStream proxy) { super(proxy); } /** @see java.io.InputStream#close() */ @Override public void close() throws IOException { throw new AssertionFailedError("close() was called on OutputStream"); } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/testtools/YellOnFlushAndCloseOutputStream.javalibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/testtools/YellOnFlushAndCloseOutputS0000644000175000017500000000424412125050425033261 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.testtools; import java.io.IOException; import java.io.OutputStream; import junit.framework.AssertionFailedError; import org.apache.commons.io.output.ProxyOutputStream; /** * Helper class for checking behaviour of IO classes. */ public class YellOnFlushAndCloseOutputStream extends ProxyOutputStream { private boolean yellForFlush; private boolean yellForClose; /** * @param proxy OutputStream to delegate to. * @param yellForFlush True if flush() is forbidden * @param yellForClose True if close() is forbidden */ public YellOnFlushAndCloseOutputStream(OutputStream proxy, boolean yellForFlush, boolean yellForClose) { super(proxy); this.yellForFlush = yellForFlush; this.yellForClose = yellForClose; } /** @see java.io.OutputStream#flush() */ @Override public void flush() throws IOException { if (yellForFlush) { throw new AssertionFailedError("flush() was called on OutputStream"); } super.flush(); } /** @see java.io.OutputStream#close() */ @Override public void close() throws IOException { if (yellForClose) { throw new AssertionFailedError("close() was called on OutputStream"); } super.close(); } public void off() { yellForFlush = false; yellForClose = false; } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/monitor/0000755000175000017500000000000012125050425025600 5ustar ebourgebourg././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/monitor/FileAlterationMonitorTestCase.javalibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/monitor/FileAlterationMonitorTestCas0000644000175000017500000001365612125050425033277 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.monitor; import java.io.File; import java.util.Collection; import java.util.Iterator; import java.util.concurrent.Executors; /** * {@link FileAlterationMonitor} Test Case. */ public class FileAlterationMonitorTestCase extends AbstractMonitorTestCase { /** * Construct a new test case. * * @param name The name of the test */ public FileAlterationMonitorTestCase(String name) { super(name); testDirName = "test-monitor"; } @Override protected void setUp() throws Exception { listener = new CollectionFileListener(false); super.setUp(); } /** * Test default constructor. */ public void testDefaultConstructor() { FileAlterationMonitor monitor = new FileAlterationMonitor(); assertEquals("Interval", 10000, monitor.getInterval()); } /** * Test add/remove observers. */ public void testAddRemoveObservers() { FileAlterationObserver[] observers = null; FileAlterationMonitor monitor = null; // Null Observers monitor = new FileAlterationMonitor(123, observers); assertEquals("Interval", 123, monitor.getInterval()); assertFalse("Observers[1]", monitor.getObservers().iterator().hasNext()); // Null Observer observers = new FileAlterationObserver[1]; // observer is null monitor = new FileAlterationMonitor(456, observers); assertFalse("Observers[2]", monitor.getObservers().iterator().hasNext()); // Null Observer monitor.addObserver(null); assertFalse("Observers[3]", monitor.getObservers().iterator().hasNext()); monitor.removeObserver(null); // Add Observer FileAlterationObserver observer = new FileAlterationObserver("foo"); monitor.addObserver(observer); Iterator it = monitor.getObservers().iterator(); assertTrue("Observers[4]", it.hasNext()); assertEquals("Added", observer, it.next()); assertFalse("Observers[5]", it.hasNext()); // Remove Observer monitor.removeObserver(observer); assertFalse("Observers[6]", monitor.getObservers().iterator().hasNext()); } /** * Test checkAndNotify() method */ public void testMonitor() { try { long interval = 100; listener.clear(); FileAlterationMonitor monitor = new FileAlterationMonitor(interval, observer); assertEquals("Interval", interval, monitor.getInterval()); monitor.start(); try { monitor.start(); // try and start again } catch (IllegalStateException e) { // expected result, monitor already running } // Create a File checkCollectionsEmpty("A"); File file1 = touch(new File(testDir, "file1.java")); checkFile("Create", file1, listener.getCreatedFiles()); listener.clear(); // Update a file checkCollectionsEmpty("B"); file1 = touch(file1); checkFile("Update", file1, listener.getChangedFiles()); listener.clear(); // Delete a file checkCollectionsEmpty("C"); file1.delete(); checkFile("Delete", file1, listener.getDeletedFiles()); listener.clear(); // Stop monitoring monitor.stop(); try { monitor.stop(); // try and stop again } catch (IllegalStateException e) { // expected result, monitor already stopped } } catch (Exception e) { e.printStackTrace(); fail("Threw " + e); } } /** * Test using a thread factory. */ public void testThreadFactory() { try { long interval = 100; listener.clear(); FileAlterationMonitor monitor = new FileAlterationMonitor(interval, observer); monitor.setThreadFactory(Executors.defaultThreadFactory()); assertEquals("Interval", interval, monitor.getInterval()); monitor.start(); // Create a File checkCollectionsEmpty("A"); File file2 = touch(new File(testDir, "file2.java")); checkFile("Create", file2, listener.getCreatedFiles()); listener.clear(); // Delete a file checkCollectionsEmpty("B"); file2.delete(); checkFile("Delete", file2, listener.getDeletedFiles()); listener.clear(); // Stop monitoring monitor.stop(); } catch (Exception e) { e.printStackTrace(); fail("Threw " + e); } } /** * Check all the File Collections have the expected sizes. */ private void checkFile(String label, File file, Collection files) { for (int i = 0; i < 20; i++) { if (files.contains(file)) { return; // found, test passes } sleepHandleInterruped(pauseTime); } fail(label + " " + file + " not found"); } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/monitor/FileAlterationObserverTestCase.javalibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/monitor/FileAlterationObserverTestCa0000644000175000017500000004332312125050425033246 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.monitor; import java.io.File; import java.io.FileFilter; import java.util.Iterator; import org.apache.commons.io.FileUtils; import org.apache.commons.io.filefilter.CanReadFileFilter; import org.apache.commons.io.filefilter.FileFilterUtils; /** * {@link FileAlterationObserver} Test Case. */ public class FileAlterationObserverTestCase extends AbstractMonitorTestCase { /** * Construct a new test case. * * @param name The name of the test */ public FileAlterationObserverTestCase(String name) { super(name); testDirName = "test-observer"; } @Override protected void setUp() throws Exception { listener = new CollectionFileListener(true); super.setUp(); } /** * Test add/remove listeners. */ public void testAddRemoveListeners() { FileAlterationObserver observer = new FileAlterationObserver("/foo"); // Null Listener observer.addListener(null); assertFalse("Listeners[1]", observer.getListeners().iterator().hasNext()); observer.removeListener(null); assertFalse("Listeners[2]", observer.getListeners().iterator().hasNext()); // Add Listener FileAlterationListenerAdaptor listener = new FileAlterationListenerAdaptor(); observer.addListener(listener); Iterator it = observer.getListeners().iterator(); assertTrue("Listeners[3]", it.hasNext()); assertEquals("Added", listener, it.next()); assertFalse("Listeners[4]", it.hasNext()); // Remove Listener observer.removeListener(listener); assertFalse("Listeners[5]", observer.getListeners().iterator().hasNext()); } /** * Test toString(). */ public void testToString() { File file = new File("/foo"); FileAlterationObserver observer = null; observer = new FileAlterationObserver(file); assertEquals("FileAlterationObserver[file='" + file.getPath() + "', listeners=0]", observer.toString()); observer = new FileAlterationObserver(file, CanReadFileFilter.CAN_READ); assertEquals("FileAlterationObserver[file='" + file.getPath() + "', CanReadFileFilter, listeners=0]", observer.toString()); assertEquals(file, observer.getDirectory()); } /** * Test checkAndNotify() method */ public void testDirectory() { try { checkAndNotify(); checkCollectionsEmpty("A"); File testDirA = new File(testDir, "test-dir-A"); File testDirB = new File(testDir, "test-dir-B"); File testDirC = new File(testDir, "test-dir-C"); testDirA.mkdir(); testDirB.mkdir(); testDirC.mkdir(); File testDirAFile1 = touch(new File(testDirA, "A-file1.java")); File testDirAFile2 = touch(new File(testDirA, "A-file2.txt")); // filter should ignore this File testDirAFile3 = touch(new File(testDirA, "A-file3.java")); File testDirAFile4 = touch(new File(testDirA, "A-file4.java")); File testDirBFile1 = touch(new File(testDirB, "B-file1.java")); checkAndNotify(); checkCollectionSizes("B", 3, 0, 0, 4, 0, 0); assertTrue("B testDirA", listener.getCreatedDirectories().contains(testDirA)); assertTrue("B testDirB", listener.getCreatedDirectories().contains(testDirB)); assertTrue("B testDirC", listener.getCreatedDirectories().contains(testDirC)); assertTrue("B testDirAFile1", listener.getCreatedFiles().contains(testDirAFile1)); assertFalse("B testDirAFile2", listener.getCreatedFiles().contains(testDirAFile2)); assertTrue("B testDirAFile3", listener.getCreatedFiles().contains(testDirAFile3)); assertTrue("B testDirAFile4", listener.getCreatedFiles().contains(testDirAFile4)); assertTrue("B testDirBFile1", listener.getCreatedFiles().contains(testDirBFile1)); checkAndNotify(); checkCollectionsEmpty("C"); testDirAFile4 = touch(testDirAFile4); FileUtils.deleteDirectory(testDirB); checkAndNotify(); checkCollectionSizes("D", 0, 0, 1, 0, 1, 1); assertTrue("D testDirB", listener.getDeletedDirectories().contains(testDirB)); assertTrue("D testDirAFile4", listener.getChangedFiles().contains(testDirAFile4)); assertTrue("D testDirBFile1", listener.getDeletedFiles().contains(testDirBFile1)); FileUtils.deleteDirectory(testDir); checkAndNotify(); checkCollectionSizes("E", 0, 0, 2, 0, 0, 3); assertTrue("E testDirA", listener.getDeletedDirectories().contains(testDirA)); assertTrue("E testDirAFile1", listener.getDeletedFiles().contains(testDirAFile1)); assertFalse("E testDirAFile2", listener.getDeletedFiles().contains(testDirAFile2)); assertTrue("E testDirAFile3", listener.getDeletedFiles().contains(testDirAFile3)); assertTrue("E testDirAFile4", listener.getDeletedFiles().contains(testDirAFile4)); testDir.mkdir(); checkAndNotify(); checkCollectionsEmpty("F"); checkAndNotify(); checkCollectionsEmpty("G"); } catch (Exception e) { e.printStackTrace(); fail("Threw " + e); } } /** * Test checkAndNotify() creating */ public void testFileCreate() { try { checkAndNotify(); checkCollectionsEmpty("A"); File testDirA = new File(testDir, "test-dir-A"); testDirA.mkdir(); testDir = touch(testDir); testDirA = touch(testDirA); File testDirAFile1 = new File(testDirA, "A-file1.java"); File testDirAFile2 = touch(new File(testDirA, "A-file2.java")); File testDirAFile3 = new File(testDirA, "A-file3.java"); File testDirAFile4 = touch(new File(testDirA, "A-file4.java")); File testDirAFile5 = new File(testDirA, "A-file5.java"); checkAndNotify(); checkCollectionSizes("B", 1, 0, 0, 2, 0, 0); assertFalse("B testDirAFile1", listener.getCreatedFiles().contains(testDirAFile1)); assertTrue("B testDirAFile2", listener.getCreatedFiles().contains(testDirAFile2)); assertFalse("B testDirAFile3", listener.getCreatedFiles().contains(testDirAFile3)); assertTrue("B testDirAFile4", listener.getCreatedFiles().contains(testDirAFile4)); assertFalse("B testDirAFile5", listener.getCreatedFiles().contains(testDirAFile5)); assertFalse("B testDirAFile1 exists", testDirAFile1.exists()); assertTrue("B testDirAFile2 exists", testDirAFile2.exists()); assertFalse("B testDirAFile3 exists", testDirAFile3.exists()); assertTrue("B testDirAFile4 exists", testDirAFile4.exists()); assertFalse("B testDirAFile5 exists", testDirAFile5.exists()); checkAndNotify(); checkCollectionsEmpty("C"); // Create file with name < first entry testDirAFile1 = touch(testDirAFile1); testDirA = touch(testDirA); checkAndNotify(); checkCollectionSizes("D", 0, 1, 0, 1, 0, 0); assertTrue("D testDirAFile1 exists", testDirAFile1.exists()); assertTrue("D testDirAFile1", listener.getCreatedFiles().contains(testDirAFile1)); // Create file with name between 2 entries testDirAFile3 = touch(testDirAFile3); testDirA = touch(testDirA); checkAndNotify(); checkCollectionSizes("E", 0, 1, 0, 1, 0, 0); assertTrue("E testDirAFile3 exists", testDirAFile3.exists()); assertTrue("E testDirAFile3", listener.getCreatedFiles().contains(testDirAFile3)); // Create file with name > last entry testDirAFile5 = touch(testDirAFile5); testDirA = touch(testDirA); checkAndNotify(); checkCollectionSizes("F", 0, 1, 0, 1, 0, 0); assertTrue("F testDirAFile5 exists", testDirAFile5.exists()); assertTrue("F testDirAFile5", listener.getCreatedFiles().contains(testDirAFile5)); } catch (Exception e) { fail("Threw " + e); } } /** * Test checkAndNotify() creating */ public void testFileUpdate() { try { checkAndNotify(); checkCollectionsEmpty("A"); File testDirA = new File(testDir, "test-dir-A"); testDirA.mkdir(); testDir = touch(testDir); testDirA = touch(testDirA); File testDirAFile1 = touch(new File(testDirA, "A-file1.java")); File testDirAFile2 = touch(new File(testDirA, "A-file2.java")); File testDirAFile3 = touch(new File(testDirA, "A-file3.java")); File testDirAFile4 = touch(new File(testDirA, "A-file4.java")); File testDirAFile5 = touch(new File(testDirA, "A-file5.java")); checkAndNotify(); checkCollectionSizes("B", 1, 0, 0, 5, 0, 0); assertTrue("B testDirAFile1", listener.getCreatedFiles().contains(testDirAFile1)); assertTrue("B testDirAFile2", listener.getCreatedFiles().contains(testDirAFile2)); assertTrue("B testDirAFile3", listener.getCreatedFiles().contains(testDirAFile3)); assertTrue("B testDirAFile4", listener.getCreatedFiles().contains(testDirAFile4)); assertTrue("B testDirAFile5", listener.getCreatedFiles().contains(testDirAFile5)); assertTrue("B testDirAFile1 exists", testDirAFile1.exists()); assertTrue("B testDirAFile2 exists", testDirAFile2.exists()); assertTrue("B testDirAFile3 exists", testDirAFile3.exists()); assertTrue("B testDirAFile4 exists", testDirAFile4.exists()); assertTrue("B testDirAFile5 exists", testDirAFile5.exists()); checkAndNotify(); checkCollectionsEmpty("C"); // Update first entry testDirAFile1 = touch(testDirAFile1); testDirA = touch(testDirA); checkAndNotify(); checkCollectionSizes("D", 0, 1, 0, 0, 1, 0); assertTrue("D testDirAFile1", listener.getChangedFiles().contains(testDirAFile1)); // Update file with name between 2 entries testDirAFile3 = touch(testDirAFile3); testDirA = touch(testDirA); checkAndNotify(); checkCollectionSizes("E", 0, 1, 0, 0, 1, 0); assertTrue("E testDirAFile3", listener.getChangedFiles().contains(testDirAFile3)); // Update last entry testDirAFile5 = touch(testDirAFile5); testDirA = touch(testDirA); checkAndNotify(); checkCollectionSizes("F", 0, 1, 0, 0, 1, 0); assertTrue("F testDirAFile5", listener.getChangedFiles().contains(testDirAFile5)); } catch (Exception e) { fail("Threw " + e); } } /** * Test checkAndNotify() deleting */ public void testFileDelete() { try { checkAndNotify(); checkCollectionsEmpty("A"); File testDirA = new File(testDir, "test-dir-A"); testDirA.mkdir(); testDir = touch(testDir); testDirA = touch(testDirA); File testDirAFile1 = touch(new File(testDirA, "A-file1.java")); File testDirAFile2 = touch(new File(testDirA, "A-file2.java")); File testDirAFile3 = touch(new File(testDirA, "A-file3.java")); File testDirAFile4 = touch(new File(testDirA, "A-file4.java")); File testDirAFile5 = touch(new File(testDirA, "A-file5.java")); assertTrue("B testDirAFile1 exists", testDirAFile1.exists()); assertTrue("B testDirAFile2 exists", testDirAFile2.exists()); assertTrue("B testDirAFile3 exists", testDirAFile3.exists()); assertTrue("B testDirAFile4 exists", testDirAFile4.exists()); assertTrue("B testDirAFile5 exists", testDirAFile5.exists()); checkAndNotify(); checkCollectionSizes("B", 1, 0, 0, 5, 0, 0); assertTrue("B testDirAFile1", listener.getCreatedFiles().contains(testDirAFile1)); assertTrue("B testDirAFile2", listener.getCreatedFiles().contains(testDirAFile2)); assertTrue("B testDirAFile3", listener.getCreatedFiles().contains(testDirAFile3)); assertTrue("B testDirAFile4", listener.getCreatedFiles().contains(testDirAFile4)); assertTrue("B testDirAFile5", listener.getCreatedFiles().contains(testDirAFile5)); checkAndNotify(); checkCollectionsEmpty("C"); // Delete first entry FileUtils.deleteQuietly(testDirAFile1); testDirA = touch(testDirA); checkAndNotify(); checkCollectionSizes("D", 0, 1, 0, 0, 0, 1); assertFalse("D testDirAFile1 exists", testDirAFile1.exists()); assertTrue("D testDirAFile1", listener.getDeletedFiles().contains(testDirAFile1)); // Delete file with name between 2 entries FileUtils.deleteQuietly(testDirAFile3); testDirA = touch(testDirA); checkAndNotify(); checkCollectionSizes("E", 0, 1, 0, 0, 0, 1); assertFalse("E testDirAFile3 exists", testDirAFile3.exists()); assertTrue("E testDirAFile3", listener.getDeletedFiles().contains(testDirAFile3)); // Delete last entry FileUtils.deleteQuietly(testDirAFile5); testDirA = touch(testDirA); checkAndNotify(); checkCollectionSizes("F", 0, 1, 0, 0, 0, 1); assertFalse("F testDirAFile5 exists", testDirAFile5.exists()); assertTrue("F testDirAFile5", listener.getDeletedFiles().contains(testDirAFile5)); } catch (Exception e) { fail("Threw " + e); } } /** * Test checkAndNotify() method */ public void testObserveSingleFile() { try { File testDirA = new File(testDir, "test-dir-A"); File testDirAFile1 = new File(testDirA, "A-file1.java"); testDirA.mkdir(); FileFilter nameFilter = FileFilterUtils.nameFileFilter(testDirAFile1.getName()); createObserver(testDirA, nameFilter); checkAndNotify(); checkCollectionsEmpty("A"); assertFalse("A testDirAFile1 exists", testDirAFile1.exists()); // Create testDirAFile1 = touch(testDirAFile1); File testDirAFile2 = touch(new File(testDirA, "A-file2.txt")); /* filter should ignore */ File testDirAFile3 = touch(new File(testDirA, "A-file3.java")); /* filter should ignore */ assertTrue("B testDirAFile1 exists", testDirAFile1.exists()); assertTrue("B testDirAFile2 exists", testDirAFile2.exists()); assertTrue("B testDirAFile3 exists", testDirAFile3.exists()); checkAndNotify(); checkCollectionSizes("C", 0, 0, 0, 1, 0, 0); assertTrue("C created", listener.getCreatedFiles().contains(testDirAFile1)); assertFalse("C created", listener.getCreatedFiles().contains(testDirAFile2)); assertFalse("C created", listener.getCreatedFiles().contains(testDirAFile3)); // Modify testDirAFile1 = touch(testDirAFile1); testDirAFile2 = touch(testDirAFile2); testDirAFile3 = touch(testDirAFile3); checkAndNotify(); checkCollectionSizes("D", 0, 0, 0, 0, 1, 0); assertTrue("D changed", listener.getChangedFiles().contains(testDirAFile1)); assertFalse("D changed", listener.getChangedFiles().contains(testDirAFile2)); assertFalse("D changed", listener.getChangedFiles().contains(testDirAFile3)); // Delete FileUtils.deleteQuietly(testDirAFile1); FileUtils.deleteQuietly(testDirAFile2); FileUtils.deleteQuietly(testDirAFile3); assertFalse("E testDirAFile1 exists", testDirAFile1.exists()); assertFalse("E testDirAFile2 exists", testDirAFile2.exists()); assertFalse("E testDirAFile3 exists", testDirAFile3.exists()); checkAndNotify(); checkCollectionSizes("E", 0, 0, 0, 0, 0, 1); assertTrue("E deleted", listener.getDeletedFiles().contains(testDirAFile1)); assertFalse("E deleted", listener.getDeletedFiles().contains(testDirAFile2)); assertFalse("E deleted", listener.getDeletedFiles().contains(testDirAFile3)); } catch (Exception e) { fail("Threw " + e); } } /** * Call {@link FileAlterationObserver#checkAndNotify()}. * * @throws Exception if an error occurs */ protected void checkAndNotify() throws Exception { observer.checkAndNotify(); } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/monitor/CollectionFileListener.java0000644000175000017500000001161412125050425033047 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.monitor; import java.io.File; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; /** * {@link FileAlterationListener} implementation that adds created, changed and deleted * files/directories to a set of {@link Collection}s. */ public class CollectionFileListener implements FileAlterationListener, Serializable { private final boolean clearOnStart; private final Collection createdFiles = new ArrayList(); private final Collection changedFiles = new ArrayList(); private final Collection deletedFiles = new ArrayList(); private final Collection createdDirectories = new ArrayList(); private final Collection changedDirectories = new ArrayList(); private final Collection deletedDirectories = new ArrayList(); /** * Create a new observer. * * @param clearOnStart true if clear() should be called by onStart(). */ public CollectionFileListener(boolean clearOnStart) { this.clearOnStart = clearOnStart; } /** * File system observer started checking event. * * @param observer The file system observer */ public void onStart(final FileAlterationObserver observer) { if (clearOnStart) { clear(); } } /** * Clear file collections. */ public void clear() { createdFiles.clear(); changedFiles.clear(); deletedFiles.clear(); createdDirectories.clear(); changedDirectories.clear(); deletedDirectories.clear(); } /** * Return the set of changed directories. * * @return Directories which have changed */ public Collection getChangedDirectories() { return changedDirectories; } /** * Return the set of changed files. * * @return Files which have changed */ public Collection getChangedFiles() { return changedFiles; } /** * Return the set of created directories. * * @return Directories which have been created */ public Collection getCreatedDirectories() { return createdDirectories; } /** * Return the set of created files. * * @return Files which have been created */ public Collection getCreatedFiles() { return createdFiles; } /** * Return the set of deleted directories. * * @return Directories which been deleted */ public Collection getDeletedDirectories() { return deletedDirectories; } /** * Return the set of deleted files. * * @return Files which been deleted */ public Collection getDeletedFiles() { return deletedFiles; } /** * Directory created Event. * * @param directory The directory created */ public void onDirectoryCreate(final File directory) { createdDirectories.add(directory); } /** * Directory changed Event. * * @param directory The directory changed */ public void onDirectoryChange(final File directory) { changedDirectories.add(directory); } /** * Directory deleted Event. * * @param directory The directory deleted */ public void onDirectoryDelete(final File directory) { deletedDirectories.add(directory); } /** * File created Event. * * @param file The file created */ public void onFileCreate(final File file) { createdFiles.add(file); } /** * File changed Event. * * @param file The file changed */ public void onFileChange(final File file) { changedFiles.add(file); } /** * File deleted Event. * * @param file The file deleted */ public void onFileDelete(final File file) { deletedFiles.add(file); } /** * File system observer finished checking event. * * @param observer The file system observer */ public void onStop(final FileAlterationObserver observer) { } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/monitor/AbstractMonitorTestCase.java0000644000175000017500000001341012125050425033211 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.monitor; import java.io.File; import java.io.FileFilter; import junit.framework.TestCase; import org.apache.commons.io.FileUtils; import org.apache.commons.io.filefilter.FileFilterUtils; import org.apache.commons.io.filefilter.HiddenFileFilter; import org.apache.commons.io.filefilter.IOFileFilter; /** * {@link FileAlterationObserver} Test Case. */ public abstract class AbstractMonitorTestCase extends TestCase { /** File observer */ protected FileAlterationObserver observer; /** Listener which collects file changes */ protected CollectionFileListener listener; /** Test diretory name */ protected String testDirName = null; /** Directory for test files */ protected File testDir; /** Time in milliseconds to pause in tests */ protected long pauseTime = 100L; /** * Construct a new test case. * * @param name The name of the test */ public AbstractMonitorTestCase(String name) { super(name); } @Override protected void setUp() throws Exception { testDir = new File(new File("."), testDirName); if (testDir.exists()) { FileUtils.cleanDirectory(testDir); } else { testDir.mkdir(); } IOFileFilter files = FileFilterUtils.fileFileFilter(); IOFileFilter javaSuffix = FileFilterUtils.suffixFileFilter(".java"); IOFileFilter fileFilter = FileFilterUtils.and(files, javaSuffix); IOFileFilter directories = FileFilterUtils.directoryFileFilter(); IOFileFilter visible = HiddenFileFilter.VISIBLE; IOFileFilter dirFilter = FileFilterUtils.and(directories, visible); IOFileFilter filter = FileFilterUtils.or(dirFilter, fileFilter); createObserver(testDir, filter); } /** * Create a {@link FileAlterationObserver}. * * @param file The directory to observe * @param fileFilter The file filter to apply */ protected void createObserver(File file, FileFilter fileFilter) { observer = new FileAlterationObserver(file, fileFilter); observer.addListener(listener); observer.addListener(new FileAlterationListenerAdaptor()); try { observer.initialize(); } catch (Exception e) { fail("Observer init() threw " + e); } } @Override protected void tearDown() throws Exception { FileUtils.deleteDirectory(testDir); } /** * Check all the Collections are empty */ protected void checkCollectionsEmpty(String label) { checkCollectionSizes("EMPTY-" + label, 0, 0, 0, 0, 0, 0); } /** * Check all the Collections have the expected sizes. */ protected void checkCollectionSizes(String label, int dirCreate, int dirChange, int dirDelete, int fileCreate, int fileChange, int fileDelete) { label = label + "[" + listener.getCreatedDirectories().size() + " " + listener.getChangedDirectories().size() + " " + listener.getDeletedDirectories().size() + " " + listener.getCreatedFiles().size() + " " + listener.getChangedFiles().size() + " " + listener.getDeletedFiles().size() + "]"; assertEquals(label + ": No. of directories created", dirCreate, listener.getCreatedDirectories().size()); assertEquals(label + ": No. of directories changed", dirChange, listener.getChangedDirectories().size()); assertEquals(label + ": No. of directories deleted", dirDelete, listener.getDeletedDirectories().size()); assertEquals(label + ": No. of files created", fileCreate, listener.getCreatedFiles().size()); assertEquals(label + ": No. of files changed", fileChange, listener.getChangedFiles().size()); assertEquals(label + ": No. of files deleted", fileDelete, listener.getDeletedFiles().size()); } /** * Either creates a file if it doesn't exist or updates the last modified date/time * if it does. * * @param file The file to touch * @return The file */ protected File touch(File file) { long lastModified = file.exists() ? file.lastModified() : 0; try { FileUtils.touch(file); file = new File(file.getParent(), file.getName()); while (lastModified == file.lastModified()) { sleepHandleInterruped(pauseTime); FileUtils.touch(file); file = new File(file.getParent(), file.getName()); } } catch (Exception e) { fail("Touching " + file + ": " + e); } sleepHandleInterruped(pauseTime); return file; } /** * Thread.sleep(timeInMilliseconds) - ignore InterruptedException */ protected void sleepHandleInterruped(long timeInMilliseconds) { try { Thread.sleep(timeInMilliseconds); } catch(InterruptedException ie) { // ignore } } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/TaggedIOExceptionTest.java0000644000175000017500000000303412125050425031116 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.io.IOException; import java.io.Serializable; import java.util.UUID; import junit.framework.TestCase; /** * JUnit Test Case for {@link TaggedIOException}. */ public class TaggedIOExceptionTest extends TestCase { public void testTaggedIOException() { Serializable tag = UUID.randomUUID(); IOException exception = new IOException("Test exception"); TaggedIOException tagged = new TaggedIOException(exception, tag); assertTrue(TaggedIOException.isTaggedWith(tagged, tag)); assertFalse(TaggedIOException.isTaggedWith(tagged, UUID.randomUUID())); assertEquals(exception, tagged.getCause()); assertEquals(exception.getMessage(), tagged.getMessage()); } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/DirectoryWalkerTestCaseJava4.java0000644000175000017500000004673012125050425032422 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import junit.framework.Assert; import junit.framework.TestCase; import org.apache.commons.io.filefilter.FileFilterUtils; import org.apache.commons.io.filefilter.IOFileFilter; import org.apache.commons.io.filefilter.NameFileFilter; import org.apache.commons.io.filefilter.OrFileFilter; /** * This is used to test DirectoryWalker for correctness when using Java4 (i.e. no generics). * * @version $Id: DirectoryWalkerTestCaseJava4.java 1302748 2012-03-20 01:35:32Z ggregory $ * @see DirectoryWalker * */ @SuppressWarnings({"unchecked","rawtypes"}) // Java4 public class DirectoryWalkerTestCaseJava4 extends TestCase { // Directories private static final File current = new File("."); private static final File javaDir = new File("src/main/java"); private static final File orgDir = new File(javaDir, "org"); private static final File apacheDir = new File(orgDir, "apache"); private static final File commonsDir = new File(apacheDir, "commons"); private static final File ioDir = new File(commonsDir, "io"); private static final File outputDir = new File(ioDir, "output"); private static final File[] dirs = new File[] {orgDir, apacheDir, commonsDir, ioDir, outputDir}; // Files private static final File filenameUtils = new File(ioDir, "FilenameUtils.java"); private static final File ioUtils = new File(ioDir, "IOUtils.java"); private static final File proxyWriter = new File(outputDir, "ProxyWriter.java"); private static final File nullStream = new File(outputDir, "NullOutputStream.java"); private static final File[] ioFiles = new File[] {filenameUtils, ioUtils}; private static final File[] outputFiles = new File[] {proxyWriter, nullStream}; // Filters private static final IOFileFilter dirsFilter = createNameFilter(dirs); private static final IOFileFilter iofilesFilter = createNameFilter(ioFiles); private static final IOFileFilter outputFilesFilter = createNameFilter(outputFiles); private static final IOFileFilter ioDirAndFilesFilter = new OrFileFilter(dirsFilter, iofilesFilter); private static final IOFileFilter dirsAndFilesFilter = new OrFileFilter(ioDirAndFilesFilter, outputFilesFilter); // Filter to exclude SVN files private static final IOFileFilter NOT_SVN = FileFilterUtils.makeSVNAware(null); /** Construct the TestCase using the name */ public DirectoryWalkerTestCaseJava4(String name) { super(name); } /** Set Up */ @Override protected void setUp() throws Exception { super.setUp(); } /** Tear Down */ @Override protected void tearDown() throws Exception { super.tearDown(); } //----------------------------------------------------------------------- /** * Test Filtering */ public void testFilter() { List results = new TestFileFinder(dirsAndFilesFilter, -1).find(javaDir); assertEquals("Result Size", 1 + dirs.length + ioFiles.length + outputFiles.length, results.size()); assertTrue("Start Dir", results.contains(javaDir)); checkContainsFiles("Dir", dirs, results); checkContainsFiles("IO File", ioFiles, results); checkContainsFiles("Output File", outputFiles, results); } /** * Test Filtering and limit to depth 0 */ public void testFilterAndLimitA() { List results = new TestFileFinder(NOT_SVN, 0).find(javaDir); assertEquals("[A] Result Size", 1, results.size()); assertTrue("[A] Start Dir", results.contains(javaDir)); } /** * Test Filtering and limit to depth 1 */ public void testFilterAndLimitB() { List results = new TestFileFinder(NOT_SVN, 1).find(javaDir); assertEquals("[B] Result Size", 2, results.size()); assertTrue("[B] Start Dir", results.contains(javaDir)); assertTrue("[B] Org Dir", results.contains(orgDir)); } /** * Test Filtering and limit to depth 3 */ public void testFilterAndLimitC() { List results = new TestFileFinder(NOT_SVN, 3).find(javaDir); assertEquals("[C] Result Size", 4, results.size()); assertTrue("[C] Start Dir", results.contains(javaDir)); assertTrue("[C] Org Dir", results.contains(orgDir)); assertTrue("[C] Apache Dir", results.contains(apacheDir)); assertTrue("[C] Commons Dir", results.contains(commonsDir)); } /** * Test Filtering and limit to depth 5 */ public void testFilterAndLimitD() { List results = new TestFileFinder(dirsAndFilesFilter, 5).find(javaDir); assertEquals("[D] Result Size", 1 + dirs.length + ioFiles.length, results.size()); assertTrue("[D] Start Dir", results.contains(javaDir)); checkContainsFiles("[D] Dir", dirs, results); checkContainsFiles("[D] File", ioFiles, results); } /** * Test separate dir and file filters */ public void testFilterDirAndFile1() { List results = new TestFileFinder(dirsFilter, iofilesFilter, -1).find(javaDir); assertEquals("[DirAndFile1] Result Size", 1 + dirs.length + ioFiles.length, results.size()); assertTrue("[DirAndFile1] Start Dir", results.contains(javaDir)); checkContainsFiles("[DirAndFile1] Dir", dirs, results); checkContainsFiles("[DirAndFile1] File", ioFiles, results); } /** * Test separate dir and file filters */ public void testFilterDirAndFile2() { List results = new TestFileFinder((IOFileFilter) null, (IOFileFilter) null, -1).find(javaDir); assertTrue("[DirAndFile2] Result Size", results.size() > 1 + dirs.length + ioFiles.length); assertTrue("[DirAndFile2] Start Dir", results.contains(javaDir)); checkContainsFiles("[DirAndFile2] Dir", dirs, results); checkContainsFiles("[DirAndFile2] File", ioFiles, results); } /** * Test separate dir and file filters */ public void testFilterDirAndFile3() { List results = new TestFileFinder(dirsFilter, (IOFileFilter) null, -1).find(javaDir); List resultDirs = directoriesOnly(results); assertEquals("[DirAndFile3] Result Size", 1 + dirs.length, resultDirs.size()); assertTrue("[DirAndFile3] Start Dir", results.contains(javaDir)); checkContainsFiles("[DirAndFile3] Dir", dirs, resultDirs); } /** * Test separate dir and file filters */ public void testFilterDirAndFile4() { List results = new TestFileFinder((IOFileFilter) null, iofilesFilter, -1).find(javaDir); List resultFiles = filesOnly(results); assertEquals("[DirAndFile4] Result Size", ioFiles.length, resultFiles.size()); assertTrue("[DirAndFile4] Start Dir", results.contains(javaDir)); checkContainsFiles("[DirAndFile4] File", ioFiles, resultFiles); } /** * Test Limiting to current directory */ public void testLimitToCurrent() { List results = new TestFileFinder(null, 0).find(current); assertEquals("Result Size", 1, results.size()); assertTrue("Current Dir", results.contains(new File("."))); } /** * test an invalid start directory */ public void testMissingStartDirectory() { // TODO is this what we want with invalid directory? File invalidDir = new File("invalid-dir"); List results = new TestFileFinder(null, -1).find(invalidDir); assertEquals("Result Size", 1, results.size()); assertTrue("Current Dir", results.contains(invalidDir)); try { new TestFileFinder(null, -1).find(null); fail("Null start directory didn't throw Exception"); } catch (NullPointerException ignore) { // expected result } } /** * test an invalid start directory */ public void testHandleStartDirectoryFalse() { List results = new TestFalseFileFinder(null, -1).find(current); assertEquals("Result Size", 0, results.size()); } // ------------ Convenience Test Methods ------------------------------------ /** * Check the files in the array are in the results list. */ private void checkContainsFiles(String prefix, File[] files, Collection results) { for (int i = 0; i < files.length; i++) { assertTrue(prefix + "["+i+"] " + files[i], results.contains(files[i])); } } /** * Extract the directories. */ private List directoriesOnly(Collection results) { List list = new ArrayList(results.size()); for (Iterator it = results.iterator(); it.hasNext(); ) { File file = (File) it.next(); if (file.isDirectory()) { list.add(file); } } return list; } /** * Extract the files. */ private List filesOnly(Collection results) { List list = new ArrayList(results.size()); for (Iterator it = results.iterator(); it.hasNext(); ) { File file = (File) it.next(); if (file.isFile()) { list.add(file); } } return list; } /** * Create an name filter containg the names of the files * in the array. */ private static IOFileFilter createNameFilter(File[] files) { String[] names = new String[files.length]; for (int i = 0; i < files.length; i++) { names[i] = files[i].getName(); } return new NameFileFilter(names); } /** * Test Cancel */ public void testCancel() { String cancelName = null; // Cancel on a file try { cancelName = "DirectoryWalker.java"; new TestCancelWalker(cancelName, false).find(javaDir); fail("CancelException not thrown for '" + cancelName + "'"); } catch (DirectoryWalker.CancelException cancel) { assertEquals("File: " + cancelName, cancelName, cancel.getFile().getName()); assertEquals("Depth: " + cancelName, 5, cancel.getDepth()); } catch(IOException ex) { fail("IOException: " + cancelName + " " + ex); } // Cancel on a directory try { cancelName = "commons"; new TestCancelWalker(cancelName, false).find(javaDir); fail("CancelException not thrown for '" + cancelName + "'"); } catch (DirectoryWalker.CancelException cancel) { assertEquals("File: " + cancelName, cancelName, cancel.getFile().getName()); assertEquals("Depth: " + cancelName, 3, cancel.getDepth()); } catch(IOException ex) { fail("IOException: " + cancelName + " " + ex); } // Suppress CancelException (use same file name as preceeding test) try { List results = new TestCancelWalker(cancelName, true).find(javaDir); File lastFile = (File) results.get(results.size() - 1); assertEquals("Suppress: " + cancelName, cancelName, lastFile.getName()); } catch(IOException ex) { fail("Suppress threw " + ex); } } /** * Test Cancel */ public void testMultiThreadCancel() { String cancelName = "DirectoryWalker.java"; TestMultiThreadCancelWalker walker = new TestMultiThreadCancelWalker(cancelName, false); // Cancel on a file try { walker.find(javaDir); fail("CancelException not thrown for '" + cancelName + "'"); } catch (DirectoryWalker.CancelException cancel) { File last = (File) walker.results.get(walker.results.size() - 1); assertEquals(cancelName, last.getName()); assertEquals("Depth: " + cancelName, 5, cancel.getDepth()); } catch(IOException ex) { fail("IOException: " + cancelName + " " + ex); } // Cancel on a directory try { cancelName = "commons"; walker = new TestMultiThreadCancelWalker(cancelName, false); walker.find(javaDir); fail("CancelException not thrown for '" + cancelName + "'"); } catch (DirectoryWalker.CancelException cancel) { assertEquals("File: " + cancelName, cancelName, cancel.getFile().getName()); assertEquals("Depth: " + cancelName, 3, cancel.getDepth()); } catch(IOException ex) { fail("IOException: " + cancelName + " " + ex); } // Suppress CancelException (use same file name as preceeding test) try { walker = new TestMultiThreadCancelWalker(cancelName, true); List results = walker.find(javaDir); File lastFile = (File) results.get(results.size() - 1); assertEquals("Suppress: " + cancelName, cancelName, lastFile.getName()); } catch(IOException ex) { fail("Suppress threw " + ex); } } // ------------ Test DirectoryWalker implementation -------------------------- /** * Test DirectoryWalker implementation that finds files in a directory hierarchy * applying a file filter. */ private static class TestFileFinder extends DirectoryWalker { protected TestFileFinder(FileFilter filter, int depthLimit) { super(filter, depthLimit); } protected TestFileFinder(IOFileFilter dirFilter, IOFileFilter fileFilter, int depthLimit) { super(dirFilter, fileFilter, depthLimit); } /** find files. */ protected List find(File startDirectory) { List results = new ArrayList(); try { walk(startDirectory, results); } catch(IOException ex) { Assert.fail(ex.toString()); } return results; } /** Handles a directory end by adding the File to the result set. */ @Override protected void handleDirectoryEnd(File directory, int depth, Collection results) { results.add(directory); } /** Handles a file by adding the File to the result set. */ @Override protected void handleFile(File file, int depth, Collection results) { results.add(file); } } // ------------ Test DirectoryWalker implementation -------------------------- /** * Test DirectoryWalker implementation that always returns false * from handleDirectoryStart() */ private static class TestFalseFileFinder extends TestFileFinder { protected TestFalseFileFinder(FileFilter filter, int depthLimit) { super(filter, depthLimit); } /** Always returns false. */ @Override protected boolean handleDirectory(File directory, int depth, Collection results) { return false; } } // ------------ Test DirectoryWalker implementation -------------------------- /** * Test DirectoryWalker implementation that finds files in a directory hierarchy * applying a file filter. */ static class TestCancelWalker extends DirectoryWalker { private String cancelFileName; private boolean suppressCancel; TestCancelWalker(String cancelFileName,boolean suppressCancel) { super(); this.cancelFileName = cancelFileName; this.suppressCancel = suppressCancel; } /** find files. */ protected List find(File startDirectory) throws IOException { List results = new ArrayList(); walk(startDirectory, results); return results; } /** Handles a directory end by adding the File to the result set. */ @Override protected void handleDirectoryEnd(File directory, int depth, Collection results) throws IOException { results.add(directory); if (cancelFileName.equals(directory.getName())) { throw new CancelException(directory, depth); } } /** Handles a file by adding the File to the result set. */ @Override protected void handleFile(File file, int depth, Collection results) throws IOException { results.add(file); if (cancelFileName.equals(file.getName())) { throw new CancelException(file, depth); } } /** Handles Cancel. */ @Override protected void handleCancelled(File startDirectory, Collection results, CancelException cancel) throws IOException { if (!suppressCancel) { super.handleCancelled(startDirectory, results, cancel); } } } /** * Test DirectoryWalker implementation that finds files in a directory hierarchy * applying a file filter. */ static class TestMultiThreadCancelWalker extends DirectoryWalker { private String cancelFileName; private boolean suppressCancel; private boolean cancelled; public List results; TestMultiThreadCancelWalker(String cancelFileName, boolean suppressCancel) { super(); this.cancelFileName = cancelFileName; this.suppressCancel = suppressCancel; } /** find files. */ protected List find(File startDirectory) throws IOException { results = new ArrayList(); walk(startDirectory, results); return results; } /** Handles a directory end by adding the File to the result set. */ @Override protected void handleDirectoryEnd(File directory, int depth, Collection results) throws IOException { results.add(directory); assertFalse(cancelled); if (cancelFileName.equals(directory.getName())) { cancelled = true; } } /** Handles a file by adding the File to the result set. */ @Override protected void handleFile(File file, int depth, Collection results) throws IOException { results.add(file); assertFalse(cancelled); if (cancelFileName.equals(file.getName())) { cancelled = true; } } /** Handles Cancelled. */ @Override protected boolean handleIsCancelled(File file, int depth, Collection results) throws IOException { return cancelled; } /** Handles Cancel. */ @Override protected void handleCancelled(File startDirectory, Collection results, CancelException cancel) throws IOException { if (!suppressCancel) { super.handleCancelled(startDirectory, results, cancel); } } } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/FileUtilsTestCase.java0000644000175000017500000030500012125050425030306 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.math.BigInteger; import java.net.URL; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.zip.CRC32; import java.util.zip.Checksum; import org.apache.commons.io.filefilter.NameFileFilter; import org.apache.commons.io.filefilter.WildcardFileFilter; import org.apache.commons.io.testtools.FileBasedTestCase; import org.junit.Assert; /** * This is used to test FileUtils for correctness. * * @version $Id: FileUtilsTestCase.java 1349488 2012-06-12 19:29:22Z ggregory $ * @see FileUtils */ public class FileUtilsTestCase extends FileBasedTestCase { // Test data /** * Size of test directory. */ private static final int TEST_DIRECTORY_SIZE = 0; /** * Size of test directory. */ private static final BigInteger TEST_DIRECTORY_SIZE_BI = BigInteger.ZERO; /** * Size (greater of zero) of test file. */ private static final BigInteger TEST_DIRECTORY_SIZE_GT_ZERO_BI = BigInteger.valueOf(100); /** * List files recursively */ private static final ListDirectoryWalker LIST_WALKER = new ListDirectoryWalker(); /** Delay in milliseconds to make sure test for "last modified date" are accurate */ //private static final int LAST_MODIFIED_DELAY = 600; private File testFile1; private File testFile2; private int testFile1Size; private int testFile2Size; public FileUtilsTestCase(String name) { super(name); testFile1 = new File(getTestDirectory(), "file1-test.txt"); testFile2 = new File(getTestDirectory(), "file1a-test.txt"); testFile1Size = (int)testFile1.length(); testFile2Size = (int)testFile2.length(); } /** @see junit.framework.TestCase#setUp() */ @Override protected void setUp() throws Exception { getTestDirectory().mkdirs(); createFile(testFile1, testFile1Size); createFile(testFile2, testFile2Size); FileUtils.deleteDirectory(getTestDirectory()); getTestDirectory().mkdirs(); createFile(testFile1, testFile1Size); createFile(testFile2, testFile2Size); } /** @see junit.framework.TestCase#tearDown() */ @Override protected void tearDown() throws Exception { FileUtils.deleteDirectory(getTestDirectory()); } //----------------------------------------------------------------------- /** * Tests the {@link FileUtils#getFile(String...)} method. */ public void testGetFile() { File expected_A = new File("src"); File expected_B = new File(expected_A, "main"); File expected_C = new File(expected_B, "java"); assertEquals("A", expected_A, FileUtils.getFile("src")); assertEquals("B", expected_B, FileUtils.getFile("src", "main")); assertEquals("C", expected_C, FileUtils.getFile("src", "main", "java")); try { FileUtils.getFile((String[])null); fail("Expected NullPointerException"); } catch (NullPointerException e) { // expected } } /** * Tests the {@link FileUtils#getFile(File, String...)} method. */ public void testGetFile_Parent() { File parent = new File("parent"); File expected_A = new File(parent, "src"); File expected_B = new File(expected_A, "main"); File expected_C = new File(expected_B, "java"); assertEquals("A", expected_A, FileUtils.getFile(parent, "src")); assertEquals("B", expected_B, FileUtils.getFile(parent, "src", "main")); assertEquals("C", expected_C, FileUtils.getFile(parent, "src", "main", "java")); try { FileUtils.getFile(parent, (String[])null); fail("Expected NullPointerException"); } catch (NullPointerException e) { // expected } try { FileUtils.getFile((File)null, "src"); fail("Expected NullPointerException"); } catch (NullPointerException e) { // expected } } /** * Tests the {@link FileUtils#getTempDirectoryPath()} method. */ public void testGetTempDirectoryPath() { assertEquals(System.getProperty("java.io.tmpdir"), FileUtils.getTempDirectoryPath()); } /** * Tests the {@link FileUtils#getTempDirectory()} method. */ public void testGetTempDirectory() { File tempDirectory = new File(System.getProperty("java.io.tmpdir")); assertEquals(tempDirectory, FileUtils.getTempDirectory()); } /** * Tests the {@link FileUtils#getUserDirectoryPath()} method. */ public void testGetUserDirectoryPath() { assertEquals(System.getProperty("user.home"), FileUtils.getUserDirectoryPath()); } /** * Tests the {@link FileUtils#getUserDirectory()} method. */ public void testGetUserDirectory() { File userDirectory = new File(System.getProperty("user.home")); assertEquals(userDirectory, FileUtils.getUserDirectory()); } //----------------------------------------------------------------------- public void test_openInputStream_exists() throws Exception { File file = new File(getTestDirectory(), "test.txt"); createLineBasedFile(file, new String[] {"Hello"}); FileInputStream in = null; try { in = FileUtils.openInputStream(file); assertEquals('H', in.read()); } finally { IOUtils.closeQuietly(in); } } public void test_openInputStream_existsButIsDirectory() throws Exception { File directory = new File(getTestDirectory(), "subdir"); directory.mkdirs(); FileInputStream in = null; try { in = FileUtils.openInputStream(directory); fail(); } catch (IOException ioe) { // expected } finally { IOUtils.closeQuietly(in); } } public void test_openInputStream_notExists() throws Exception { File directory = new File(getTestDirectory(), "test.txt"); FileInputStream in = null; try { in = FileUtils.openInputStream(directory); fail(); } catch (IOException ioe) { // expected } finally { IOUtils.closeQuietly(in); } } //----------------------------------------------------------------------- void openOutputStream_noParent(boolean createFile) throws Exception { File file = new File("test.txt"); assertNull(file.getParentFile()); try { if (createFile) { createLineBasedFile(file, new String[]{"Hello"});} FileOutputStream out = null; try { out = FileUtils.openOutputStream(file); out.write(0); } finally { IOUtils.closeQuietly(out); } assertTrue(file.exists()); } finally { if (file.delete() == false) { file.deleteOnExit(); } } } public void test_openOutputStream_noParentCreateFile() throws Exception { openOutputStream_noParent(true); } public void test_openOutputStream_noParentNoFile() throws Exception { openOutputStream_noParent(false); } public void test_openOutputStream_exists() throws Exception { File file = new File(getTestDirectory(), "test.txt"); createLineBasedFile(file, new String[] {"Hello"}); FileOutputStream out = null; try { out = FileUtils.openOutputStream(file); out.write(0); } finally { IOUtils.closeQuietly(out); } assertTrue(file.exists()); } public void test_openOutputStream_existsButIsDirectory() throws Exception { File directory = new File(getTestDirectory(), "subdir"); directory.mkdirs(); FileOutputStream out = null; try { out = FileUtils.openOutputStream(directory); fail(); } catch (IOException ioe) { // expected } finally { IOUtils.closeQuietly(out); } } public void test_openOutputStream_notExists() throws Exception { File file = new File(getTestDirectory(), "a/test.txt"); FileOutputStream out = null; try { out = FileUtils.openOutputStream(file); out.write(0); } finally { IOUtils.closeQuietly(out); } assertTrue(file.exists()); } public void test_openOutputStream_notExistsCannotCreate() throws Exception { // according to Wikipedia, most filing systems have a 256 limit on filename String longStr = "abcdevwxyzabcdevwxyzabcdevwxyzabcdevwxyzabcdevwxyz" + "abcdevwxyzabcdevwxyzabcdevwxyzabcdevwxyzabcdevwxyz" + "abcdevwxyzabcdevwxyzabcdevwxyzabcdevwxyzabcdevwxyz" + "abcdevwxyzabcdevwxyzabcdevwxyzabcdevwxyzabcdevwxyz" + "abcdevwxyzabcdevwxyzabcdevwxyzabcdevwxyzabcdevwxyz" + "abcdevwxyzabcdevwxyzabcdevwxyzabcdevwxyzabcdevwxyz"; // 300 chars File file = new File(getTestDirectory(), "a/" + longStr + "/test.txt"); FileOutputStream out = null; try { out = FileUtils.openOutputStream(file); fail(); } catch (IOException ioe) { // expected } finally { IOUtils.closeQuietly(out); } } //----------------------------------------------------------------------- // byteCountToDisplaySize public void testByteCountToDisplaySizeBigInteger() { final BigInteger b1023 = BigInteger.valueOf(1023); final BigInteger b1025 = BigInteger.valueOf(1025); final BigInteger KB1 = BigInteger.valueOf(1024); final BigInteger MB1 = KB1.multiply(KB1); final BigInteger GB1 = MB1.multiply(KB1); final BigInteger GB2 = GB1.add(GB1); final BigInteger TB1 = GB1.multiply(KB1); final BigInteger PB1 = TB1.multiply(KB1); final BigInteger EB1 = PB1.multiply(KB1); assertEquals(FileUtils.byteCountToDisplaySize(BigInteger.ZERO), "0 bytes"); assertEquals(FileUtils.byteCountToDisplaySize(BigInteger.ONE), "1 bytes"); assertEquals(FileUtils.byteCountToDisplaySize(b1023), "1023 bytes"); assertEquals(FileUtils.byteCountToDisplaySize(KB1), "1 KB"); assertEquals(FileUtils.byteCountToDisplaySize(b1025), "1 KB"); assertEquals(FileUtils.byteCountToDisplaySize(MB1.subtract(BigInteger.ONE)), "1023 KB"); assertEquals(FileUtils.byteCountToDisplaySize(MB1), "1 MB"); assertEquals(FileUtils.byteCountToDisplaySize(MB1.add(BigInteger.ONE)), "1 MB"); assertEquals(FileUtils.byteCountToDisplaySize(GB1.subtract(BigInteger.ONE)), "1023 MB"); assertEquals(FileUtils.byteCountToDisplaySize(GB1), "1 GB"); assertEquals(FileUtils.byteCountToDisplaySize(GB1.add(BigInteger.ONE)), "1 GB"); assertEquals(FileUtils.byteCountToDisplaySize(GB2), "2 GB"); assertEquals(FileUtils.byteCountToDisplaySize(GB2.subtract(BigInteger.ONE)), "1 GB"); assertEquals(FileUtils.byteCountToDisplaySize(TB1), "1 TB"); assertEquals(FileUtils.byteCountToDisplaySize(PB1), "1 PB"); assertEquals(FileUtils.byteCountToDisplaySize(EB1), "1 EB"); assertEquals(FileUtils.byteCountToDisplaySize(Long.MAX_VALUE), "7 EB"); // Other MAX_VALUEs assertEquals(FileUtils.byteCountToDisplaySize(BigInteger.valueOf(Character.MAX_VALUE)), "63 KB"); assertEquals(FileUtils.byteCountToDisplaySize(BigInteger.valueOf(Short.MAX_VALUE)), "31 KB"); assertEquals(FileUtils.byteCountToDisplaySize(BigInteger.valueOf(Integer.MAX_VALUE)), "1 GB"); } public void testByteCountToDisplaySizeLong() { assertEquals(FileUtils.byteCountToDisplaySize(0), "0 bytes"); assertEquals(FileUtils.byteCountToDisplaySize(1), "1 bytes"); assertEquals(FileUtils.byteCountToDisplaySize(1023), "1023 bytes"); assertEquals(FileUtils.byteCountToDisplaySize(1024), "1 KB"); assertEquals(FileUtils.byteCountToDisplaySize(1025), "1 KB"); assertEquals(FileUtils.byteCountToDisplaySize(1024 * 1023), "1023 KB"); assertEquals(FileUtils.byteCountToDisplaySize(1024 * 1024), "1 MB"); assertEquals(FileUtils.byteCountToDisplaySize(1024 * 1025), "1 MB"); assertEquals(FileUtils.byteCountToDisplaySize(1024 * 1024 * 1023), "1023 MB"); assertEquals(FileUtils.byteCountToDisplaySize(1024 * 1024 * 1024), "1 GB"); assertEquals(FileUtils.byteCountToDisplaySize(1024 * 1024 * 1025), "1 GB"); assertEquals(FileUtils.byteCountToDisplaySize(1024L * 1024 * 1024 * 2), "2 GB"); assertEquals(FileUtils.byteCountToDisplaySize(1024 * 1024 * 1024 * 2 - 1), "1 GB"); assertEquals(FileUtils.byteCountToDisplaySize(1024L * 1024 * 1024 * 1024), "1 TB"); assertEquals(FileUtils.byteCountToDisplaySize(1024L * 1024 * 1024 * 1024 * 1024), "1 PB"); assertEquals(FileUtils.byteCountToDisplaySize(1024L * 1024 * 1024 * 1024 * 1024 * 1024), "1 EB"); assertEquals(FileUtils.byteCountToDisplaySize(Long.MAX_VALUE), "7 EB"); // Other MAX_VALUEs assertEquals(FileUtils.byteCountToDisplaySize(Character.MAX_VALUE), "63 KB"); assertEquals(FileUtils.byteCountToDisplaySize(Short.MAX_VALUE), "31 KB"); assertEquals(FileUtils.byteCountToDisplaySize(Integer.MAX_VALUE), "1 GB"); } //----------------------------------------------------------------------- public void testToFile1() throws Exception { URL url = new URL("file", null, "a/b/c/file.txt"); File file = FileUtils.toFile(url); assertTrue(file.toString().indexOf("file.txt") >= 0); } public void testToFile2() throws Exception { URL url = new URL("file", null, "a/b/c/file%20n%61me%2520.tx%74"); File file = FileUtils.toFile(url); assertTrue(file.toString().indexOf("file name%20.txt") >= 0); } public void testToFile3() throws Exception { assertEquals(null, FileUtils.toFile((URL) null)); assertEquals(null, FileUtils.toFile(new URL("http://jakarta.apache.org"))); } public void testToFile4() throws Exception { URL url = new URL("file", null, "a/b/c/file%%20%me.txt%"); File file = FileUtils.toFile(url); assertTrue(file.toString().indexOf("file% %me.txt%") >= 0); } /** IO-252 */ public void testToFile5() throws Exception { URL url = new URL("file", null, "both%20are%20100%20%25%20true"); File file = FileUtils.toFile(url); assertEquals("both are 100 % true", file.toString()); } public void testToFileUtf8() throws Exception { URL url = new URL("file", null, "/home/%C3%A4%C3%B6%C3%BC%C3%9F"); File file = FileUtils.toFile(url); assertTrue(file.toString().indexOf("\u00E4\u00F6\u00FC\u00DF") >= 0); } public void testDecodeUrl() { assertEquals("", FileUtils.decodeUrl("")); assertEquals("foo", FileUtils.decodeUrl("foo")); assertEquals("+", FileUtils.decodeUrl("+")); assertEquals("% ", FileUtils.decodeUrl("%25%20")); assertEquals("%20", FileUtils.decodeUrl("%2520")); assertEquals("jar:file:/C:/dir/sub dir/1.0/foo-1.0.jar!/org/Bar.class", FileUtils .decodeUrl("jar:file:/C:/dir/sub%20dir/1.0/foo-1.0.jar!/org/Bar.class")); } public void testDecodeUrlLenient() { assertEquals(" ", FileUtils.decodeUrl(" ")); assertEquals("\u00E4\u00F6\u00FC\u00DF", FileUtils.decodeUrl("\u00E4\u00F6\u00FC\u00DF")); assertEquals("%", FileUtils.decodeUrl("%")); assertEquals("% ", FileUtils.decodeUrl("%%20")); assertEquals("%2", FileUtils.decodeUrl("%2")); assertEquals("%2G", FileUtils.decodeUrl("%2G")); } public void testDecodeUrlNullSafe() { assertNull(FileUtils.decodeUrl(null)); } public void testDecodeUrlEncodingUtf8() { assertEquals("\u00E4\u00F6\u00FC\u00DF", FileUtils.decodeUrl("%C3%A4%C3%B6%C3%BC%C3%9F")); } // toFiles public void testToFiles1() throws Exception { URL[] urls = new URL[] { new URL("file", null, "file1.txt"), new URL("file", null, "file2.txt"), }; File[] files = FileUtils.toFiles(urls); assertEquals(urls.length, files.length); assertEquals("File: " + files[0], true, files[0].toString().indexOf("file1.txt") >= 0); assertEquals("File: " + files[1], true, files[1].toString().indexOf("file2.txt") >= 0); } public void testToFiles2() throws Exception { URL[] urls = new URL[] { new URL("file", null, "file1.txt"), null, }; File[] files = FileUtils.toFiles(urls); assertEquals(urls.length, files.length); assertEquals("File: " + files[0], true, files[0].toString().indexOf("file1.txt") >= 0); assertEquals("File: " + files[1], null, files[1]); } public void testToFiles3() throws Exception { URL[] urls = null; File[] files = FileUtils.toFiles(urls); assertEquals(0, files.length); } public void testToFiles3a() throws Exception { URL[] urls = new URL[0]; // empty array File[] files = FileUtils.toFiles(urls); assertEquals(0, files.length); } public void testToFiles4() throws Exception { URL[] urls = new URL[] { new URL("file", null, "file1.txt"), new URL("http", "jakarta.apache.org", "file1.txt"), }; try { FileUtils.toFiles(urls); fail(); } catch (IllegalArgumentException ex) {} } // toURLs public void testToURLs1() throws Exception { File[] files = new File[] { new File(getTestDirectory(), "file1.txt"), new File(getTestDirectory(), "file2.txt"), new File(getTestDirectory(), "test file.txt"), }; URL[] urls = FileUtils.toURLs(files); assertEquals(files.length, urls.length); assertTrue(urls[0].toExternalForm().startsWith("file:")); assertTrue(urls[0].toExternalForm().indexOf("file1.txt") >= 0); assertTrue(urls[1].toExternalForm().startsWith("file:")); assertTrue(urls[1].toExternalForm().indexOf("file2.txt") >= 0); // Test escaped char assertTrue(urls[2].toExternalForm().startsWith("file:")); assertTrue(urls[2].toExternalForm().indexOf("test%20file.txt") >= 0); } // public void testToURLs2() throws Exception { // File[] files = new File[] { // new File(getTestDirectory(), "file1.txt"), // null, // }; // URL[] urls = FileUtils.toURLs(files); // // assertEquals(files.length, urls.length); // assertTrue(urls[0].toExternalForm().startsWith("file:")); // assertTrue(urls[0].toExternalForm().indexOf("file1.txt") > 0); // assertEquals(null, urls[1]); // } // // public void testToURLs3() throws Exception { // File[] files = null; // URL[] urls = FileUtils.toURLs(files); // // assertEquals(0, urls.length); // } public void testToURLs3a() throws Exception { File[] files = new File[0]; // empty array URL[] urls = FileUtils.toURLs(files); assertEquals(0, urls.length); } // contentEquals public void testContentEquals() throws Exception { // Non-existent files File file = new File(getTestDirectory(), getName()); File file2 = new File(getTestDirectory(), getName() + "2"); // both don't exist assertTrue(FileUtils.contentEquals(file, file)); assertTrue(FileUtils.contentEquals(file, file2)); assertTrue(FileUtils.contentEquals(file2, file2)); assertTrue(FileUtils.contentEquals(file2, file)); // Directories try { FileUtils.contentEquals(getTestDirectory(), getTestDirectory()); fail("Comparing directories should fail with an IOException"); } catch (IOException ioe) { //expected } // Different files File objFile1 = new File(getTestDirectory(), getName() + ".object"); objFile1.deleteOnExit(); FileUtils.copyURLToFile( getClass().getResource("/java/lang/Object.class"), objFile1); File objFile1b = new File(getTestDirectory(), getName() + ".object2"); objFile1.deleteOnExit(); FileUtils.copyURLToFile( getClass().getResource("/java/lang/Object.class"), objFile1b); File objFile2 = new File(getTestDirectory(), getName() + ".collection"); objFile2.deleteOnExit(); FileUtils.copyURLToFile( getClass().getResource("/java/util/Collection.class"), objFile2); assertFalse(FileUtils.contentEquals(objFile1, objFile2)); assertFalse(FileUtils.contentEquals(objFile1b, objFile2)); assertTrue(FileUtils.contentEquals(objFile1, objFile1b)); assertTrue(FileUtils.contentEquals(objFile1, objFile1)); assertTrue(FileUtils.contentEquals(objFile1b, objFile1b)); assertTrue(FileUtils.contentEquals(objFile2, objFile2)); // Equal files file.createNewFile(); file2.createNewFile(); assertTrue(FileUtils.contentEquals(file, file)); assertTrue(FileUtils.contentEquals(file, file2)); } public void testContentEqualsIgnoreEOL() throws Exception { // Non-existent files File file1 = new File(getTestDirectory(), getName()); File file2 = new File(getTestDirectory(), getName() + "2"); // both don't exist assertTrue(FileUtils.contentEqualsIgnoreEOL(file1, file1, null)); assertTrue(FileUtils.contentEqualsIgnoreEOL(file1, file2, null)); assertTrue(FileUtils.contentEqualsIgnoreEOL(file2, file2, null)); assertTrue(FileUtils.contentEqualsIgnoreEOL(file2, file1, null)); // Directories try { FileUtils.contentEqualsIgnoreEOL(getTestDirectory(), getTestDirectory(), null); fail("Comparing directories should fail with an IOException"); } catch (IOException ioe) { //expected } // Different files File tfile1 = new File(getTestDirectory(), getName() + ".txt1"); tfile1.deleteOnExit(); FileUtils.write(tfile1,"123\r"); File tfile2 = new File(getTestDirectory(), getName() + ".txt2"); tfile1.deleteOnExit(); FileUtils.write(tfile2,"123\n"); File tfile3 = new File(getTestDirectory(), getName() + ".collection"); tfile3.deleteOnExit(); FileUtils.write(tfile3,"123\r\n2"); assertTrue(FileUtils.contentEqualsIgnoreEOL(tfile1, tfile1, null)); assertTrue(FileUtils.contentEqualsIgnoreEOL(tfile2, tfile2, null)); assertTrue(FileUtils.contentEqualsIgnoreEOL(tfile3, tfile3, null)); assertTrue(FileUtils.contentEqualsIgnoreEOL(tfile1, tfile2, null)); assertFalse(FileUtils.contentEqualsIgnoreEOL(tfile1, tfile3, null)); assertFalse(FileUtils.contentEqualsIgnoreEOL(tfile2, tfile3, null)); URL urlCR = getClass().getResource("FileUtilsTestDataCR.dat"); assertNotNull(urlCR); File cr = new File(urlCR.getPath()); assertTrue(cr.exists()); URL urlCRLF = getClass().getResource("FileUtilsTestDataCRLF.dat"); assertNotNull(urlCRLF); File crlf = new File(urlCRLF.getPath()); assertTrue(crlf.exists()); URL urlLF = getClass().getResource("FileUtilsTestDataLF.dat"); assertNotNull(urlLF); File lf = new File(urlLF.getPath()); assertTrue(lf.exists()); assertTrue(FileUtils.contentEqualsIgnoreEOL(cr, cr, null)); assertTrue(FileUtils.contentEqualsIgnoreEOL(crlf, crlf, null)); assertTrue(FileUtils.contentEqualsIgnoreEOL(lf, lf, null)); assertTrue(FileUtils.contentEqualsIgnoreEOL(cr, crlf, null)); assertTrue(FileUtils.contentEqualsIgnoreEOL(cr, lf, null)); assertTrue(FileUtils.contentEqualsIgnoreEOL(crlf, lf, null)); // Check the files behave OK when EOL is not ignored assertTrue(FileUtils.contentEquals(cr, cr)); assertTrue(FileUtils.contentEquals(crlf, crlf)); assertTrue(FileUtils.contentEquals(lf, lf)); assertFalse(FileUtils.contentEquals(cr, crlf)); assertFalse(FileUtils.contentEquals(cr, lf)); assertFalse(FileUtils.contentEquals(crlf, lf)); // Equal files file1.createNewFile(); file2.createNewFile(); assertTrue(FileUtils.contentEqualsIgnoreEOL(file1, file1, null)); assertTrue(FileUtils.contentEqualsIgnoreEOL(file1, file2, null)); } // copyURLToFile public void testCopyURLToFile() throws Exception { // Creates file File file = new File(getTestDirectory(), getName()); file.deleteOnExit(); // Loads resource String resourceName = "/java/lang/Object.class"; FileUtils.copyURLToFile(getClass().getResource(resourceName), file); // Tests that resuorce was copied correctly FileInputStream fis = new FileInputStream(file); try { assertTrue( "Content is not equal.", IOUtils.contentEquals( getClass().getResourceAsStream(resourceName), fis)); } finally { fis.close(); } //TODO Maybe test copy to itself like for copyFile() } public void testCopyURLToFileWithTimeout() throws Exception { // Creates file File file = new File(getTestDirectory(), "testCopyURLToFileWithTimeout"); file.deleteOnExit(); // Loads resource String resourceName = "/java/lang/Object.class"; FileUtils.copyURLToFile(getClass().getResource(resourceName), file, 500, 500); // Tests that resuorce was copied correctly FileInputStream fis = new FileInputStream(file); try { assertTrue( "Content is not equal.", IOUtils.contentEquals( getClass().getResourceAsStream(resourceName), fis)); } finally { fis.close(); } //TODO Maybe test copy to itself like for copyFile() } // forceMkdir public void testForceMkdir() throws Exception { // Tests with existing directory FileUtils.forceMkdir(getTestDirectory()); // Creates test file File testFile = new File(getTestDirectory(), getName()); testFile.deleteOnExit(); testFile.createNewFile(); assertTrue("Test file does not exist.", testFile.exists()); // Tests with existing file try { FileUtils.forceMkdir(testFile); fail("Exception expected."); } catch (IOException ex) {} testFile.delete(); // Tests with non-existent directory FileUtils.forceMkdir(testFile); assertTrue("Directory was not created.", testFile.exists()); } // sizeOfDirectory public void testSizeOfDirectory() throws Exception { File file = new File(getTestDirectory(), getName()); // Non-existent file try { FileUtils.sizeOfDirectory(file); fail("Exception expected."); } catch (IllegalArgumentException ex) {} // Creates file file.createNewFile(); file.deleteOnExit(); // Existing file try { FileUtils.sizeOfDirectory(file); fail("Exception expected."); } catch (IllegalArgumentException ex) {} // Existing directory file.delete(); file.mkdir(); // Create a cyclic symlink this.createCircularSymLink(file); assertEquals( "Unexpected directory size", TEST_DIRECTORY_SIZE, FileUtils.sizeOfDirectory(file)); } private void createCircularSymLink(File file) throws IOException { if(!FilenameUtils.isSystemWindows()) { Runtime.getRuntime() .exec("ln -s " + file + "/.. " + file + "/cycle"); } else { try { Runtime.getRuntime() .exec("mklink /D " + file + "/cycle" + file + "/.. "); } catch(IOException ioe) { // So that tests run in FAT filesystems //don't fail } } } public void testSizeOfDirectoryAsBigInteger() throws Exception { File file = new File(getTestDirectory(), getName()); // Non-existent file try { FileUtils.sizeOfDirectoryAsBigInteger(file); fail("Exception expected."); } catch (IllegalArgumentException ex) { } // Creates file file.createNewFile(); file.deleteOnExit(); // Existing file try { FileUtils.sizeOfDirectoryAsBigInteger(file); fail("Exception expected."); } catch (IllegalArgumentException ex) { } // Existing directory file.delete(); file.mkdir(); this.createCircularSymLink(file); assertEquals("Unexpected directory size", TEST_DIRECTORY_SIZE_BI, FileUtils.sizeOfDirectoryAsBigInteger(file)); // Existing directory which size is greater than zero file.delete(); file.mkdir(); File nonEmptyFile = new File(file, "nonEmptyFile" + System.nanoTime()); this.createFile(nonEmptyFile, TEST_DIRECTORY_SIZE_GT_ZERO_BI.longValue()); nonEmptyFile.deleteOnExit(); assertEquals("Unexpected directory size", TEST_DIRECTORY_SIZE_GT_ZERO_BI, FileUtils.sizeOfDirectoryAsBigInteger(file)); nonEmptyFile.delete(); file.delete(); } /** * Tests the {@link FileUtils#sizeOf(File)} method. * @throws Exception */ public void testSizeOf() throws Exception { File file = new File(getTestDirectory(), getName()); // Null argument try { FileUtils.sizeOf(null); fail("Exception expected."); } catch (NullPointerException ex) {} // Non-existent file try { FileUtils.sizeOf(file); fail("Exception expected."); } catch (IllegalArgumentException ex) {} // Creates file file.createNewFile(); file.deleteOnExit(); // New file assertEquals(0, FileUtils.sizeOf(file)); file.delete(); // Existing file assertEquals("Unexpected files size", testFile1Size, FileUtils.sizeOf(testFile1)); // Existing directory assertEquals("Unexpected directory size", TEST_DIRECTORY_SIZE, FileUtils.sizeOf(getTestDirectory())); } /** * Tests the {@link FileUtils#sizeOf(File)} method. * @throws Exception */ public void testSizeOfAsBigInteger() throws Exception { File file = new File(getTestDirectory(), getName()); // Null argument try { FileUtils.sizeOfAsBigInteger(null); fail("Exception expected."); } catch (NullPointerException ex) {} // Non-existent file try { FileUtils.sizeOfAsBigInteger(file); fail("Exception expected."); } catch (IllegalArgumentException ex) {} // Creates file file.createNewFile(); file.deleteOnExit(); // New file assertEquals(BigInteger.ZERO, FileUtils.sizeOfAsBigInteger(file)); file.delete(); // Existing file assertEquals("Unexpected files size", BigInteger.valueOf(testFile1Size), FileUtils.sizeOfAsBigInteger(testFile1)); // Existing directory assertEquals("Unexpected directory size", TEST_DIRECTORY_SIZE_BI, FileUtils.sizeOfAsBigInteger(getTestDirectory())); } // isFileNewer / isFileOlder public void testIsFileNewerOlder() throws Exception { File reference = new File(getTestDirectory(), "FileUtils-reference.txt"); File oldFile = new File(getTestDirectory(), "FileUtils-old.txt"); File newFile = new File(getTestDirectory(), "FileUtils-new.txt"); File invalidFile = new File(getTestDirectory(), "FileUtils-invalid-file.txt"); // Create Files createFile(oldFile, 0); do { try { Thread.sleep(1000); } catch(InterruptedException ie) { // ignore } createFile(reference, 0); } while( oldFile.lastModified() == reference.lastModified() ); Date date = new Date(); long now = date.getTime(); do { try { Thread.sleep(1000); } catch(InterruptedException ie) { // ignore } createFile(newFile, 0); } while( reference.lastModified() == newFile.lastModified() ); // Test isFileNewer() assertFalse("Old File - Newer - File", FileUtils.isFileNewer(oldFile, reference)); assertFalse("Old File - Newer - Date", FileUtils.isFileNewer(oldFile, date)); assertFalse("Old File - Newer - Mili", FileUtils.isFileNewer(oldFile, now)); assertTrue("New File - Newer - File", FileUtils.isFileNewer(newFile, reference)); assertTrue("New File - Newer - Date", FileUtils.isFileNewer(newFile, date)); assertTrue("New File - Newer - Mili", FileUtils.isFileNewer(newFile, now)); assertFalse("Invalid - Newer - File", FileUtils.isFileNewer(invalidFile, reference)); final String invalidFileName = invalidFile.getName(); try { FileUtils.isFileNewer(newFile, invalidFile); fail("Should have cause IllegalArgumentException"); } catch (IllegalArgumentException iae){ final String message = iae.getMessage(); assertTrue("Message should contain: "+invalidFileName+ " but was: "+message,message.contains(invalidFileName)); } // Test isFileOlder() assertTrue("Old File - Older - File", FileUtils.isFileOlder(oldFile, reference)); assertTrue("Old File - Older - Date", FileUtils.isFileOlder(oldFile, date)); assertTrue("Old File - Older - Mili", FileUtils.isFileOlder(oldFile, now)); assertFalse("New File - Older - File", FileUtils.isFileOlder(newFile, reference)); assertFalse("New File - Older - Date", FileUtils.isFileOlder(newFile, date)); assertFalse("New File - Older - Mili", FileUtils.isFileOlder(newFile, now)); assertFalse("Invalid - Older - File", FileUtils.isFileOlder(invalidFile, reference)); try { FileUtils.isFileOlder(newFile, invalidFile); fail("Should have cause IllegalArgumentException"); } catch (IllegalArgumentException iae){ final String message = iae.getMessage(); assertTrue("Message should contain: "+invalidFileName+ " but was: "+message,message.contains(invalidFileName)); } // ----- Test isFileNewer() exceptions ----- // Null File try { FileUtils.isFileNewer(null, now); fail("Newer Null, expected IllegalArgumentExcepion"); } catch (IllegalArgumentException expected) { // expected result } // Null reference File try { FileUtils.isFileNewer(oldFile, (File)null); fail("Newer Null reference, expected IllegalArgumentExcepion"); } catch (IllegalArgumentException expected) { // expected result } // Invalid reference File try { FileUtils.isFileNewer(oldFile, invalidFile); fail("Newer invalid reference, expected IllegalArgumentExcepion"); } catch (IllegalArgumentException expected) { // expected result } // Null reference Date try { FileUtils.isFileNewer(oldFile, (Date)null); fail("Newer Null date, expected IllegalArgumentExcepion"); } catch (IllegalArgumentException expected) { // expected result } // ----- Test isFileOlder() exceptions ----- // Null File try { FileUtils.isFileOlder(null, now); fail("Older Null, expected IllegalArgumentExcepion"); } catch (IllegalArgumentException expected) { // expected result } // Null reference File try { FileUtils.isFileOlder(oldFile, (File)null); fail("Older Null reference, expected IllegalArgumentExcepion"); } catch (IllegalArgumentException expected) { // expected result } // Invalid reference File try { FileUtils.isFileOlder(oldFile, invalidFile); fail("Older invalid reference, expected IllegalArgumentExcepion"); } catch (IllegalArgumentException expected) { // expected result } // Null reference Date try { FileUtils.isFileOlder(oldFile, (Date)null); fail("Older Null date, expected IllegalArgumentExcepion"); } catch (IllegalArgumentException expected) { // expected result } } // // TODO Remove after debugging // private void log(Object obj) { // System.out.println( // FileUtilsTestCase.class +" " + getName() + " " + obj); // } // copyFile public void testCopyFile1() throws Exception { File destination = new File(getTestDirectory(), "copy1.txt"); //Thread.sleep(LAST_MODIFIED_DELAY); //This is to slow things down so we can catch if //the lastModified date is not ok FileUtils.copyFile(testFile1, destination); assertTrue("Check Exist", destination.exists()); assertEquals("Check Full copy", testFile1Size, destination.length()); /* disabled: Thread.sleep doesn't work reliantly for this case assertTrue("Check last modified date preserved", testFile1.lastModified() == destination.lastModified());*/ } public void testCopyFileToOutputStream() throws Exception { ByteArrayOutputStream destination = new ByteArrayOutputStream(); FileUtils.copyFile(testFile1, destination); assertEquals("Check Full copy size", testFile1Size, destination.size()); byte[] expected = FileUtils.readFileToByteArray(testFile1); Assert.assertArrayEquals("Check Full copy", expected, destination.toByteArray()); } public void IGNOREtestCopyFileLarge() throws Exception { File largeFile = new File(getTestDirectory(), "large.txt"); File destination = new File(getTestDirectory(), "copylarge.txt"); System.out.println("START: " + new java.util.Date()); createFile(largeFile, FileUtils.ONE_GB); System.out.println("CREATED: " + new java.util.Date()); FileUtils.copyFile(largeFile, destination); System.out.println("COPIED: " + new java.util.Date()); assertTrue("Check Exist", destination.exists()); assertEquals("Check Full copy", largeFile.length(), destination.length()); } public void testCopyFile2() throws Exception { File destination = new File(getTestDirectory(), "copy2.txt"); //Thread.sleep(LAST_MODIFIED_DELAY); //This is to slow things down so we can catch if //the lastModified date is not ok FileUtils.copyFile(testFile1, destination); assertTrue("Check Exist", destination.exists()); assertEquals("Check Full copy", testFile2Size, destination.length()); /* disabled: Thread.sleep doesn't work reliably for this case assertTrue("Check last modified date preserved", testFile1.lastModified() == destination.lastModified());*/ } public void testCopyToSelf() throws Exception { File destination = new File(getTestDirectory(), "copy3.txt"); //Prepare a test file FileUtils.copyFile(testFile1, destination); try { FileUtils.copyFile(destination, destination); fail("file copy to self should not be possible"); } catch (IOException ioe) { //we want the exception, copy to self should be illegal } } public void testCopyFile2WithoutFileDatePreservation() throws Exception { File destination = new File(getTestDirectory(), "copy2.txt"); //Thread.sleep(LAST_MODIFIED_DELAY); //This is to slow things down so we can catch if //the lastModified date is not ok FileUtils.copyFile(testFile1, destination, false); assertTrue("Check Exist", destination.exists()); assertEquals("Check Full copy", testFile2Size, destination.length()); /* disabled: Thread.sleep doesn't work reliantly for this case assertTrue("Check last modified date modified", testFile1.lastModified() != destination.lastModified());*/ } public void testCopyDirectoryToDirectory_NonExistingDest() throws Exception { createFile(testFile1, 1234); createFile(testFile2, 4321); File srcDir = getTestDirectory(); File subDir = new File(srcDir, "sub"); subDir.mkdir(); File subFile = new File(subDir, "A.txt"); FileUtils.writeStringToFile(subFile, "HELLO WORLD", "UTF8"); File destDir = new File(System.getProperty("java.io.tmpdir"), "tmp-FileUtilsTestCase"); FileUtils.deleteDirectory(destDir); File actualDestDir = new File(destDir, srcDir.getName()); FileUtils.copyDirectoryToDirectory(srcDir, destDir); assertTrue("Check exists", destDir.exists()); assertTrue("Check exists", actualDestDir.exists()); long srcSize = FileUtils.sizeOfDirectory(srcDir); assertTrue("Size > 0", srcSize > 0); assertEquals("Check size", srcSize, FileUtils.sizeOfDirectory(actualDestDir)); assertTrue(new File(actualDestDir, "sub/A.txt").exists()); FileUtils.deleteDirectory(destDir); } public void testCopyDirectoryToNonExistingDest() throws Exception { createFile(testFile1, 1234); createFile(testFile2, 4321); File srcDir = getTestDirectory(); File subDir = new File(srcDir, "sub"); subDir.mkdir(); File subFile = new File(subDir, "A.txt"); FileUtils.writeStringToFile(subFile, "HELLO WORLD", "UTF8"); File destDir = new File(System.getProperty("java.io.tmpdir"), "tmp-FileUtilsTestCase"); FileUtils.deleteDirectory(destDir); FileUtils.copyDirectory(srcDir, destDir); assertTrue("Check exists", destDir.exists()); long sizeOfSrcDirectory = FileUtils.sizeOfDirectory(srcDir); assertTrue("Size > 0",sizeOfSrcDirectory > 0); assertEquals("Check size", sizeOfSrcDirectory, FileUtils.sizeOfDirectory(destDir)); assertTrue(new File(destDir, "sub/A.txt").exists()); FileUtils.deleteDirectory(destDir); } public void testCopyDirectoryToExistingDest() throws Exception { createFile(testFile1, 1234); createFile(testFile2, 4321); File srcDir = getTestDirectory(); File subDir = new File(srcDir, "sub"); subDir.mkdir(); File subFile = new File(subDir, "A.txt"); FileUtils.writeStringToFile(subFile, "HELLO WORLD", "UTF8"); File destDir = new File(System.getProperty("java.io.tmpdir"), "tmp-FileUtilsTestCase"); FileUtils.deleteDirectory(destDir); destDir.mkdirs(); FileUtils.copyDirectory(srcDir, destDir); long srcSize = FileUtils.sizeOfDirectory(srcDir); assertTrue("Size > 0",srcSize > 0); assertEquals(srcSize, FileUtils.sizeOfDirectory(destDir)); assertTrue(new File(destDir, "sub/A.txt").exists()); } public void testCopyDirectoryFiltered() throws Exception { File grandParentDir = new File(getTestDirectory(), "grandparent"); File parentDir = new File(grandParentDir, "parent"); File childDir = new File(parentDir, "child"); createFilesForTestCopyDirectory(grandParentDir, parentDir, childDir); NameFileFilter filter = new NameFileFilter(new String[] {"parent", "child", "file3.txt"}); File destDir = new File(getTestDirectory(), "copydest"); FileUtils.copyDirectory(grandParentDir, destDir, filter); List files = LIST_WALKER.list(destDir); assertEquals(3, files.size()); assertEquals("parent", files.get(0).getName()); assertEquals("child", files.get(1).getName()); assertEquals("file3.txt", files.get(2).getName()); } public void testCopyDirectoryPreserveDates() throws Exception { File source = new File(getTestDirectory(), "source"); File sourceDirectory = new File(source, "directory"); File sourceFile = new File(sourceDirectory, "hello.txt"); // Prepare source data source.mkdirs(); sourceDirectory.mkdir(); FileUtils.writeStringToFile(sourceFile, "HELLO WORLD", "UTF8"); // Set dates in reverse order to avoid overwriting previous values // Also, use full seconds (arguments are in ms) close to today // but still highly unlikely to occur in the real world sourceFile.setLastModified(1000000002000L); sourceDirectory.setLastModified(1000000001000L); source.setLastModified(1000000000000L); File target = new File(getTestDirectory(), "target"); File targetDirectory = new File(target, "directory"); File targetFile = new File(targetDirectory, "hello.txt"); // Test with preserveFileDate disabled FileUtils.copyDirectory(source, target, false); assertTrue(1000000000000L != target.lastModified()); assertTrue(1000000001000L != targetDirectory.lastModified()); assertTrue(1000000002000L != targetFile.lastModified()); FileUtils.deleteDirectory(target); // Test with preserveFileDate enabled FileUtils.copyDirectory(source, target, true); assertEquals(1000000000000L, target.lastModified()); assertEquals(1000000001000L, targetDirectory.lastModified()); assertEquals(1000000002000L, targetFile.lastModified()); FileUtils.deleteDirectory(target); // also if the target directory already exists (IO-190) target.mkdirs(); FileUtils.copyDirectory(source, target, true); assertEquals(1000000000000L, target.lastModified()); assertEquals(1000000001000L, targetDirectory.lastModified()); assertEquals(1000000002000L, targetFile.lastModified()); FileUtils.deleteDirectory(target); // also if the target subdirectory already exists (IO-190) targetDirectory.mkdirs(); FileUtils.copyDirectory(source, target, true); assertEquals(1000000000000L, target.lastModified()); assertEquals(1000000001000L, targetDirectory.lastModified()); assertEquals(1000000002000L, targetFile.lastModified()); FileUtils.deleteDirectory(target); } /** Test for IO-141 */ public void testCopyDirectoryToChild() throws Exception { File grandParentDir = new File(getTestDirectory(), "grandparent"); File parentDir = new File(grandParentDir, "parent"); File childDir = new File(parentDir, "child"); createFilesForTestCopyDirectory(grandParentDir, parentDir, childDir); long expectedCount = LIST_WALKER.list(grandParentDir).size() + LIST_WALKER.list(parentDir).size(); long expectedSize = FileUtils.sizeOfDirectory(grandParentDir) + FileUtils.sizeOfDirectory(parentDir); FileUtils.copyDirectory(parentDir, childDir); assertEquals(expectedCount, LIST_WALKER.list(grandParentDir).size()); assertEquals(expectedSize, FileUtils.sizeOfDirectory(grandParentDir)); assertTrue("Count > 0", expectedCount > 0); assertTrue("Size > 0", expectedSize > 0); } /** Test for IO-141 */ public void testCopyDirectoryToGrandChild() throws Exception { File grandParentDir = new File(getTestDirectory(), "grandparent"); File parentDir = new File(grandParentDir, "parent"); File childDir = new File(parentDir, "child"); createFilesForTestCopyDirectory(grandParentDir, parentDir, childDir); long expectedCount = LIST_WALKER.list(grandParentDir).size() * 2; long expectedSize = FileUtils.sizeOfDirectory(grandParentDir) * 2; FileUtils.copyDirectory(grandParentDir, childDir); assertEquals(expectedCount, LIST_WALKER.list(grandParentDir).size()); assertEquals(expectedSize, FileUtils.sizeOfDirectory(grandParentDir)); assertTrue("Size > 0",expectedSize > 0); } /** Test for IO-217 FileUtils.copyDirectoryToDirectory makes infinite loops */ public void testCopyDirectoryToItself() throws Exception { File dir = new File(getTestDirectory(), "itself"); dir.mkdirs(); FileUtils.copyDirectoryToDirectory(dir, dir); assertEquals(1, LIST_WALKER.list(dir).size()); } private void createFilesForTestCopyDirectory(File grandParentDir, File parentDir, File childDir) throws Exception { File childDir2 = new File(parentDir, "child2"); File grandChildDir = new File(childDir, "grandChild"); File grandChild2Dir = new File(childDir2, "grandChild2"); File file1 = new File(grandParentDir, "file1.txt"); File file2 = new File(parentDir, "file2.txt"); File file3 = new File(childDir, "file3.txt"); File file4 = new File(childDir2, "file4.txt"); File file5 = new File(grandChildDir, "file5.txt"); File file6 = new File(grandChild2Dir, "file6.txt"); FileUtils.deleteDirectory(grandParentDir); grandChildDir.mkdirs(); grandChild2Dir.mkdirs(); FileUtils.writeStringToFile(file1, "File 1 in grandparent", "UTF8"); FileUtils.writeStringToFile(file2, "File 2 in parent", "UTF8"); FileUtils.writeStringToFile(file3, "File 3 in child", "UTF8"); FileUtils.writeStringToFile(file4, "File 4 in child2", "UTF8"); FileUtils.writeStringToFile(file5, "File 5 in grandChild", "UTF8"); FileUtils.writeStringToFile(file6, "File 6 in grandChild2", "UTF8"); } public void testCopyDirectoryErrors() throws Exception { try { FileUtils.copyDirectory(null, null); fail(); } catch (NullPointerException ex) {} try { FileUtils.copyDirectory(new File("a"), null); fail(); } catch (NullPointerException ex) {} try { FileUtils.copyDirectory(null, new File("a")); fail(); } catch (NullPointerException ex) {} try { FileUtils.copyDirectory(new File("doesnt-exist"), new File("a")); fail(); } catch (IOException ex) {} try { FileUtils.copyDirectory(testFile1, new File("a")); fail(); } catch (IOException ex) {} try { FileUtils.copyDirectory(getTestDirectory(), testFile1); fail(); } catch (IOException ex) {} try { FileUtils.copyDirectory(getTestDirectory(), getTestDirectory()); fail(); } catch (IOException ex) {} } // forceDelete public void testForceDeleteAFile1() throws Exception { File destination = new File(getTestDirectory(), "copy1.txt"); destination.createNewFile(); assertTrue("Copy1.txt doesn't exist to delete", destination.exists()); FileUtils.forceDelete(destination); assertTrue("Check No Exist", !destination.exists()); } public void testForceDeleteAFile2() throws Exception { File destination = new File(getTestDirectory(), "copy2.txt"); destination.createNewFile(); assertTrue("Copy2.txt doesn't exist to delete", destination.exists()); FileUtils.forceDelete(destination); assertTrue("Check No Exist", !destination.exists()); } public void testForceDeleteAFile3() throws Exception { File destination = new File(getTestDirectory(), "no_such_file"); assertTrue("Check No Exist", !destination.exists()); try { FileUtils.forceDelete(destination); fail("Should generate FileNotFoundException"); } catch (FileNotFoundException ignored){ } } // copyFileToDirectory public void testCopyFile1ToDir() throws Exception { File directory = new File(getTestDirectory(), "subdir"); if (!directory.exists()) { directory.mkdirs(); } File destination = new File(directory, testFile1.getName()); //Thread.sleep(LAST_MODIFIED_DELAY); //This is to slow things down so we can catch if //the lastModified date is not ok FileUtils.copyFileToDirectory(testFile1, directory); assertTrue("Check Exist", destination.exists()); assertEquals("Check Full copy", testFile1Size, destination.length()); /* disabled: Thread.sleep doesn't work reliantly for this case assertTrue("Check last modified date preserved", testFile1.lastModified() == destination.lastModified());*/ try { FileUtils.copyFileToDirectory(destination, directory); fail("Should not be able to copy a file into the same directory as itself"); } catch (IOException ioe) { //we want that, cannot copy to the same directory as the original file } } public void testCopyFile2ToDir() throws Exception { File directory = new File(getTestDirectory(), "subdir"); if (!directory.exists()) { directory.mkdirs(); } File destination = new File(directory, testFile1.getName()); //Thread.sleep(LAST_MODIFIED_DELAY); //This is to slow things down so we can catch if //the lastModified date is not ok FileUtils.copyFileToDirectory(testFile1, directory); assertTrue("Check Exist", destination.exists()); assertEquals("Check Full copy", testFile2Size, destination.length()); /* disabled: Thread.sleep doesn't work reliantly for this case assertTrue("Check last modified date preserved", testFile1.lastModified() == destination.lastModified());*/ } // forceDelete public void testForceDeleteDir() throws Exception { File testDirectory = getTestDirectory(); FileUtils.forceDelete(testDirectory.getParentFile()); assertTrue( "Check No Exist", !testDirectory.getParentFile().exists()); } /** * Test the FileUtils implementation. */ public void testFileUtils() throws Exception { // Loads file from classpath File file1 = new File(getTestDirectory(), "test.txt"); String filename = file1.getAbsolutePath(); //Create test file on-the-fly (used to be in CVS) OutputStream out = new java.io.FileOutputStream(file1); try { out.write("This is a test".getBytes("UTF-8")); } finally { out.close(); } File file2 = new File(getTestDirectory(), "test2.txt"); FileUtils.writeStringToFile(file2, filename, "UTF-8"); assertTrue(file2.exists()); assertTrue(file2.length() > 0); String file2contents = FileUtils.readFileToString(file2, "UTF-8"); assertTrue( "Second file's contents correct", filename.equals(file2contents)); assertTrue(file2.delete()); String contents = FileUtils.readFileToString(new File(filename), "UTF-8"); assertEquals("FileUtils.fileRead()", "This is a test", contents); } public void testTouch() throws IOException { File file = new File(getTestDirectory(), "touch.txt") ; if (file.exists()) { file.delete(); } assertTrue("Bad test: test file still exists", !file.exists()); FileUtils.touch(file); assertTrue("FileUtils.touch() created file", file.exists()); FileOutputStream out = new FileOutputStream(file) ; assertEquals("Created empty file.", 0, file.length()); out.write(0) ; out.close(); assertEquals("Wrote one byte to file", 1, file.length()); long y2k = new GregorianCalendar(2000, 0, 1).getTime().getTime(); boolean res = file.setLastModified(y2k); // 0L fails on Win98 assertEquals("Bad test: set lastModified failed", true, res); assertEquals("Bad test: set lastModified set incorrect value", y2k, file.lastModified()); long now = System.currentTimeMillis(); FileUtils.touch(file) ; assertEquals("FileUtils.touch() didn't empty the file.", 1, file.length()); assertEquals("FileUtils.touch() changed lastModified", false, y2k == file.lastModified()); assertEquals("FileUtils.touch() changed lastModified to more than now-3s", true, file.lastModified() >= now - 3000); assertEquals("FileUtils.touch() changed lastModified to less than now+3s", true, file.lastModified() <= now + 3000); } public void testListFiles() throws Exception { File srcDir = getTestDirectory(); File subDir = new File(srcDir, "list_test" ); subDir.mkdir(); File subDir2 = new File(subDir, "subdir" ); subDir2.mkdir(); String[] fileNames = {"a.txt", "b.txt", "c.txt", "d.txt", "e.txt", "f.txt"}; int[] fileSizes = {123, 234, 345, 456, 678, 789}; for (int i = 0; i < fileNames.length; ++i) { File theFile = new File(subDir, fileNames[i]); createFile(theFile, fileSizes[i]); } Collection files = FileUtils.listFiles(subDir, new WildcardFileFilter("*.*"), new WildcardFileFilter("*")); int count = files.size(); Object[] fileObjs = files.toArray(); assertEquals(fileNames.length, files.size()); Map foundFileNames = new HashMap(); for (int i = 0; i < count; ++i) { boolean found = false; for(int j = 0; !found && j < fileNames.length; ++j) { if ( fileNames[j].equals(((File) fileObjs[i]).getName())) { foundFileNames.put(fileNames[j], fileNames[j]); found = true; } } } assertEquals(foundFileNames.size(), fileNames.length); subDir.delete(); } public void testListFilesWithDirs() throws IOException { File srcDir = getTestDirectory(); File subDir1 = new File(srcDir, "subdir"); subDir1.mkdir(); File subDir2 = new File(subDir1, "subdir2"); subDir2.mkdir(); File someFile = new File(subDir2, "a.txt"); createFile(someFile, 100); File subDir3 = new File(subDir2, "subdir3"); subDir3.mkdir(); Collection files = FileUtils.listFilesAndDirs(subDir1, new WildcardFileFilter("*.*"), new WildcardFileFilter("*")); assertEquals(4, files.size()); assertTrue("Should contain the directory.", files.contains(subDir1)); assertTrue("Should contain the directory.", files.contains(subDir2)); assertTrue("Should contain the file.", files.contains(someFile)); assertTrue("Should contain the directory.", files.contains(subDir3)); subDir1.delete(); } public void testIterateFiles() throws Exception { File srcDir = getTestDirectory(); File subDir = new File(srcDir, "list_test" ); subDir.mkdir(); String[] fileNames = {"a.txt", "b.txt", "c.txt", "d.txt", "e.txt", "f.txt"}; int[] fileSizes = {123, 234, 345, 456, 678, 789}; for (int i = 0; i < fileNames.length; ++i) { File theFile = new File(subDir, fileNames[i]); createFile(theFile, fileSizes[i]); } Iterator files = FileUtils.iterateFiles(subDir, new WildcardFileFilter("*.*"), new WildcardFileFilter("*")); Map foundFileNames = new HashMap(); while (files.hasNext()) { boolean found = false; String fileName = files.next().getName(); for (int j = 0; !found && j < fileNames.length; ++j) { if ( fileNames[j].equals(fileName)) { foundFileNames.put(fileNames[j], fileNames[j]); found = true; } } } assertEquals(foundFileNames.size(), fileNames.length); subDir.delete(); } public void testIterateFilesAndDirs() throws IOException { File srcDir = getTestDirectory(); File subDir1 = new File(srcDir, "subdir"); subDir1.mkdir(); File subDir2 = new File(subDir1, "subdir2"); subDir2.mkdir(); File someFile = new File(subDir2, "a.txt"); createFile(someFile, 100); File subDir3 = new File(subDir2, "subdir3"); subDir3.mkdir(); Collection filesAndDirs = Arrays.asList(subDir1, subDir2, someFile, subDir3); int filesCount = 0; Iterator files = FileUtils.iterateFilesAndDirs(subDir1, new WildcardFileFilter("*.*"), new WildcardFileFilter("*")); while (files.hasNext()) { filesCount++; File file = files.next(); assertTrue("Should contain the directory/file", filesAndDirs.contains(file)); } assertEquals(filesCount, filesAndDirs.size()); } public void testReadFileToStringWithDefaultEncoding() throws Exception { File file = new File(getTestDirectory(), "read.obj"); FileOutputStream out = new FileOutputStream(file); byte[] text = "Hello /u1234".getBytes(); out.write(text); out.close(); String data = FileUtils.readFileToString(file); assertEquals("Hello /u1234", data); } public void testReadFileToStringWithEncoding() throws Exception { File file = new File(getTestDirectory(), "read.obj"); FileOutputStream out = new FileOutputStream(file); byte[] text = "Hello /u1234".getBytes("UTF8"); out.write(text); out.close(); String data = FileUtils.readFileToString(file, "UTF8"); assertEquals("Hello /u1234", data); } public void testReadFileToByteArray() throws Exception { File file = new File(getTestDirectory(), "read.txt"); FileOutputStream out = new FileOutputStream(file); out.write(11); out.write(21); out.write(31); out.close(); byte[] data = FileUtils.readFileToByteArray(file); assertEquals(3, data.length); assertEquals(11, data[0]); assertEquals(21, data[1]); assertEquals(31, data[2]); } public void testReadLines() throws Exception { File file = newFile("lines.txt"); try { String[] data = new String[] {"hello", "/u1234", "", "this is", "some text"}; createLineBasedFile(file, data); List lines = FileUtils.readLines(file, "UTF-8"); assertEquals(Arrays.asList(data), lines); } finally { deleteFile(file); } } public void testWriteStringToFile1() throws Exception { File file = new File(getTestDirectory(), "write.txt"); FileUtils.writeStringToFile(file, "Hello /u1234", "UTF8"); byte[] text = "Hello /u1234".getBytes("UTF8"); assertEqualContent(text, file); } public void testWriteStringToFile2() throws Exception { File file = new File(getTestDirectory(), "write.txt"); FileUtils.writeStringToFile(file, "Hello /u1234", (String)null); byte[] text = "Hello /u1234".getBytes(); assertEqualContent(text, file); } public void testWriteStringToFile3() throws Exception { File file = new File(getTestDirectory(), "write.txt"); FileUtils.writeStringToFile(file, "Hello /u1234", (Charset)null); byte[] text = "Hello /u1234".getBytes(); assertEqualContent(text, file); } public void testWriteCharSequence1() throws Exception { File file = new File(getTestDirectory(), "write.txt"); FileUtils.write(file, "Hello /u1234", "UTF8"); byte[] text = "Hello /u1234".getBytes("UTF8"); assertEqualContent(text, file); } public void testWriteCharSequence2() throws Exception { File file = new File(getTestDirectory(), "write.txt"); FileUtils.write(file, "Hello /u1234", (String) null); byte[] text = "Hello /u1234".getBytes(); assertEqualContent(text, file); } public void testWriteByteArrayToFile() throws Exception { File file = new File(getTestDirectory(), "write.obj"); byte[] data = new byte[] {11, 21, 31}; FileUtils.writeByteArrayToFile(file, data); assertEqualContent(data, file); } public void testWriteLines_4arg() throws Exception { Object[] data = new Object[] { "hello", new StringBuffer("world"), "", "this is", null, "some text"}; List list = Arrays.asList(data); File file = newFile("lines.txt"); FileUtils.writeLines(file, "US-ASCII", list, "*"); String expected = "hello*world**this is**some text*"; String actual = FileUtils.readFileToString(file, "US-ASCII"); assertEquals(expected, actual); } public void testWriteLines_4arg_Writer_nullData() throws Exception { File file = newFile("lines.txt"); FileUtils.writeLines(file, "US-ASCII", (List) null, "*"); assertEquals("Sizes differ", 0, file.length()); } public void testWriteLines_4arg_nullSeparator() throws Exception { Object[] data = new Object[] { "hello", new StringBuffer("world"), "", "this is", null, "some text"}; List list = Arrays.asList(data); File file = newFile("lines.txt"); FileUtils.writeLines(file, "US-ASCII", list, null); String expected = "hello" + IOUtils.LINE_SEPARATOR + "world" + IOUtils.LINE_SEPARATOR + IOUtils.LINE_SEPARATOR + "this is" + IOUtils.LINE_SEPARATOR + IOUtils.LINE_SEPARATOR + "some text" + IOUtils.LINE_SEPARATOR; String actual = FileUtils.readFileToString(file, "US-ASCII"); assertEquals(expected, actual); } public void testWriteLines_3arg_nullSeparator() throws Exception { Object[] data = new Object[] { "hello", new StringBuffer("world"), "", "this is", null, "some text"}; List list = Arrays.asList(data); File file = newFile("lines.txt"); FileUtils.writeLines(file, "US-ASCII", list); String expected = "hello" + IOUtils.LINE_SEPARATOR + "world" + IOUtils.LINE_SEPARATOR + IOUtils.LINE_SEPARATOR + "this is" + IOUtils.LINE_SEPARATOR + IOUtils.LINE_SEPARATOR + "some text" + IOUtils.LINE_SEPARATOR; String actual = FileUtils.readFileToString(file, "US-ASCII"); assertEquals(expected, actual); } public void testWriteLines_5argsWithAppendOptionTrue_ShouldNotDeletePreviousFileLines() throws Exception { File file = newFile("lines.txt"); FileUtils.writeStringToFile(file, "This line was there before you..."); List linesToAppend = Arrays.asList(new String[] { "my first line", "The second Line" }); FileUtils.writeLines(file, null, linesToAppend, null, true); String expected = "This line was there before you..." + "my first line" + IOUtils.LINE_SEPARATOR + "The second Line" + IOUtils.LINE_SEPARATOR ; String actual = FileUtils.readFileToString(file); assertEquals(expected, actual); } public void testWriteLines_5argsWithAppendOptionFalse_ShouldDeletePreviousFileLines() throws Exception { File file = newFile("lines.txt"); FileUtils.writeStringToFile(file, "This line was there before you..."); List linesToAppend = Arrays.asList(new String[] { "my first line", "The second Line" }); FileUtils.writeLines(file, null, linesToAppend, null, false); String expected = "my first line" + IOUtils.LINE_SEPARATOR + "The second Line" + IOUtils.LINE_SEPARATOR ; String actual = FileUtils.readFileToString(file); assertEquals(expected, actual); } public void testWriteLines_4argsWithAppendOptionTrue_ShouldNotDeletePreviousFileLines() throws Exception { File file = newFile("lines.txt"); FileUtils.writeStringToFile(file, "This line was there before you..."); List linesToAppend = Arrays.asList(new String[] { "my first line", "The second Line" }); FileUtils.writeLines(file, linesToAppend, null, true); String expected = "This line was there before you..." + "my first line" + IOUtils.LINE_SEPARATOR + "The second Line" + IOUtils.LINE_SEPARATOR ; String actual = FileUtils.readFileToString(file); assertEquals(expected, actual); } public void testWriteLines_4argsWithAppendOptionFalse_ShouldDeletePreviousFileLines() throws Exception { File file = newFile("lines.txt"); FileUtils.writeStringToFile(file, "This line was there before you..."); List linesToAppend = Arrays.asList(new String[] { "my first line", "The second Line" }); FileUtils.writeLines(file, linesToAppend, null, false); String expected = "my first line" + IOUtils.LINE_SEPARATOR + "The second Line" + IOUtils.LINE_SEPARATOR ; String actual = FileUtils.readFileToString(file); assertEquals(expected, actual); } public void testWriteLinesEncoding_WithAppendOptionTrue_ShouldNotDeletePreviousFileLines() throws Exception { File file = newFile("lines.txt"); FileUtils.writeStringToFile(file, "This line was there before you..."); List linesToAppend = Arrays.asList(new String[] { "my first line", "The second Line" }); FileUtils.writeLines(file, null, linesToAppend, true); String expected = "This line was there before you..." + "my first line" + IOUtils.LINE_SEPARATOR + "The second Line" + IOUtils.LINE_SEPARATOR ; String actual = FileUtils.readFileToString(file); assertEquals(expected, actual); } public void testWriteLinesEncoding_WithAppendOptionFalse_ShouldDeletePreviousFileLines() throws Exception { File file = newFile("lines.txt"); FileUtils.writeStringToFile(file, "This line was there before you..."); List linesToAppend = Arrays.asList(new String[] { "my first line", "The second Line" }); FileUtils.writeLines(file, null, linesToAppend, false); String expected = "my first line" + IOUtils.LINE_SEPARATOR + "The second Line" + IOUtils.LINE_SEPARATOR ; String actual = FileUtils.readFileToString(file); assertEquals(expected, actual); } public void testWriteLines_3argsWithAppendOptionTrue_ShouldNotDeletePreviousFileLines() throws Exception { File file = newFile("lines.txt"); FileUtils.writeStringToFile(file, "This line was there before you..."); List linesToAppend = Arrays.asList(new String[] { "my first line", "The second Line" }); FileUtils.writeLines(file, linesToAppend, true); String expected = "This line was there before you..." + "my first line" + IOUtils.LINE_SEPARATOR + "The second Line" + IOUtils.LINE_SEPARATOR ; String actual = FileUtils.readFileToString(file); assertEquals(expected, actual); } public void testWriteLines_3argsWithAppendOptionFalse_ShouldDeletePreviousFileLines() throws Exception { File file = newFile("lines.txt"); FileUtils.writeStringToFile(file, "This line was there before you..."); List linesToAppend = Arrays.asList(new String[] { "my first line", "The second Line" }); FileUtils.writeLines(file, linesToAppend, false); String expected = "my first line" + IOUtils.LINE_SEPARATOR + "The second Line" + IOUtils.LINE_SEPARATOR ; String actual = FileUtils.readFileToString(file); assertEquals(expected, actual); } public void testWriteStringToFileWithEncoding_WithAppendOptionTrue_ShouldNotDeletePreviousFileLines() throws Exception { File file = newFile("lines.txt"); FileUtils.writeStringToFile(file, "This line was there before you..."); FileUtils.writeStringToFile(file, "this is brand new data", (String) null, true); String expected = "This line was there before you..." + "this is brand new data"; String actual = FileUtils.readFileToString(file); assertEquals(expected, actual); } public void testWriteStringToFileWithEncoding_WithAppendOptionFalse_ShouldDeletePreviousFileLines() throws Exception { File file = newFile("lines.txt"); FileUtils.writeStringToFile(file, "This line was there before you..."); FileUtils.writeStringToFile(file, "this is brand new data", (String) null, false); String expected = "this is brand new data"; String actual = FileUtils.readFileToString(file); assertEquals(expected, actual); } public void testWriteStringToFile_WithAppendOptionTrue_ShouldNotDeletePreviousFileLines() throws Exception { File file = newFile("lines.txt"); FileUtils.writeStringToFile(file, "This line was there before you..."); FileUtils.writeStringToFile(file, "this is brand new data", true); String expected = "This line was there before you..." + "this is brand new data"; String actual = FileUtils.readFileToString(file); assertEquals(expected, actual); } public void testWriteStringToFile_WithAppendOptionFalse_ShouldDeletePreviousFileLines() throws Exception { File file = newFile("lines.txt"); FileUtils.writeStringToFile(file, "This line was there before you..."); FileUtils.writeStringToFile(file, "this is brand new data", false); String expected = "this is brand new data"; String actual = FileUtils.readFileToString(file); assertEquals(expected, actual); } public void testWriteWithEncoding_WithAppendOptionTrue_ShouldNotDeletePreviousFileLines() throws Exception { File file = newFile("lines.txt"); FileUtils.writeStringToFile(file, "This line was there before you..."); FileUtils.write(file, "this is brand new data", (String) null, true); String expected = "This line was there before you..." + "this is brand new data"; String actual = FileUtils.readFileToString(file); assertEquals(expected, actual); } public void testWriteWithEncoding_WithAppendOptionFalse_ShouldDeletePreviousFileLines() throws Exception { File file = newFile("lines.txt"); FileUtils.writeStringToFile(file, "This line was there before you..."); FileUtils.write(file, "this is brand new data", (String) null, false); String expected = "this is brand new data"; String actual = FileUtils.readFileToString(file); assertEquals(expected, actual); } public void testWrite_WithAppendOptionTrue_ShouldNotDeletePreviousFileLines() throws Exception { File file = newFile("lines.txt"); FileUtils.writeStringToFile(file, "This line was there before you..."); FileUtils.write(file, "this is brand new data", true); String expected = "This line was there before you..." + "this is brand new data"; String actual = FileUtils.readFileToString(file); assertEquals(expected, actual); } public void testWrite_WithAppendOptionFalse_ShouldDeletePreviousFileLines() throws Exception { File file = newFile("lines.txt"); FileUtils.writeStringToFile(file, "This line was there before you..."); FileUtils.write(file, "this is brand new data", false); String expected = "this is brand new data"; String actual = FileUtils.readFileToString(file); assertEquals(expected, actual); } public void testWriteByteArrayToFile_WithAppendOptionTrue_ShouldNotDeletePreviousFileLines() throws Exception { File file = newFile("lines.txt"); FileUtils.writeStringToFile(file, "This line was there before you..."); FileUtils.writeByteArrayToFile(file, "this is brand new data".getBytes(), true); String expected = "This line was there before you..." + "this is brand new data"; String actual = FileUtils.readFileToString(file); assertEquals(expected, actual); } public void testWriteByteArrayToFile_WithAppendOptionFalse_ShouldDeletePreviousFileLines() throws Exception { File file = newFile("lines.txt"); FileUtils.writeStringToFile(file, "This line was there before you..."); FileUtils.writeByteArrayToFile(file, "this is brand new data".getBytes(), false); String expected = "this is brand new data"; String actual = FileUtils.readFileToString(file); assertEquals(expected, actual); } //----------------------------------------------------------------------- public void testChecksumCRC32() throws Exception { // create a test file String text = "Imagination is more important than knowledge - Einstein"; File file = new File(getTestDirectory(), "checksum-test.txt"); FileUtils.writeStringToFile(file, text, "US-ASCII"); // compute the expected checksum Checksum expectedChecksum = new CRC32(); expectedChecksum.update(text.getBytes("US-ASCII"), 0, text.length()); long expectedValue = expectedChecksum.getValue(); // compute the checksum of the file long resultValue = FileUtils.checksumCRC32(file); assertEquals(expectedValue, resultValue); } public void testChecksum() throws Exception { // create a test file String text = "Imagination is more important than knowledge - Einstein"; File file = new File(getTestDirectory(), "checksum-test.txt"); FileUtils.writeStringToFile(file, text, "US-ASCII"); // compute the expected checksum Checksum expectedChecksum = new CRC32(); expectedChecksum.update(text.getBytes("US-ASCII"), 0, text.length()); long expectedValue = expectedChecksum.getValue(); // compute the checksum of the file Checksum testChecksum = new CRC32(); Checksum resultChecksum = FileUtils.checksum(file, testChecksum); long resultValue = resultChecksum.getValue(); assertSame(testChecksum, resultChecksum); assertEquals(expectedValue, resultValue); } public void testChecksumOnNullFile() throws Exception { try { FileUtils.checksum((File) null, new CRC32()); fail(); } catch (NullPointerException ex) { // expected } } public void testChecksumOnNullChecksum() throws Exception { // create a test file String text = "Imagination is more important than knowledge - Einstein"; File file = new File(getTestDirectory(), "checksum-test.txt"); FileUtils.writeStringToFile(file, text, "US-ASCII"); try { FileUtils.checksum(file, (Checksum) null); fail(); } catch (NullPointerException ex) { // expected } } public void testChecksumOnDirectory() throws Exception { try { FileUtils.checksum(new File("."), new CRC32()); fail(); } catch (IllegalArgumentException ex) { // expected } } public void testChecksumDouble() throws Exception { // create a test file String text1 = "Imagination is more important than knowledge - Einstein"; File file1 = new File(getTestDirectory(), "checksum-test.txt"); FileUtils.writeStringToFile(file1, text1, "US-ASCII"); // create a second test file String text2 = "To be or not to be - Shakespeare"; File file2 = new File(getTestDirectory(), "checksum-test2.txt"); FileUtils.writeStringToFile(file2, text2, "US-ASCII"); // compute the expected checksum Checksum expectedChecksum = new CRC32(); expectedChecksum.update(text1.getBytes("US-ASCII"), 0, text1.length()); expectedChecksum.update(text2.getBytes("US-ASCII"), 0, text2.length()); long expectedValue = expectedChecksum.getValue(); // compute the checksum of the file Checksum testChecksum = new CRC32(); FileUtils.checksum(file1, testChecksum); FileUtils.checksum(file2, testChecksum); long resultValue = testChecksum.getValue(); assertEquals(expectedValue, resultValue); } public void testDeleteQuietlyForNull() { try { FileUtils.deleteQuietly(null); } catch (Exception ex) { fail(ex.getMessage()); } } public void testDeleteQuietlyDir() throws IOException { File testDirectory = new File(getTestDirectory(), "testDeleteQuietlyDir"); File testFile= new File(testDirectory, "testDeleteQuietlyFile"); testDirectory.mkdirs(); createFile(testFile, 0); assertTrue(testDirectory.exists()); assertTrue(testFile.exists()); FileUtils.deleteQuietly(testDirectory); assertFalse("Check No Exist", testDirectory.exists()); assertFalse("Check No Exist", testFile.exists()); } public void testDeleteQuietlyFile() throws IOException { File testFile= new File(getTestDirectory(), "testDeleteQuietlyFile"); createFile(testFile, 0); assertTrue(testFile.exists()); FileUtils.deleteQuietly(testFile); assertFalse("Check No Exist", testFile.exists()); } public void testDeleteQuietlyNonExistent() { File testFile = new File("testDeleteQuietlyNonExistent"); assertFalse(testFile.exists()); try { FileUtils.deleteQuietly(testFile); } catch (Exception ex) { fail(ex.getMessage()); } } public void testMoveFile_Rename() throws Exception { File destination = new File( getTestDirectory(), "move1.txt" ); FileUtils.moveFile( testFile1, destination ); assertTrue( "Check Exist", destination.exists() ); assertTrue( "Original deleted", ! testFile1.exists() ); } public void testMoveFile_CopyDelete() throws Exception { File destination = new File( getTestDirectory(), "move2.txt" ); File src = new File( testFile1.getAbsolutePath() ) { // Force renameTo to fail, as if destination is on another // filesystem @Override public boolean renameTo( File f ) { return false; } }; FileUtils.moveFile( src, destination ); assertTrue( "Check Exist", destination.exists() ); assertTrue( "Original deleted", ! src.exists() ); } public void testMoveFile_CopyDelete_Failed() throws Exception { File destination = new File( getTestDirectory(), "move3.txt" ); File src = new File( testFile1.getAbsolutePath() ) { // Force renameTo to fail, as if destination is on another // filesystem @Override public boolean renameTo( File f ) { return false; } // Force delete failure @Override public boolean delete() { return false; } }; try { FileUtils.moveFile( src, destination ); fail( "move should have failed as src has not been deleted" ); } catch (IOException e) { // exepected assertTrue( "Check Rollback", !destination.exists() ); assertTrue( "Original exists", src.exists() ); } } public void testMoveFile_Errors() throws Exception { try { FileUtils.moveFile(null, new File("foo")); fail("Expected NullPointerException when source is null"); } catch (NullPointerException e) { // expected } try { FileUtils.moveFile(new File("foo"), null); fail("Expected NullPointerException when destination is null"); } catch (NullPointerException e) { // expected } try { FileUtils.moveFile(new File("nonexistant"), new File("foo")); fail("Expected FileNotFoundException for source"); } catch (FileNotFoundException e) { // expected } try { FileUtils.moveFile(getTestDirectory(), new File("foo")); fail("Expected IOException when source is a directory"); } catch (IOException e) { // expected } File testSourceFile = new File(getTestDirectory(), "testMoveFileSource"); File testDestFile = new File(getTestDirectory(), "testMoveFileSource"); createFile(testSourceFile, 0); createFile(testDestFile, 0); try { FileUtils.moveFile(testSourceFile, testDestFile); fail("Expected FileExistsException when dest already exists"); } catch (FileExistsException e) { // expected } } public void testMoveFileToDirectory() throws Exception { File destDir = new File( getTestDirectory(), "moveFileDestDir"); File movedFile = new File(destDir, testFile1.getName()); assertFalse("Check Exist before", destDir.exists()); assertFalse("Check Exist before", movedFile.exists()); FileUtils.moveFileToDirectory(testFile1, destDir, true); assertTrue( "Check Exist after", movedFile.exists() ); assertTrue( "Original deleted", ! testFile1.exists() ); } public void testMoveFileToDirectory_Errors() throws Exception { try { FileUtils.moveFileToDirectory(null, new File("foo"), true); fail("Expected NullPointerException when source is null"); } catch (NullPointerException e) { // expected } try { FileUtils.moveFileToDirectory(new File("foo"), null, true); fail("Expected NullPointerException when destination is null"); } catch (NullPointerException e) { // expected } File testFile1 = new File(getTestDirectory(), "testMoveFileFile1"); File testFile2 = new File(getTestDirectory(), "testMoveFileFile2"); createFile(testFile1, 0); createFile(testFile2, 0); try { FileUtils.moveFileToDirectory(testFile1, testFile2, true); fail("Expected IOException when dest not a directory"); } catch (IOException e) { // expected } File nonexistant = new File(getTestDirectory(), "testMoveFileNonExistant"); try { FileUtils.moveFileToDirectory(testFile1, nonexistant, false); fail("Expected IOException when dest does not exist and create=false"); } catch (IOException e) { // expected } } public void testMoveDirectory_Rename() throws Exception { File dir = getTestDirectory(); File src = new File(dir, "testMoveDirectory1Source"); File testDir = new File(src, "foo"); File testFile = new File(testDir, "bar"); testDir.mkdirs(); createFile(testFile, 0); File destination = new File(dir, "testMoveDirectory1Dest"); FileUtils.deleteDirectory( destination ); // Move the directory FileUtils.moveDirectory( src, destination ); // Check results assertTrue( "Check Exist", destination.exists() ); assertTrue( "Original deleted", ! src.exists() ); File movedDir = new File(destination, testDir.getName()); File movedFile = new File(movedDir, testFile.getName()); assertTrue( "Check dir moved", movedDir.exists()); assertTrue( "Check file moved", movedFile.exists()); } public void testMoveDirectory_CopyDelete() throws Exception { File dir = getTestDirectory(); File src = new File(dir, "testMoveDirectory2Source") { // Force renameTo to fail @Override public boolean renameTo( File dest ) { return false; } }; File testDir = new File(src, "foo"); File testFile = new File(testDir, "bar"); testDir.mkdirs(); createFile(testFile, 0); File destination = new File(dir, "testMoveDirectory1Dest"); FileUtils.deleteDirectory( destination ); // Move the directory FileUtils.moveDirectory( src, destination ); // Check results assertTrue( "Check Exist", destination.exists() ); assertTrue( "Original deleted", ! src.exists() ); File movedDir = new File(destination, testDir.getName()); File movedFile = new File(movedDir, testFile.getName()); assertTrue( "Check dir moved", movedDir.exists()); assertTrue( "Check file moved", movedFile.exists()); } public void testMoveDirectory_Errors() throws Exception { try { FileUtils.moveDirectory(null, new File("foo")); fail("Expected NullPointerException when source is null"); } catch (NullPointerException e) { // expected } try { FileUtils.moveDirectory(new File("foo"), null); fail("Expected NullPointerException when destination is null"); } catch (NullPointerException e) { // expected } try { FileUtils.moveDirectory(new File("nonexistant"), new File("foo")); fail("Expected FileNotFoundException for source"); } catch (FileNotFoundException e) { // expected } File testFile = new File(getTestDirectory(), "testMoveDirectoryFile"); createFile(testFile, 0); try { FileUtils.moveDirectory(testFile, new File("foo")); fail("Expected IOException when source is not a directory"); } catch (IOException e) { // expected } File testSrcFile = new File(getTestDirectory(), "testMoveDirectorySource"); File testDestFile = new File(getTestDirectory(), "testMoveDirectoryDest"); testSrcFile.mkdir(); testDestFile.mkdir(); try { FileUtils.moveDirectory(testSrcFile, testDestFile); fail("Expected FileExistsException when dest already exists"); } catch (FileExistsException e) { // expected } } public void testMoveDirectoryToDirectory() throws Exception { File dir = getTestDirectory(); File src = new File(dir, "testMoveDirectory1Source"); File testChildDir = new File(src, "foo"); File testFile = new File(testChildDir, "bar"); testChildDir.mkdirs(); createFile(testFile, 0); File destDir = new File(dir, "testMoveDirectory1Dest"); FileUtils.deleteDirectory( destDir ); assertFalse( "Check Exist before", destDir.exists() ); // Move the directory FileUtils.moveDirectoryToDirectory(src, destDir, true); // Check results assertTrue( "Check Exist after", destDir.exists() ); assertTrue( "Original deleted", ! src.exists() ); File movedDir = new File(destDir, src.getName()); File movedChildDir = new File(movedDir, testChildDir.getName()); File movedFile = new File(movedChildDir, testFile.getName()); assertTrue( "Check dir moved", movedDir.exists()); assertTrue( "Check child dir moved", movedChildDir.exists()); assertTrue( "Check file moved", movedFile.exists()); } public void testMoveDirectoryToDirectory_Errors() throws Exception { try { FileUtils.moveDirectoryToDirectory(null, new File("foo"), true); fail("Expected NullPointerException when source is null"); } catch (NullPointerException e) { // expected } try { FileUtils.moveDirectoryToDirectory(new File("foo"), null, true); fail("Expected NullPointerException when destination is null"); } catch (NullPointerException e) { // expected } File testFile1 = new File(getTestDirectory(), "testMoveFileFile1"); File testFile2 = new File(getTestDirectory(), "testMoveFileFile2"); createFile(testFile1, 0); createFile(testFile2, 0); try { FileUtils.moveDirectoryToDirectory(testFile1, testFile2, true); fail("Expected IOException when dest not a directory"); } catch (IOException e) { // expected } File nonexistant = new File(getTestDirectory(), "testMoveFileNonExistant"); try { FileUtils.moveDirectoryToDirectory(testFile1, nonexistant, false); fail("Expected IOException when dest does not exist and create=false"); } catch (IOException e) { // expected } } public void testMoveToDirectory() throws Exception { File destDir = new File(getTestDirectory(), "testMoveToDirectoryDestDir"); File testDir = new File(getTestDirectory(), "testMoveToDirectoryTestDir"); File testFile = new File(getTestDirectory(), "testMoveToDirectoryTestFile"); testDir.mkdirs(); createFile(testFile, 0); File movedFile = new File(destDir, testFile.getName()); File movedDir = new File(destDir, testFile.getName()); assertFalse( "Check File Doesnt exist", movedFile.exists() ); assertFalse( "Check Dir Doesnt exist", movedDir.exists() ); // Test moving a file FileUtils.moveToDirectory(testFile, destDir, true); assertTrue( "Check File exists", movedFile.exists() ); assertFalse( "Check Original File doesn't exist", testFile.exists() ); // Test moving a directory FileUtils.moveToDirectory(testDir, destDir, true); assertTrue( "Check Dir exists", movedDir.exists() ); assertFalse( "Check Original Dir doesn't exist", testDir.exists()); } public void testMoveToDirectory_Errors() throws Exception { try { FileUtils.moveDirectoryToDirectory(null, new File("foo"), true); fail("Expected NullPointerException when source is null"); } catch (NullPointerException e) { // expected } try { FileUtils.moveDirectoryToDirectory(new File("foo"), null, true); fail("Expected NullPointerException when destination is null"); } catch (NullPointerException e) { // expected } File nonexistant = new File(getTestDirectory(), "nonexistant"); File destDir = new File(getTestDirectory(), "MoveToDirectoryDestDir"); try { FileUtils.moveToDirectory(nonexistant, destDir, true); fail("Expected IOException when source does not exist"); } catch (IOException e) { // expected } } public void testIO300() throws Exception { final File testDirectory = getTestDirectory(); File src = new File(testDirectory, "dir1"); File dest = new File(src,"dir2"); assertTrue(dest.mkdirs()); assertTrue(src.exists()); try { FileUtils.moveDirectoryToDirectory(src, dest, false); fail("expected IOException"); } catch (IOException ioe) { // expected } assertTrue(src.exists()); } public void testIO276() throws Exception { File dir = new File("target", "IO276"); assertTrue(dir + " should not be present", dir.mkdirs()); File file = new File(dir, "IO276.txt"); assertTrue(file + " should not be present", file.createNewFile()); FileUtils.forceDeleteOnExit(dir); // If this does not work, test will fail next time (assuming target is not cleaned) } /** * DirectoryWalker implementation that recursively lists all files and directories. */ static class ListDirectoryWalker extends DirectoryWalker { ListDirectoryWalker() { super(); } List list(File startDirectory) throws IOException { ArrayList files = new ArrayList(); walk(startDirectory, files); return files; } @Override protected void handleDirectoryStart(File directory, int depth, Collection results) throws IOException { // Add all directories except the starting directory if (depth > 0) { results.add(directory); } } @Override protected void handleFile(File file, int depth, Collection results) throws IOException { results.add(file); } } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/FileUtilsCleanDirectoryTestCase.java0000644000175000017500000001076212125050425033146 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.commons.io.testtools.FileBasedTestCase; /** * Test cases for FileUtils.cleanDirectory() method. * * @version $Id: FileUtilsCleanDirectoryTestCase.java 1302748 2012-03-20 01:35:32Z ggregory $ */ public class FileUtilsCleanDirectoryTestCase extends FileBasedTestCase { final File top = getLocalTestDirectory(); public FileUtilsCleanDirectoryTestCase(String name) { super(name); } private File getLocalTestDirectory() { return new File(getTestDirectory(), "list-files"); } /** * @see junit.framework.TestCase#setUp() */ @Override protected void setUp() throws Exception { top.mkdirs(); } /** * @see junit.framework.TestCase#tearDown() */ @Override protected void tearDown() throws Exception { chmod(top, 775, true); FileUtils.deleteDirectory(top); } //----------------------------------------------------------------------- public void testCleanEmpty() throws Exception { assertEquals(0, top.list().length); FileUtils.cleanDirectory(top); assertEquals(0, top.list().length); } public void testDeletesRegular() throws Exception { FileUtils.touch(new File(top, "regular")); FileUtils.touch(new File(top, ".hidden")); assertEquals(2, top.list().length); FileUtils.cleanDirectory(top); assertEquals(0, top.list().length); } public void testDeletesNested() throws Exception { final File nested = new File(top, "nested"); assertTrue(nested.mkdirs()); FileUtils.touch(new File(nested, "file")); assertEquals(1, top.list().length); FileUtils.cleanDirectory(top); assertEquals(0, top.list().length); } public void testThrowsOnNullList() throws Exception { if (System.getProperty("os.name").startsWith("Win") || !chmod(top, 0, false)) { // test wont work if we can't restrict permissions on the // directory, so skip it. return; } try { FileUtils.cleanDirectory(top); fail("expected IOException"); } catch (IOException e) { assertEquals("Failed to list contents of " + top.getAbsolutePath(), e.getMessage()); } } public void testThrowsOnCannotDeleteFile() throws Exception { final File file = new File(top, "restricted"); FileUtils.touch(file); if (System.getProperty("os.name").startsWith("Win") || !chmod(top, 500, false)) { // test wont work if we can't restrict permissions on the // directory, so skip it. return; } try { FileUtils.cleanDirectory(top); fail("expected IOException"); } catch (IOException e) { assertEquals("Unable to delete file: " + file.getAbsolutePath(), e.getMessage()); } } private boolean chmod(File file, int mode, boolean recurse) throws InterruptedException { // TODO: Refactor this to FileSystemUtils List args = new ArrayList(); args.add("chmod"); if (recurse) { args.add("-R"); } args.add(Integer.toString(mode)); args.add(file.getAbsolutePath()); Process proc; try { proc = Runtime.getRuntime().exec( args.toArray(new String[args.size()])); } catch (IOException e) { return false; } int result = proc.waitFor(); return result == 0; } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/FileUtilsCleanSymlinksTestCase.java0000644000175000017500000002067312125050425033015 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.io.File; import java.util.ArrayList; import java.util.List; import org.apache.commons.io.testtools.FileBasedTestCase; /** * Test cases for FileUtils.cleanDirectory() method that involve symlinks. * & FileUtils.isSymlink(File file) */ public class FileUtilsCleanSymlinksTestCase extends FileBasedTestCase { final File top = getTestDirectory(); public FileUtilsCleanSymlinksTestCase(String name) { super(name); } @Override protected void setUp() throws Exception { top.mkdirs(); } @Override protected void tearDown() throws Exception { FileUtils.deleteDirectory(top); } public void testCleanDirWithSymlinkFile() throws Exception { if (System.getProperty("os.name").startsWith("Win")) { // cant create symlinks in windows. return; } final File realOuter = new File(top, "realouter"); assertTrue(realOuter.mkdirs()); final File realInner = new File(realOuter, "realinner"); assertTrue(realInner.mkdirs()); final File realFile = new File(realInner, "file1"); FileUtils.touch(realFile); assertEquals(1, realInner.list().length); final File randomFile = new File(top, "randomfile"); FileUtils.touch(randomFile); final File symlinkFile = new File(realInner, "fakeinner"); setupSymlink(randomFile, symlinkFile); assertEquals(2, realInner.list().length); // assert contents of the real directory were removed including the symlink FileUtils.cleanDirectory(realOuter); assertEquals(0, realOuter.list().length); // ensure that the contents of the symlink were NOT removed. assertTrue(randomFile.exists()); assertFalse(symlinkFile.exists()); } public void testCleanDirWithASymlinkDir() throws Exception { if (System.getProperty("os.name").startsWith("Win")) { // cant create symlinks in windows. return; } final File realOuter = new File(top, "realouter"); assertTrue(realOuter.mkdirs()); final File realInner = new File(realOuter, "realinner"); assertTrue(realInner.mkdirs()); FileUtils.touch(new File(realInner, "file1")); assertEquals(1, realInner.list().length); final File randomDirectory = new File(top, "randomDir"); assertTrue(randomDirectory.mkdirs()); FileUtils.touch(new File(randomDirectory, "randomfile")); assertEquals(1, randomDirectory.list().length); final File symlinkDirectory = new File(realOuter, "fakeinner"); setupSymlink(randomDirectory, symlinkDirectory); assertEquals(1, symlinkDirectory.list().length); // assert contents of the real directory were removed including the symlink FileUtils.cleanDirectory(realOuter); assertEquals(0, realOuter.list().length); // ensure that the contents of the symlink were NOT removed. assertEquals("Contents of sym link should not have been removed", 1, randomDirectory.list().length); } public void testCleanDirWithParentSymlinks() throws Exception { if (System.getProperty("os.name").startsWith("Win")) { // cant create symlinks in windows. return; } final File realParent = new File(top, "realparent"); assertTrue(realParent.mkdirs()); final File realInner = new File(realParent, "realinner"); assertTrue(realInner.mkdirs()); FileUtils.touch(new File(realInner, "file1")); assertEquals(1, realInner.list().length); final File randomDirectory = new File(top, "randomDir"); assertTrue(randomDirectory.mkdirs()); FileUtils.touch(new File(randomDirectory, "randomfile")); assertEquals(1, randomDirectory.list().length); final File symlinkDirectory = new File(realParent, "fakeinner"); setupSymlink(randomDirectory, symlinkDirectory); assertEquals(1, symlinkDirectory.list().length); final File symlinkParentDirectory = new File(top, "fakeouter"); setupSymlink(realParent, symlinkParentDirectory); // assert contents of the real directory were removed including the symlink FileUtils.cleanDirectory(symlinkParentDirectory);// should clean the contents of this but not recurse into other links assertEquals(0, symlinkParentDirectory.list().length); assertEquals(0, realParent.list().length); // ensure that the contents of the symlink were NOT removed. assertEquals("Contents of sym link should not have been removed", 1, randomDirectory.list().length); } public void testStillClearsIfGivenDirectoryIsASymlink() throws Exception { if (System.getProperty("os.name").startsWith("Win")) { // cant create symlinks in windows. return; } final File randomDirectory = new File(top, "randomDir"); assertTrue(randomDirectory.mkdirs()); FileUtils.touch(new File(randomDirectory, "randomfile")); assertEquals(1, randomDirectory.list().length); final File symlinkDirectory = new File(top, "fakeDir"); setupSymlink(randomDirectory, symlinkDirectory); FileUtils.cleanDirectory(symlinkDirectory); assertEquals(0, symlinkDirectory.list().length); assertEquals(0, randomDirectory.list().length); } public void testIdentifiesSymlinkDir() throws Exception { if (System.getProperty("os.name").startsWith("Win")) { // cant create symlinks in windows. return; } final File randomDirectory = new File(top, "randomDir"); assertTrue(randomDirectory.mkdirs()); final File symlinkDirectory = new File(top, "fakeDir"); setupSymlink(randomDirectory, symlinkDirectory); assertTrue(FileUtils.isSymlink(symlinkDirectory)); assertFalse(FileUtils.isSymlink(randomDirectory)); } public void testIdentifiesSymlinkFile() throws Exception { if (System.getProperty("os.name").startsWith("Win")) { // cant create symlinks in windows. return; } final File randomFile = new File(top, "randomfile"); FileUtils.touch(randomFile); final File symlinkFile = new File(top, "fakeinner"); setupSymlink(randomFile, symlinkFile); assertTrue(FileUtils.isSymlink(symlinkFile)); assertFalse(FileUtils.isSymlink(randomFile)); } public void testCorrectlyIdentifySymlinkWithParentSymLink() throws Exception { if (System.getProperty("os.name").startsWith("Win")) { // cant create symlinks in windows. return; } final File realParent = new File(top, "realparent"); assertTrue(realParent.mkdirs()); final File symlinkParentDirectory = new File(top, "fakeparent"); setupSymlink(realParent, symlinkParentDirectory); final File realChild = new File(symlinkParentDirectory, "realChild"); assertTrue(realChild.mkdirs()); final File symlinkChild = new File(symlinkParentDirectory, "fakeChild"); setupSymlink(realChild, symlinkChild); assertTrue(FileUtils.isSymlink(symlinkChild)); assertFalse(FileUtils.isSymlink(realChild)); } private void setupSymlink(File res, File link) throws Exception { // create symlink List args = new ArrayList(); args.add("ln"); args.add("-s"); args.add(res.getAbsolutePath()); args.add(link.getAbsolutePath()); Process proc; proc = Runtime.getRuntime().exec(args.toArray(new String[args.size()])); proc.waitFor(); } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/IOUtilsWriteTestCase.java0000644000175000017500000006712612125050425030767 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.Arrays; import java.util.List; import org.apache.commons.io.output.ByteArrayOutputStream; import org.apache.commons.io.testtools.FileBasedTestCase; import org.apache.commons.io.testtools.YellOnFlushAndCloseOutputStream; /** * JUnit tests for IOUtils write methods. * * @version $Id: IOUtilsWriteTestCase.java 1307397 2012-03-30 13:12:16Z ggregory $ * @see IOUtils */ public class IOUtilsWriteTestCase extends FileBasedTestCase { private static final int FILE_SIZE = 1024 * 4 + 1; private byte[] inData = generateTestData(FILE_SIZE); public IOUtilsWriteTestCase(String testName) { super(testName); } // ---------------------------------------------------------------- // Setup // ---------------------------------------------------------------- @Override public void setUp() throws Exception { } @Override public void tearDown() throws Exception { } // ---------------------------------------------------------------- // Tests // ---------------------------------------------------------------- //----------------------------------------------------------------------- public void testWrite_byteArrayToOutputStream() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true); IOUtils.write(inData, out); out.off(); out.flush(); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); } public void testWrite_byteArrayToOutputStream_nullData() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true); IOUtils.write((byte[]) null, out); out.off(); out.flush(); assertEquals("Sizes differ", 0, baout.size()); } public void testWrite_byteArrayToOutputStream_nullStream() throws Exception { try { IOUtils.write(inData, (OutputStream) null); fail(); } catch (NullPointerException ex) {} } //----------------------------------------------------------------------- public void testWrite_byteArrayToWriter() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); IOUtils.write(inData, writer); out.off(); writer.flush(); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); } public void testWrite_byteArrayToWriter_nullData() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); IOUtils.write((byte[]) null, writer); out.off(); writer.flush(); assertEquals("Sizes differ", 0, baout.size()); } public void testWrite_byteArrayToWriter_nullWriter() throws Exception { try { IOUtils.write(inData, (Writer) null); fail(); } catch (NullPointerException ex) {} } //----------------------------------------------------------------------- public void testWrite_byteArrayToWriter_Encoding() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); IOUtils.write(inData, writer, "UTF8"); out.off(); writer.flush(); byte[] bytes = baout.toByteArray(); bytes = new String(bytes, "UTF8").getBytes("US-ASCII"); assertTrue("Content differs", Arrays.equals(inData, bytes)); } public void testWrite_byteArrayToWriter_Encoding_nullData() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); IOUtils.write((byte[]) null, writer, "UTF8"); out.off(); writer.flush(); assertEquals("Sizes differ", 0, baout.size()); } public void testWrite_byteArrayToWriter_Encoding_nullWriter() throws Exception { try { IOUtils.write(inData, (Writer) null, "UTF8"); fail(); } catch (NullPointerException ex) {} } public void testWrite_byteArrayToWriter_Encoding_nullEncoding() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); IOUtils.write(inData, writer, (String) null); out.off(); writer.flush(); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); } //----------------------------------------------------------------------- public void testWrite_charSequenceToOutputStream() throws Exception { CharSequence csq = new StringBuilder(new String(inData, "US-ASCII")); ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true); IOUtils.write(csq, out); out.off(); out.flush(); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); } public void testWrite_charSequenceToOutputStream_nullData() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true); IOUtils.write((CharSequence) null, out); out.off(); out.flush(); assertEquals("Sizes differ", 0, baout.size()); } public void testWrite_charSequenceToOutputStream_nullStream() throws Exception { CharSequence csq = new StringBuilder(new String(inData, "US-ASCII")); try { IOUtils.write(csq, (OutputStream) null); fail(); } catch (NullPointerException ex) {} } //----------------------------------------------------------------------- public void testWrite_charSequenceToOutputStream_Encoding() throws Exception { CharSequence csq = new StringBuilder(new String(inData, "US-ASCII")); ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true); IOUtils.write(csq, out, "UTF16"); out.off(); out.flush(); byte[] bytes = baout.toByteArray(); bytes = new String(bytes, "UTF16").getBytes("US-ASCII"); assertTrue("Content differs", Arrays.equals(inData, bytes)); } public void testWrite_charSequenceToOutputStream_Encoding_nullData() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true); IOUtils.write((CharSequence) null, out); out.off(); out.flush(); assertEquals("Sizes differ", 0, baout.size()); } public void testWrite_charSequenceToOutputStream_Encoding_nullStream() throws Exception { CharSequence csq = new StringBuilder(new String(inData, "US-ASCII")); try { IOUtils.write(csq, (OutputStream) null); fail(); } catch (NullPointerException ex) {} } public void testWrite_charSequenceToOutputStream_nullEncoding() throws Exception { CharSequence csq = new StringBuilder(new String(inData, "US-ASCII")); ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true); IOUtils.write(csq, out, (String) null); out.off(); out.flush(); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); } //----------------------------------------------------------------------- public void testWrite_charSequenceToWriter() throws Exception { CharSequence csq = new StringBuilder(new String(inData, "US-ASCII")); ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); IOUtils.write(csq, writer); out.off(); writer.flush(); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); } public void testWrite_charSequenceToWriter_Encoding_nullData() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); IOUtils.write((CharSequence) null, writer); out.off(); writer.flush(); assertEquals("Sizes differ", 0, baout.size()); } public void testWrite_charSequenceToWriter_Encoding_nullStream() throws Exception { CharSequence csq = new StringBuilder(new String(inData, "US-ASCII")); try { IOUtils.write(csq, (Writer) null); fail(); } catch (NullPointerException ex) {} } //----------------------------------------------------------------------- public void testWrite_stringToOutputStream() throws Exception { String str = new String(inData, "US-ASCII"); ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true); IOUtils.write(str, out); out.off(); out.flush(); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); } public void testWrite_stringToOutputStream_nullData() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true); IOUtils.write((String) null, out); out.off(); out.flush(); assertEquals("Sizes differ", 0, baout.size()); } public void testWrite_stringToOutputStream_nullStream() throws Exception { String str = new String(inData, "US-ASCII"); try { IOUtils.write(str, (OutputStream) null); fail(); } catch (NullPointerException ex) {} } //----------------------------------------------------------------------- public void testWrite_stringToOutputStream_Encoding() throws Exception { String str = new String(inData, "US-ASCII"); ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true); IOUtils.write(str, out, "UTF16"); out.off(); out.flush(); byte[] bytes = baout.toByteArray(); bytes = new String(bytes, "UTF16").getBytes("US-ASCII"); assertTrue("Content differs", Arrays.equals(inData, bytes)); } public void testWrite_stringToOutputStream_Encoding_nullData() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true); IOUtils.write((String) null, out); out.off(); out.flush(); assertEquals("Sizes differ", 0, baout.size()); } public void testWrite_stringToOutputStream_Encoding_nullStream() throws Exception { String str = new String(inData, "US-ASCII"); try { IOUtils.write(str, (OutputStream) null); fail(); } catch (NullPointerException ex) {} } public void testWrite_stringToOutputStream_nullEncoding() throws Exception { String str = new String(inData, "US-ASCII"); ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true); IOUtils.write(str, out, (String) null); out.off(); out.flush(); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); } //----------------------------------------------------------------------- public void testWrite_stringToWriter() throws Exception { String str = new String(inData, "US-ASCII"); ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); IOUtils.write(str, writer); out.off(); writer.flush(); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); } public void testWrite_stringToWriter_Encoding_nullData() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); IOUtils.write((String) null, writer); out.off(); writer.flush(); assertEquals("Sizes differ", 0, baout.size()); } public void testWrite_stringToWriter_Encoding_nullStream() throws Exception { String str = new String(inData, "US-ASCII"); try { IOUtils.write(str, (Writer) null); fail(); } catch (NullPointerException ex) {} } //----------------------------------------------------------------------- public void testWrite_charArrayToOutputStream() throws Exception { String str = new String(inData, "US-ASCII"); ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true); IOUtils.write(str.toCharArray(), out); out.off(); out.flush(); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); } public void testWrite_charArrayToOutputStream_nullData() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true); IOUtils.write((char[]) null, out); out.off(); out.flush(); assertEquals("Sizes differ", 0, baout.size()); } public void testWrite_charArrayToOutputStream_nullStream() throws Exception { String str = new String(inData, "US-ASCII"); try { IOUtils.write(str.toCharArray(), (OutputStream) null); fail(); } catch (NullPointerException ex) {} } //----------------------------------------------------------------------- public void testWrite_charArrayToOutputStream_Encoding() throws Exception { String str = new String(inData, "US-ASCII"); ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true); IOUtils.write(str.toCharArray(), out, "UTF16"); out.off(); out.flush(); byte[] bytes = baout.toByteArray(); bytes = new String(bytes, "UTF16").getBytes("US-ASCII"); assertTrue("Content differs", Arrays.equals(inData, bytes)); } public void testWrite_charArrayToOutputStream_Encoding_nullData() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true); IOUtils.write((char[]) null, out); out.off(); out.flush(); assertEquals("Sizes differ", 0, baout.size()); } public void testWrite_charArrayToOutputStream_Encoding_nullStream() throws Exception { String str = new String(inData, "US-ASCII"); try { IOUtils.write(str.toCharArray(), (OutputStream) null); fail(); } catch (NullPointerException ex) {} } public void testWrite_charArrayToOutputStream_nullEncoding() throws Exception { String str = new String(inData, "US-ASCII"); ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true); IOUtils.write(str.toCharArray(), out, (String) null); out.off(); out.flush(); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); } //----------------------------------------------------------------------- public void testWrite_charArrayToWriter() throws Exception { String str = new String(inData, "US-ASCII"); ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); IOUtils.write(str.toCharArray(), writer); out.off(); writer.flush(); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); } public void testWrite_charArrayToWriter_Encoding_nullData() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); IOUtils.write((char[]) null, writer); out.off(); writer.flush(); assertEquals("Sizes differ", 0, baout.size()); } public void testWrite_charArrayToWriter_Encoding_nullStream() throws Exception { String str = new String(inData, "US-ASCII"); try { IOUtils.write(str.toCharArray(), (Writer) null); fail(); } catch (NullPointerException ex) {} } //----------------------------------------------------------------------- public void testWriteLines_OutputStream() throws Exception { Object[] data = new Object[] { "hello", new StringBuffer("world"), "", "this is", null, "some text"}; List list = Arrays.asList(data); ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, false, true); IOUtils.writeLines(list, "*", out); out.off(); out.flush(); String expected = "hello*world**this is**some text*"; String actual = baout.toString(); assertEquals(expected, actual); } public void testWriteLines_OutputStream_nullData() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, false, true); IOUtils.writeLines((List) null, "*", out); out.off(); out.flush(); assertEquals("Sizes differ", 0, baout.size()); } public void testWriteLines_OutputStream_nullSeparator() throws Exception { Object[] data = new Object[] {"hello", "world"}; List list = Arrays.asList(data); ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, false, true); IOUtils.writeLines(list, (String) null, out); out.off(); out.flush(); String expected = "hello" + IOUtils.LINE_SEPARATOR + "world" + IOUtils.LINE_SEPARATOR; String actual = baout.toString(); assertEquals(expected, actual); } public void testWriteLines_OutputStream_nullStream() throws Exception { Object[] data = new Object[] {"hello", "world"}; List list = Arrays.asList(data); try { IOUtils.writeLines(list, "*", (OutputStream) null); fail(); } catch (NullPointerException ex) {} } //----------------------------------------------------------------------- public void testWriteLines_OutputStream_Encoding() throws Exception { Object[] data = new Object[] { "hello\u8364", new StringBuffer("world"), "", "this is", null, "some text"}; List list = Arrays.asList(data); ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, false, true); IOUtils.writeLines(list, "*", out, "UTF-8"); out.off(); out.flush(); String expected = "hello\u8364*world**this is**some text*"; String actual = baout.toString("UTF-8"); assertEquals(expected, actual); } public void testWriteLines_OutputStream_Encoding_nullData() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, false, true); IOUtils.writeLines((List) null, "*", out, "US-ASCII"); out.off(); out.flush(); assertEquals("Sizes differ", 0, baout.size()); } public void testWriteLines_OutputStream_Encoding_nullSeparator() throws Exception { Object[] data = new Object[] {"hello", "world"}; List list = Arrays.asList(data); ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, false, true); IOUtils.writeLines(list, (String) null, out, "US-ASCII"); out.off(); out.flush(); String expected = "hello" + IOUtils.LINE_SEPARATOR + "world" + IOUtils.LINE_SEPARATOR; String actual = baout.toString(); assertEquals(expected, actual); } public void testWriteLines_OutputStream_Encoding_nullStream() throws Exception { Object[] data = new Object[] {"hello", "world"}; List list = Arrays.asList(data); try { IOUtils.writeLines(list, "*", (OutputStream) null, "US-ASCII"); fail(); } catch (NullPointerException ex) {} } public void testWriteLines_OutputStream_Encoding_nullEncoding() throws Exception { Object[] data = new Object[] { "hello", new StringBuffer("world"), "", "this is", null, "some text"}; List list = Arrays.asList(data); ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, false, true); IOUtils.writeLines(list, "*", out, (String) null); out.off(); out.flush(); String expected = "hello*world**this is**some text*"; String actual = baout.toString(); assertEquals(expected, actual); } //----------------------------------------------------------------------- public void testWriteLines_Writer() throws Exception { Object[] data = new Object[] { "hello", new StringBuffer("world"), "", "this is", null, "some text"}; List list = Arrays.asList(data); ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); IOUtils.writeLines(list, "*", writer); out.off(); writer.flush(); String expected = "hello*world**this is**some text*"; String actual = baout.toString(); assertEquals(expected, actual); } public void testWriteLines_Writer_nullData() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); IOUtils.writeLines((List) null, "*", writer); out.off(); writer.flush(); assertEquals("Sizes differ", 0, baout.size()); } public void testWriteLines_Writer_nullSeparator() throws Exception { Object[] data = new Object[] {"hello", "world"}; List list = Arrays.asList(data); ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); IOUtils.writeLines(list, (String) null, writer); out.off(); writer.flush(); String expected = "hello" + IOUtils.LINE_SEPARATOR + "world" + IOUtils.LINE_SEPARATOR; String actual = baout.toString(); assertEquals(expected, actual); } public void testWriteLines_Writer_nullStream() throws Exception { Object[] data = new Object[] {"hello", "world"}; List list = Arrays.asList(data); try { IOUtils.writeLines(list, "*", (Writer) null); fail(); } catch (NullPointerException ex) {} } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/FilenameUtilsTestCase.java0000644000175000017500000017022712125050425031162 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import org.apache.commons.io.testtools.FileBasedTestCase; /** * This is used to test FilenameUtils for correctness. * * @version $Id: FilenameUtilsTestCase.java 1302748 2012-03-20 01:35:32Z ggregory $ * @see FilenameUtils */ public class FilenameUtilsTestCase extends FileBasedTestCase { private static final String SEP = "" + File.separatorChar; private static final boolean WINDOWS = File.separatorChar == '\\'; private File testFile1; private File testFile2; private int testFile1Size; private int testFile2Size; public FilenameUtilsTestCase(String name) { super(name); testFile1 = new File(getTestDirectory(), "file1-test.txt"); testFile2 = new File(getTestDirectory(), "file1a-test.txt"); testFile1Size = (int)testFile1.length(); testFile2Size = (int)testFile2.length(); } /** @see junit.framework.TestCase#setUp() */ @Override protected void setUp() throws Exception { getTestDirectory().mkdirs(); createFile(testFile1, testFile1Size); createFile(testFile2, testFile2Size); FileUtils.deleteDirectory(getTestDirectory()); getTestDirectory().mkdirs(); createFile(testFile1, testFile1Size); createFile(testFile2, testFile2Size); } /** @see junit.framework.TestCase#tearDown() */ @Override protected void tearDown() throws Exception { FileUtils.deleteDirectory(getTestDirectory()); } //----------------------------------------------------------------------- public void testNormalize() throws Exception { assertEquals(null, FilenameUtils.normalize(null)); assertEquals(null, FilenameUtils.normalize(":")); assertEquals(null, FilenameUtils.normalize("1:\\a\\b\\c.txt")); assertEquals(null, FilenameUtils.normalize("1:")); assertEquals(null, FilenameUtils.normalize("1:a")); assertEquals(null, FilenameUtils.normalize("\\\\\\a\\b\\c.txt")); assertEquals(null, FilenameUtils.normalize("\\\\a")); assertEquals("a" + SEP + "b" + SEP + "c.txt", FilenameUtils.normalize("a\\b/c.txt")); assertEquals("" + SEP + "a" + SEP + "b" + SEP + "c.txt", FilenameUtils.normalize("\\a\\b/c.txt")); assertEquals("C:" + SEP + "a" + SEP + "b" + SEP + "c.txt", FilenameUtils.normalize("C:\\a\\b/c.txt")); assertEquals("" + SEP + "" + SEP + "server" + SEP + "a" + SEP + "b" + SEP + "c.txt", FilenameUtils.normalize("\\\\server\\a\\b/c.txt")); assertEquals("~" + SEP + "a" + SEP + "b" + SEP + "c.txt", FilenameUtils.normalize("~\\a\\b/c.txt")); assertEquals("~user" + SEP + "a" + SEP + "b" + SEP + "c.txt", FilenameUtils.normalize("~user\\a\\b/c.txt")); assertEquals("a" + SEP + "c", FilenameUtils.normalize("a/b/../c")); assertEquals("c", FilenameUtils.normalize("a/b/../../c")); assertEquals("c" + SEP, FilenameUtils.normalize("a/b/../../c/")); assertEquals(null, FilenameUtils.normalize("a/b/../../../c")); assertEquals("a" + SEP, FilenameUtils.normalize("a/b/..")); assertEquals("a" + SEP, FilenameUtils.normalize("a/b/../")); assertEquals("", FilenameUtils.normalize("a/b/../..")); assertEquals("", FilenameUtils.normalize("a/b/../../")); assertEquals(null, FilenameUtils.normalize("a/b/../../..")); assertEquals("a" + SEP + "d", FilenameUtils.normalize("a/b/../c/../d")); assertEquals("a" + SEP + "d" + SEP, FilenameUtils.normalize("a/b/../c/../d/")); assertEquals("a" + SEP + "b" + SEP + "d", FilenameUtils.normalize("a/b//d")); assertEquals("a" + SEP + "b" + SEP, FilenameUtils.normalize("a/b/././.")); assertEquals("a" + SEP + "b" + SEP, FilenameUtils.normalize("a/b/./././")); assertEquals("a" + SEP, FilenameUtils.normalize("./a/")); assertEquals("a", FilenameUtils.normalize("./a")); assertEquals("", FilenameUtils.normalize("./")); assertEquals("", FilenameUtils.normalize(".")); assertEquals(null, FilenameUtils.normalize("../a")); assertEquals(null, FilenameUtils.normalize("..")); assertEquals("", FilenameUtils.normalize("")); assertEquals(SEP + "a", FilenameUtils.normalize("/a")); assertEquals(SEP + "a" + SEP, FilenameUtils.normalize("/a/")); assertEquals(SEP + "a" + SEP + "c", FilenameUtils.normalize("/a/b/../c")); assertEquals(SEP + "c", FilenameUtils.normalize("/a/b/../../c")); assertEquals(null, FilenameUtils.normalize("/a/b/../../../c")); assertEquals(SEP + "a" + SEP, FilenameUtils.normalize("/a/b/..")); assertEquals(SEP + "", FilenameUtils.normalize("/a/b/../..")); assertEquals(null, FilenameUtils.normalize("/a/b/../../..")); assertEquals(SEP + "a" + SEP + "d", FilenameUtils.normalize("/a/b/../c/../d")); assertEquals(SEP + "a" + SEP + "b" + SEP + "d", FilenameUtils.normalize("/a/b//d")); assertEquals(SEP + "a" + SEP + "b" + SEP, FilenameUtils.normalize("/a/b/././.")); assertEquals(SEP + "a", FilenameUtils.normalize("/./a")); assertEquals(SEP + "", FilenameUtils.normalize("/./")); assertEquals(SEP + "", FilenameUtils.normalize("/.")); assertEquals(null, FilenameUtils.normalize("/../a")); assertEquals(null, FilenameUtils.normalize("/..")); assertEquals(SEP + "", FilenameUtils.normalize("/")); assertEquals("~" + SEP + "a", FilenameUtils.normalize("~/a")); assertEquals("~" + SEP + "a" + SEP, FilenameUtils.normalize("~/a/")); assertEquals("~" + SEP + "a" + SEP + "c", FilenameUtils.normalize("~/a/b/../c")); assertEquals("~" + SEP + "c", FilenameUtils.normalize("~/a/b/../../c")); assertEquals(null, FilenameUtils.normalize("~/a/b/../../../c")); assertEquals("~" + SEP + "a" + SEP, FilenameUtils.normalize("~/a/b/..")); assertEquals("~" + SEP + "", FilenameUtils.normalize("~/a/b/../..")); assertEquals(null, FilenameUtils.normalize("~/a/b/../../..")); assertEquals("~" + SEP + "a" + SEP + "d", FilenameUtils.normalize("~/a/b/../c/../d")); assertEquals("~" + SEP + "a" + SEP + "b" + SEP + "d", FilenameUtils.normalize("~/a/b//d")); assertEquals("~" + SEP + "a" + SEP + "b" + SEP, FilenameUtils.normalize("~/a/b/././.")); assertEquals("~" + SEP + "a", FilenameUtils.normalize("~/./a")); assertEquals("~" + SEP, FilenameUtils.normalize("~/./")); assertEquals("~" + SEP, FilenameUtils.normalize("~/.")); assertEquals(null, FilenameUtils.normalize("~/../a")); assertEquals(null, FilenameUtils.normalize("~/..")); assertEquals("~" + SEP, FilenameUtils.normalize("~/")); assertEquals("~" + SEP, FilenameUtils.normalize("~")); assertEquals("~user" + SEP + "a", FilenameUtils.normalize("~user/a")); assertEquals("~user" + SEP + "a" + SEP, FilenameUtils.normalize("~user/a/")); assertEquals("~user" + SEP + "a" + SEP + "c", FilenameUtils.normalize("~user/a/b/../c")); assertEquals("~user" + SEP + "c", FilenameUtils.normalize("~user/a/b/../../c")); assertEquals(null, FilenameUtils.normalize("~user/a/b/../../../c")); assertEquals("~user" + SEP + "a" + SEP, FilenameUtils.normalize("~user/a/b/..")); assertEquals("~user" + SEP + "", FilenameUtils.normalize("~user/a/b/../..")); assertEquals(null, FilenameUtils.normalize("~user/a/b/../../..")); assertEquals("~user" + SEP + "a" + SEP + "d", FilenameUtils.normalize("~user/a/b/../c/../d")); assertEquals("~user" + SEP + "a" + SEP + "b" + SEP + "d", FilenameUtils.normalize("~user/a/b//d")); assertEquals("~user" + SEP + "a" + SEP + "b" + SEP, FilenameUtils.normalize("~user/a/b/././.")); assertEquals("~user" + SEP + "a", FilenameUtils.normalize("~user/./a")); assertEquals("~user" + SEP + "", FilenameUtils.normalize("~user/./")); assertEquals("~user" + SEP + "", FilenameUtils.normalize("~user/.")); assertEquals(null, FilenameUtils.normalize("~user/../a")); assertEquals(null, FilenameUtils.normalize("~user/..")); assertEquals("~user" + SEP, FilenameUtils.normalize("~user/")); assertEquals("~user" + SEP, FilenameUtils.normalize("~user")); assertEquals("C:" + SEP + "a", FilenameUtils.normalize("C:/a")); assertEquals("C:" + SEP + "a" + SEP, FilenameUtils.normalize("C:/a/")); assertEquals("C:" + SEP + "a" + SEP + "c", FilenameUtils.normalize("C:/a/b/../c")); assertEquals("C:" + SEP + "c", FilenameUtils.normalize("C:/a/b/../../c")); assertEquals(null, FilenameUtils.normalize("C:/a/b/../../../c")); assertEquals("C:" + SEP + "a" + SEP, FilenameUtils.normalize("C:/a/b/..")); assertEquals("C:" + SEP + "", FilenameUtils.normalize("C:/a/b/../..")); assertEquals(null, FilenameUtils.normalize("C:/a/b/../../..")); assertEquals("C:" + SEP + "a" + SEP + "d", FilenameUtils.normalize("C:/a/b/../c/../d")); assertEquals("C:" + SEP + "a" + SEP + "b" + SEP + "d", FilenameUtils.normalize("C:/a/b//d")); assertEquals("C:" + SEP + "a" + SEP + "b" + SEP, FilenameUtils.normalize("C:/a/b/././.")); assertEquals("C:" + SEP + "a", FilenameUtils.normalize("C:/./a")); assertEquals("C:" + SEP + "", FilenameUtils.normalize("C:/./")); assertEquals("C:" + SEP + "", FilenameUtils.normalize("C:/.")); assertEquals(null, FilenameUtils.normalize("C:/../a")); assertEquals(null, FilenameUtils.normalize("C:/..")); assertEquals("C:" + SEP + "", FilenameUtils.normalize("C:/")); assertEquals("C:" + "a", FilenameUtils.normalize("C:a")); assertEquals("C:" + "a" + SEP, FilenameUtils.normalize("C:a/")); assertEquals("C:" + "a" + SEP + "c", FilenameUtils.normalize("C:a/b/../c")); assertEquals("C:" + "c", FilenameUtils.normalize("C:a/b/../../c")); assertEquals(null, FilenameUtils.normalize("C:a/b/../../../c")); assertEquals("C:" + "a" + SEP, FilenameUtils.normalize("C:a/b/..")); assertEquals("C:" + "", FilenameUtils.normalize("C:a/b/../..")); assertEquals(null, FilenameUtils.normalize("C:a/b/../../..")); assertEquals("C:" + "a" + SEP + "d", FilenameUtils.normalize("C:a/b/../c/../d")); assertEquals("C:" + "a" + SEP + "b" + SEP + "d", FilenameUtils.normalize("C:a/b//d")); assertEquals("C:" + "a" + SEP + "b" + SEP, FilenameUtils.normalize("C:a/b/././.")); assertEquals("C:" + "a", FilenameUtils.normalize("C:./a")); assertEquals("C:" + "", FilenameUtils.normalize("C:./")); assertEquals("C:" + "", FilenameUtils.normalize("C:.")); assertEquals(null, FilenameUtils.normalize("C:../a")); assertEquals(null, FilenameUtils.normalize("C:..")); assertEquals("C:" + "", FilenameUtils.normalize("C:")); assertEquals(SEP + SEP + "server" + SEP + "a", FilenameUtils.normalize("//server/a")); assertEquals(SEP + SEP + "server" + SEP + "a" + SEP, FilenameUtils.normalize("//server/a/")); assertEquals(SEP + SEP + "server" + SEP + "a" + SEP + "c", FilenameUtils.normalize("//server/a/b/../c")); assertEquals(SEP + SEP + "server" + SEP + "c", FilenameUtils.normalize("//server/a/b/../../c")); assertEquals(null, FilenameUtils.normalize("//server/a/b/../../../c")); assertEquals(SEP + SEP + "server" + SEP + "a" + SEP, FilenameUtils.normalize("//server/a/b/..")); assertEquals(SEP + SEP + "server" + SEP + "", FilenameUtils.normalize("//server/a/b/../..")); assertEquals(null, FilenameUtils.normalize("//server/a/b/../../..")); assertEquals(SEP + SEP + "server" + SEP + "a" + SEP + "d", FilenameUtils.normalize("//server/a/b/../c/../d")); assertEquals(SEP + SEP + "server" + SEP + "a" + SEP + "b" + SEP + "d", FilenameUtils.normalize("//server/a/b//d")); assertEquals(SEP + SEP + "server" + SEP + "a" + SEP + "b" + SEP, FilenameUtils.normalize("//server/a/b/././.")); assertEquals(SEP + SEP + "server" + SEP + "a", FilenameUtils.normalize("//server/./a")); assertEquals(SEP + SEP + "server" + SEP + "", FilenameUtils.normalize("//server/./")); assertEquals(SEP + SEP + "server" + SEP + "", FilenameUtils.normalize("//server/.")); assertEquals(null, FilenameUtils.normalize("//server/../a")); assertEquals(null, FilenameUtils.normalize("//server/..")); assertEquals(SEP + SEP + "server" + SEP + "", FilenameUtils.normalize("//server/")); } public void testNormalizeUnixWin() throws Exception { // Normalize (Unix Separator) assertEquals("/a/c/", FilenameUtils.normalize("/a/b/../c/", true)); assertEquals("/a/c/", FilenameUtils.normalize("\\a\\b\\..\\c\\", true)); // Normalize (Windows Separator) assertEquals("\\a\\c\\", FilenameUtils.normalize("/a/b/../c/", false)); assertEquals("\\a\\c\\", FilenameUtils.normalize("\\a\\b\\..\\c\\", false)); } //----------------------------------------------------------------------- public void testNormalizeNoEndSeparator() throws Exception { assertEquals(null, FilenameUtils.normalizeNoEndSeparator(null)); assertEquals(null, FilenameUtils.normalizeNoEndSeparator(":")); assertEquals(null, FilenameUtils.normalizeNoEndSeparator("1:\\a\\b\\c.txt")); assertEquals(null, FilenameUtils.normalizeNoEndSeparator("1:")); assertEquals(null, FilenameUtils.normalizeNoEndSeparator("1:a")); assertEquals(null, FilenameUtils.normalizeNoEndSeparator("\\\\\\a\\b\\c.txt")); assertEquals(null, FilenameUtils.normalizeNoEndSeparator("\\\\a")); assertEquals("a" + SEP + "b" + SEP + "c.txt", FilenameUtils.normalizeNoEndSeparator("a\\b/c.txt")); assertEquals("" + SEP + "a" + SEP + "b" + SEP + "c.txt", FilenameUtils.normalizeNoEndSeparator("\\a\\b/c.txt")); assertEquals("C:" + SEP + "a" + SEP + "b" + SEP + "c.txt", FilenameUtils.normalizeNoEndSeparator("C:\\a\\b/c.txt")); assertEquals("" + SEP + "" + SEP + "server" + SEP + "a" + SEP + "b" + SEP + "c.txt", FilenameUtils.normalizeNoEndSeparator("\\\\server\\a\\b/c.txt")); assertEquals("~" + SEP + "a" + SEP + "b" + SEP + "c.txt", FilenameUtils.normalizeNoEndSeparator("~\\a\\b/c.txt")); assertEquals("~user" + SEP + "a" + SEP + "b" + SEP + "c.txt", FilenameUtils.normalizeNoEndSeparator("~user\\a\\b/c.txt")); assertEquals("a" + SEP + "c", FilenameUtils.normalizeNoEndSeparator("a/b/../c")); assertEquals("c", FilenameUtils.normalizeNoEndSeparator("a/b/../../c")); assertEquals("c", FilenameUtils.normalizeNoEndSeparator("a/b/../../c/")); assertEquals(null, FilenameUtils.normalizeNoEndSeparator("a/b/../../../c")); assertEquals("a", FilenameUtils.normalizeNoEndSeparator("a/b/..")); assertEquals("a", FilenameUtils.normalizeNoEndSeparator("a/b/../")); assertEquals("", FilenameUtils.normalizeNoEndSeparator("a/b/../..")); assertEquals("", FilenameUtils.normalizeNoEndSeparator("a/b/../../")); assertEquals(null, FilenameUtils.normalizeNoEndSeparator("a/b/../../..")); assertEquals("a" + SEP + "d", FilenameUtils.normalizeNoEndSeparator("a/b/../c/../d")); assertEquals("a" + SEP + "d", FilenameUtils.normalizeNoEndSeparator("a/b/../c/../d/")); assertEquals("a" + SEP + "b" + SEP + "d", FilenameUtils.normalizeNoEndSeparator("a/b//d")); assertEquals("a" + SEP + "b", FilenameUtils.normalizeNoEndSeparator("a/b/././.")); assertEquals("a" + SEP + "b", FilenameUtils.normalizeNoEndSeparator("a/b/./././")); assertEquals("a", FilenameUtils.normalizeNoEndSeparator("./a/")); assertEquals("a", FilenameUtils.normalizeNoEndSeparator("./a")); assertEquals("", FilenameUtils.normalizeNoEndSeparator("./")); assertEquals("", FilenameUtils.normalizeNoEndSeparator(".")); assertEquals(null, FilenameUtils.normalizeNoEndSeparator("../a")); assertEquals(null, FilenameUtils.normalizeNoEndSeparator("..")); assertEquals("", FilenameUtils.normalizeNoEndSeparator("")); assertEquals(SEP + "a", FilenameUtils.normalizeNoEndSeparator("/a")); assertEquals(SEP + "a", FilenameUtils.normalizeNoEndSeparator("/a/")); assertEquals(SEP + "a" + SEP + "c", FilenameUtils.normalizeNoEndSeparator("/a/b/../c")); assertEquals(SEP + "c", FilenameUtils.normalizeNoEndSeparator("/a/b/../../c")); assertEquals(null, FilenameUtils.normalizeNoEndSeparator("/a/b/../../../c")); assertEquals(SEP + "a", FilenameUtils.normalizeNoEndSeparator("/a/b/..")); assertEquals(SEP + "", FilenameUtils.normalizeNoEndSeparator("/a/b/../..")); assertEquals(null, FilenameUtils.normalizeNoEndSeparator("/a/b/../../..")); assertEquals(SEP + "a" + SEP + "d", FilenameUtils.normalizeNoEndSeparator("/a/b/../c/../d")); assertEquals(SEP + "a" + SEP + "b" + SEP + "d", FilenameUtils.normalizeNoEndSeparator("/a/b//d")); assertEquals(SEP + "a" + SEP + "b", FilenameUtils.normalizeNoEndSeparator("/a/b/././.")); assertEquals(SEP + "a", FilenameUtils.normalizeNoEndSeparator("/./a")); assertEquals(SEP + "", FilenameUtils.normalizeNoEndSeparator("/./")); assertEquals(SEP + "", FilenameUtils.normalizeNoEndSeparator("/.")); assertEquals(null, FilenameUtils.normalizeNoEndSeparator("/../a")); assertEquals(null, FilenameUtils.normalizeNoEndSeparator("/..")); assertEquals(SEP + "", FilenameUtils.normalizeNoEndSeparator("/")); assertEquals("~" + SEP + "a", FilenameUtils.normalizeNoEndSeparator("~/a")); assertEquals("~" + SEP + "a", FilenameUtils.normalizeNoEndSeparator("~/a/")); assertEquals("~" + SEP + "a" + SEP + "c", FilenameUtils.normalizeNoEndSeparator("~/a/b/../c")); assertEquals("~" + SEP + "c", FilenameUtils.normalizeNoEndSeparator("~/a/b/../../c")); assertEquals(null, FilenameUtils.normalizeNoEndSeparator("~/a/b/../../../c")); assertEquals("~" + SEP + "a", FilenameUtils.normalizeNoEndSeparator("~/a/b/..")); assertEquals("~" + SEP + "", FilenameUtils.normalizeNoEndSeparator("~/a/b/../..")); assertEquals(null, FilenameUtils.normalizeNoEndSeparator("~/a/b/../../..")); assertEquals("~" + SEP + "a" + SEP + "d", FilenameUtils.normalizeNoEndSeparator("~/a/b/../c/../d")); assertEquals("~" + SEP + "a" + SEP + "b" + SEP + "d", FilenameUtils.normalizeNoEndSeparator("~/a/b//d")); assertEquals("~" + SEP + "a" + SEP + "b", FilenameUtils.normalizeNoEndSeparator("~/a/b/././.")); assertEquals("~" + SEP + "a", FilenameUtils.normalizeNoEndSeparator("~/./a")); assertEquals("~" + SEP, FilenameUtils.normalizeNoEndSeparator("~/./")); assertEquals("~" + SEP, FilenameUtils.normalizeNoEndSeparator("~/.")); assertEquals(null, FilenameUtils.normalizeNoEndSeparator("~/../a")); assertEquals(null, FilenameUtils.normalizeNoEndSeparator("~/..")); assertEquals("~" + SEP, FilenameUtils.normalizeNoEndSeparator("~/")); assertEquals("~" + SEP, FilenameUtils.normalizeNoEndSeparator("~")); assertEquals("~user" + SEP + "a", FilenameUtils.normalizeNoEndSeparator("~user/a")); assertEquals("~user" + SEP + "a", FilenameUtils.normalizeNoEndSeparator("~user/a/")); assertEquals("~user" + SEP + "a" + SEP + "c", FilenameUtils.normalizeNoEndSeparator("~user/a/b/../c")); assertEquals("~user" + SEP + "c", FilenameUtils.normalizeNoEndSeparator("~user/a/b/../../c")); assertEquals(null, FilenameUtils.normalizeNoEndSeparator("~user/a/b/../../../c")); assertEquals("~user" + SEP + "a", FilenameUtils.normalizeNoEndSeparator("~user/a/b/..")); assertEquals("~user" + SEP + "", FilenameUtils.normalizeNoEndSeparator("~user/a/b/../..")); assertEquals(null, FilenameUtils.normalizeNoEndSeparator("~user/a/b/../../..")); assertEquals("~user" + SEP + "a" + SEP + "d", FilenameUtils.normalizeNoEndSeparator("~user/a/b/../c/../d")); assertEquals("~user" + SEP + "a" + SEP + "b" + SEP + "d", FilenameUtils.normalizeNoEndSeparator("~user/a/b//d")); assertEquals("~user" + SEP + "a" + SEP + "b", FilenameUtils.normalizeNoEndSeparator("~user/a/b/././.")); assertEquals("~user" + SEP + "a", FilenameUtils.normalizeNoEndSeparator("~user/./a")); assertEquals("~user" + SEP + "", FilenameUtils.normalizeNoEndSeparator("~user/./")); assertEquals("~user" + SEP + "", FilenameUtils.normalizeNoEndSeparator("~user/.")); assertEquals(null, FilenameUtils.normalizeNoEndSeparator("~user/../a")); assertEquals(null, FilenameUtils.normalizeNoEndSeparator("~user/..")); assertEquals("~user" + SEP, FilenameUtils.normalizeNoEndSeparator("~user/")); assertEquals("~user" + SEP, FilenameUtils.normalizeNoEndSeparator("~user")); assertEquals("C:" + SEP + "a", FilenameUtils.normalizeNoEndSeparator("C:/a")); assertEquals("C:" + SEP + "a", FilenameUtils.normalizeNoEndSeparator("C:/a/")); assertEquals("C:" + SEP + "a" + SEP + "c", FilenameUtils.normalizeNoEndSeparator("C:/a/b/../c")); assertEquals("C:" + SEP + "c", FilenameUtils.normalizeNoEndSeparator("C:/a/b/../../c")); assertEquals(null, FilenameUtils.normalizeNoEndSeparator("C:/a/b/../../../c")); assertEquals("C:" + SEP + "a", FilenameUtils.normalizeNoEndSeparator("C:/a/b/..")); assertEquals("C:" + SEP + "", FilenameUtils.normalizeNoEndSeparator("C:/a/b/../..")); assertEquals(null, FilenameUtils.normalizeNoEndSeparator("C:/a/b/../../..")); assertEquals("C:" + SEP + "a" + SEP + "d", FilenameUtils.normalizeNoEndSeparator("C:/a/b/../c/../d")); assertEquals("C:" + SEP + "a" + SEP + "b" + SEP + "d", FilenameUtils.normalizeNoEndSeparator("C:/a/b//d")); assertEquals("C:" + SEP + "a" + SEP + "b", FilenameUtils.normalizeNoEndSeparator("C:/a/b/././.")); assertEquals("C:" + SEP + "a", FilenameUtils.normalizeNoEndSeparator("C:/./a")); assertEquals("C:" + SEP + "", FilenameUtils.normalizeNoEndSeparator("C:/./")); assertEquals("C:" + SEP + "", FilenameUtils.normalizeNoEndSeparator("C:/.")); assertEquals(null, FilenameUtils.normalizeNoEndSeparator("C:/../a")); assertEquals(null, FilenameUtils.normalizeNoEndSeparator("C:/..")); assertEquals("C:" + SEP + "", FilenameUtils.normalizeNoEndSeparator("C:/")); assertEquals("C:" + "a", FilenameUtils.normalizeNoEndSeparator("C:a")); assertEquals("C:" + "a", FilenameUtils.normalizeNoEndSeparator("C:a/")); assertEquals("C:" + "a" + SEP + "c", FilenameUtils.normalizeNoEndSeparator("C:a/b/../c")); assertEquals("C:" + "c", FilenameUtils.normalizeNoEndSeparator("C:a/b/../../c")); assertEquals(null, FilenameUtils.normalizeNoEndSeparator("C:a/b/../../../c")); assertEquals("C:" + "a", FilenameUtils.normalizeNoEndSeparator("C:a/b/..")); assertEquals("C:" + "", FilenameUtils.normalizeNoEndSeparator("C:a/b/../..")); assertEquals(null, FilenameUtils.normalizeNoEndSeparator("C:a/b/../../..")); assertEquals("C:" + "a" + SEP + "d", FilenameUtils.normalizeNoEndSeparator("C:a/b/../c/../d")); assertEquals("C:" + "a" + SEP + "b" + SEP + "d", FilenameUtils.normalizeNoEndSeparator("C:a/b//d")); assertEquals("C:" + "a" + SEP + "b", FilenameUtils.normalizeNoEndSeparator("C:a/b/././.")); assertEquals("C:" + "a", FilenameUtils.normalizeNoEndSeparator("C:./a")); assertEquals("C:" + "", FilenameUtils.normalizeNoEndSeparator("C:./")); assertEquals("C:" + "", FilenameUtils.normalizeNoEndSeparator("C:.")); assertEquals(null, FilenameUtils.normalizeNoEndSeparator("C:../a")); assertEquals(null, FilenameUtils.normalizeNoEndSeparator("C:..")); assertEquals("C:" + "", FilenameUtils.normalizeNoEndSeparator("C:")); assertEquals(SEP + SEP + "server" + SEP + "a", FilenameUtils.normalizeNoEndSeparator("//server/a")); assertEquals(SEP + SEP + "server" + SEP + "a", FilenameUtils.normalizeNoEndSeparator("//server/a/")); assertEquals(SEP + SEP + "server" + SEP + "a" + SEP + "c", FilenameUtils.normalizeNoEndSeparator("//server/a/b/../c")); assertEquals(SEP + SEP + "server" + SEP + "c", FilenameUtils.normalizeNoEndSeparator("//server/a/b/../../c")); assertEquals(null, FilenameUtils.normalizeNoEndSeparator("//server/a/b/../../../c")); assertEquals(SEP + SEP + "server" + SEP + "a", FilenameUtils.normalizeNoEndSeparator("//server/a/b/..")); assertEquals(SEP + SEP + "server" + SEP + "", FilenameUtils.normalizeNoEndSeparator("//server/a/b/../..")); assertEquals(null, FilenameUtils.normalizeNoEndSeparator("//server/a/b/../../..")); assertEquals(SEP + SEP + "server" + SEP + "a" + SEP + "d", FilenameUtils.normalizeNoEndSeparator("//server/a/b/../c/../d")); assertEquals(SEP + SEP + "server" + SEP + "a" + SEP + "b" + SEP + "d", FilenameUtils.normalizeNoEndSeparator("//server/a/b//d")); assertEquals(SEP + SEP + "server" + SEP + "a" + SEP + "b", FilenameUtils.normalizeNoEndSeparator("//server/a/b/././.")); assertEquals(SEP + SEP + "server" + SEP + "a", FilenameUtils.normalizeNoEndSeparator("//server/./a")); assertEquals(SEP + SEP + "server" + SEP + "", FilenameUtils.normalizeNoEndSeparator("//server/./")); assertEquals(SEP + SEP + "server" + SEP + "", FilenameUtils.normalizeNoEndSeparator("//server/.")); assertEquals(null, FilenameUtils.normalizeNoEndSeparator("//server/../a")); assertEquals(null, FilenameUtils.normalizeNoEndSeparator("//server/..")); assertEquals(SEP + SEP + "server" + SEP + "", FilenameUtils.normalizeNoEndSeparator("//server/")); } public void testNormalizeNoEndSeparatorUnixWin() throws Exception { // Normalize (Unix Separator) assertEquals("/a/c", FilenameUtils.normalizeNoEndSeparator("/a/b/../c/", true)); assertEquals("/a/c", FilenameUtils.normalizeNoEndSeparator("\\a\\b\\..\\c\\", true)); // Normalize (Windows Separator) assertEquals("\\a\\c", FilenameUtils.normalizeNoEndSeparator("/a/b/../c/", false)); assertEquals("\\a\\c", FilenameUtils.normalizeNoEndSeparator("\\a\\b\\..\\c\\", false)); } //----------------------------------------------------------------------- public void testConcat() { assertEquals(null, FilenameUtils.concat("", null)); assertEquals(null, FilenameUtils.concat(null, null)); assertEquals(null, FilenameUtils.concat(null, "")); assertEquals(null, FilenameUtils.concat(null, "a")); assertEquals(SEP + "a", FilenameUtils.concat(null, "/a")); assertEquals(null, FilenameUtils.concat("", ":")); // invalid prefix assertEquals(null, FilenameUtils.concat(":", "")); // invalid prefix assertEquals("f" + SEP, FilenameUtils.concat("", "f/")); assertEquals("f", FilenameUtils.concat("", "f")); assertEquals("a" + SEP + "f" + SEP, FilenameUtils.concat("a/", "f/")); assertEquals("a" + SEP + "f", FilenameUtils.concat("a", "f")); assertEquals("a" + SEP + "b" + SEP + "f" + SEP, FilenameUtils.concat("a/b/", "f/")); assertEquals("a" + SEP + "b" + SEP + "f", FilenameUtils.concat("a/b", "f")); assertEquals("a" + SEP + "f" + SEP, FilenameUtils.concat("a/b/", "../f/")); assertEquals("a" + SEP + "f", FilenameUtils.concat("a/b", "../f")); assertEquals("a" + SEP + "c" + SEP + "g" + SEP, FilenameUtils.concat("a/b/../c/", "f/../g/")); assertEquals("a" + SEP + "c" + SEP + "g", FilenameUtils.concat("a/b/../c", "f/../g")); assertEquals("a" + SEP + "c.txt" + SEP + "f", FilenameUtils.concat("a/c.txt", "f")); assertEquals(SEP + "f" + SEP, FilenameUtils.concat("", "/f/")); assertEquals(SEP + "f", FilenameUtils.concat("", "/f")); assertEquals(SEP + "f" + SEP, FilenameUtils.concat("a/", "/f/")); assertEquals(SEP + "f", FilenameUtils.concat("a", "/f")); assertEquals(SEP + "c" + SEP + "d", FilenameUtils.concat("a/b/", "/c/d")); assertEquals("C:c" + SEP + "d", FilenameUtils.concat("a/b/", "C:c/d")); assertEquals("C:" + SEP + "c" + SEP + "d", FilenameUtils.concat("a/b/", "C:/c/d")); assertEquals("~" + SEP + "c" + SEP + "d", FilenameUtils.concat("a/b/", "~/c/d")); assertEquals("~user" + SEP + "c" + SEP + "d", FilenameUtils.concat("a/b/", "~user/c/d")); assertEquals("~" + SEP, FilenameUtils.concat("a/b/", "~")); assertEquals("~user" + SEP, FilenameUtils.concat("a/b/", "~user")); } //----------------------------------------------------------------------- public void testSeparatorsToUnix() { assertEquals(null, FilenameUtils.separatorsToUnix(null)); assertEquals("/a/b/c", FilenameUtils.separatorsToUnix("/a/b/c")); assertEquals("/a/b/c.txt", FilenameUtils.separatorsToUnix("/a/b/c.txt")); assertEquals("/a/b/c", FilenameUtils.separatorsToUnix("/a/b\\c")); assertEquals("/a/b/c", FilenameUtils.separatorsToUnix("\\a\\b\\c")); assertEquals("D:/a/b/c", FilenameUtils.separatorsToUnix("D:\\a\\b\\c")); } public void testSeparatorsToWindows() { assertEquals(null, FilenameUtils.separatorsToWindows(null)); assertEquals("\\a\\b\\c", FilenameUtils.separatorsToWindows("\\a\\b\\c")); assertEquals("\\a\\b\\c.txt", FilenameUtils.separatorsToWindows("\\a\\b\\c.txt")); assertEquals("\\a\\b\\c", FilenameUtils.separatorsToWindows("\\a\\b/c")); assertEquals("\\a\\b\\c", FilenameUtils.separatorsToWindows("/a/b/c")); assertEquals("D:\\a\\b\\c", FilenameUtils.separatorsToWindows("D:/a/b/c")); } public void testSeparatorsToSystem() { if (WINDOWS) { assertEquals(null, FilenameUtils.separatorsToSystem(null)); assertEquals("\\a\\b\\c", FilenameUtils.separatorsToSystem("\\a\\b\\c")); assertEquals("\\a\\b\\c.txt", FilenameUtils.separatorsToSystem("\\a\\b\\c.txt")); assertEquals("\\a\\b\\c", FilenameUtils.separatorsToSystem("\\a\\b/c")); assertEquals("\\a\\b\\c", FilenameUtils.separatorsToSystem("/a/b/c")); assertEquals("D:\\a\\b\\c", FilenameUtils.separatorsToSystem("D:/a/b/c")); } else { assertEquals(null, FilenameUtils.separatorsToSystem(null)); assertEquals("/a/b/c", FilenameUtils.separatorsToSystem("/a/b/c")); assertEquals("/a/b/c.txt", FilenameUtils.separatorsToSystem("/a/b/c.txt")); assertEquals("/a/b/c", FilenameUtils.separatorsToSystem("/a/b\\c")); assertEquals("/a/b/c", FilenameUtils.separatorsToSystem("\\a\\b\\c")); assertEquals("D:/a/b/c", FilenameUtils.separatorsToSystem("D:\\a\\b\\c")); } } //----------------------------------------------------------------------- public void testGetPrefixLength() { assertEquals(-1, FilenameUtils.getPrefixLength(null)); assertEquals(-1, FilenameUtils.getPrefixLength(":")); assertEquals(-1, FilenameUtils.getPrefixLength("1:\\a\\b\\c.txt")); assertEquals(-1, FilenameUtils.getPrefixLength("1:")); assertEquals(-1, FilenameUtils.getPrefixLength("1:a")); assertEquals(-1, FilenameUtils.getPrefixLength("\\\\\\a\\b\\c.txt")); assertEquals(-1, FilenameUtils.getPrefixLength("\\\\a")); assertEquals(0, FilenameUtils.getPrefixLength("")); assertEquals(1, FilenameUtils.getPrefixLength("\\")); assertEquals(2, FilenameUtils.getPrefixLength("C:")); assertEquals(3, FilenameUtils.getPrefixLength("C:\\")); assertEquals(9, FilenameUtils.getPrefixLength("//server/")); assertEquals(2, FilenameUtils.getPrefixLength("~")); assertEquals(2, FilenameUtils.getPrefixLength("~/")); assertEquals(6, FilenameUtils.getPrefixLength("~user")); assertEquals(6, FilenameUtils.getPrefixLength("~user/")); assertEquals(0, FilenameUtils.getPrefixLength("a\\b\\c.txt")); assertEquals(1, FilenameUtils.getPrefixLength("\\a\\b\\c.txt")); assertEquals(2, FilenameUtils.getPrefixLength("C:a\\b\\c.txt")); assertEquals(3, FilenameUtils.getPrefixLength("C:\\a\\b\\c.txt")); assertEquals(9, FilenameUtils.getPrefixLength("\\\\server\\a\\b\\c.txt")); assertEquals(0, FilenameUtils.getPrefixLength("a/b/c.txt")); assertEquals(1, FilenameUtils.getPrefixLength("/a/b/c.txt")); assertEquals(3, FilenameUtils.getPrefixLength("C:/a/b/c.txt")); assertEquals(9, FilenameUtils.getPrefixLength("//server/a/b/c.txt")); assertEquals(2, FilenameUtils.getPrefixLength("~/a/b/c.txt")); assertEquals(6, FilenameUtils.getPrefixLength("~user/a/b/c.txt")); assertEquals(0, FilenameUtils.getPrefixLength("a\\b\\c.txt")); assertEquals(1, FilenameUtils.getPrefixLength("\\a\\b\\c.txt")); assertEquals(2, FilenameUtils.getPrefixLength("~\\a\\b\\c.txt")); assertEquals(6, FilenameUtils.getPrefixLength("~user\\a\\b\\c.txt")); } public void testIndexOfLastSeparator() { assertEquals(-1, FilenameUtils.indexOfLastSeparator(null)); assertEquals(-1, FilenameUtils.indexOfLastSeparator("noseperator.inthispath")); assertEquals(3, FilenameUtils.indexOfLastSeparator("a/b/c")); assertEquals(3, FilenameUtils.indexOfLastSeparator("a\\b\\c")); } public void testIndexOfExtension() { assertEquals(-1, FilenameUtils.indexOfExtension(null)); assertEquals(-1, FilenameUtils.indexOfExtension("file")); assertEquals(4, FilenameUtils.indexOfExtension("file.txt")); assertEquals(13, FilenameUtils.indexOfExtension("a.txt/b.txt/c.txt")); assertEquals(-1, FilenameUtils.indexOfExtension("a/b/c")); assertEquals(-1, FilenameUtils.indexOfExtension("a\\b\\c")); assertEquals(-1, FilenameUtils.indexOfExtension("a/b.notextension/c")); assertEquals(-1, FilenameUtils.indexOfExtension("a\\b.notextension\\c")); } //----------------------------------------------------------------------- public void testGetPrefix() { assertEquals(null, FilenameUtils.getPrefix(null)); assertEquals(null, FilenameUtils.getPrefix(":")); assertEquals(null, FilenameUtils.getPrefix("1:\\a\\b\\c.txt")); assertEquals(null, FilenameUtils.getPrefix("1:")); assertEquals(null, FilenameUtils.getPrefix("1:a")); assertEquals(null, FilenameUtils.getPrefix("\\\\\\a\\b\\c.txt")); assertEquals(null, FilenameUtils.getPrefix("\\\\a")); assertEquals("", FilenameUtils.getPrefix("")); assertEquals("\\", FilenameUtils.getPrefix("\\")); assertEquals("C:", FilenameUtils.getPrefix("C:")); assertEquals("C:\\", FilenameUtils.getPrefix("C:\\")); assertEquals("//server/", FilenameUtils.getPrefix("//server/")); assertEquals("~/", FilenameUtils.getPrefix("~")); assertEquals("~/", FilenameUtils.getPrefix("~/")); assertEquals("~user/", FilenameUtils.getPrefix("~user")); assertEquals("~user/", FilenameUtils.getPrefix("~user/")); assertEquals("", FilenameUtils.getPrefix("a\\b\\c.txt")); assertEquals("\\", FilenameUtils.getPrefix("\\a\\b\\c.txt")); assertEquals("C:\\", FilenameUtils.getPrefix("C:\\a\\b\\c.txt")); assertEquals("\\\\server\\", FilenameUtils.getPrefix("\\\\server\\a\\b\\c.txt")); assertEquals("", FilenameUtils.getPrefix("a/b/c.txt")); assertEquals("/", FilenameUtils.getPrefix("/a/b/c.txt")); assertEquals("C:/", FilenameUtils.getPrefix("C:/a/b/c.txt")); assertEquals("//server/", FilenameUtils.getPrefix("//server/a/b/c.txt")); assertEquals("~/", FilenameUtils.getPrefix("~/a/b/c.txt")); assertEquals("~user/", FilenameUtils.getPrefix("~user/a/b/c.txt")); assertEquals("", FilenameUtils.getPrefix("a\\b\\c.txt")); assertEquals("\\", FilenameUtils.getPrefix("\\a\\b\\c.txt")); assertEquals("~\\", FilenameUtils.getPrefix("~\\a\\b\\c.txt")); assertEquals("~user\\", FilenameUtils.getPrefix("~user\\a\\b\\c.txt")); } public void testGetPath() { assertEquals(null, FilenameUtils.getPath(null)); assertEquals("", FilenameUtils.getPath("noseperator.inthispath")); assertEquals("", FilenameUtils.getPath("/noseperator.inthispath")); assertEquals("", FilenameUtils.getPath("\\noseperator.inthispath")); assertEquals("a/b/", FilenameUtils.getPath("a/b/c.txt")); assertEquals("a/b/", FilenameUtils.getPath("a/b/c")); assertEquals("a/b/c/", FilenameUtils.getPath("a/b/c/")); assertEquals("a\\b\\", FilenameUtils.getPath("a\\b\\c")); assertEquals(null, FilenameUtils.getPath(":")); assertEquals(null, FilenameUtils.getPath("1:/a/b/c.txt")); assertEquals(null, FilenameUtils.getPath("1:")); assertEquals(null, FilenameUtils.getPath("1:a")); assertEquals(null, FilenameUtils.getPath("///a/b/c.txt")); assertEquals(null, FilenameUtils.getPath("//a")); assertEquals("", FilenameUtils.getPath("")); assertEquals("", FilenameUtils.getPath("C:")); assertEquals("", FilenameUtils.getPath("C:/")); assertEquals("", FilenameUtils.getPath("//server/")); assertEquals("", FilenameUtils.getPath("~")); assertEquals("", FilenameUtils.getPath("~/")); assertEquals("", FilenameUtils.getPath("~user")); assertEquals("", FilenameUtils.getPath("~user/")); assertEquals("a/b/", FilenameUtils.getPath("a/b/c.txt")); assertEquals("a/b/", FilenameUtils.getPath("/a/b/c.txt")); assertEquals("", FilenameUtils.getPath("C:a")); assertEquals("a/b/", FilenameUtils.getPath("C:a/b/c.txt")); assertEquals("a/b/", FilenameUtils.getPath("C:/a/b/c.txt")); assertEquals("a/b/", FilenameUtils.getPath("//server/a/b/c.txt")); assertEquals("a/b/", FilenameUtils.getPath("~/a/b/c.txt")); assertEquals("a/b/", FilenameUtils.getPath("~user/a/b/c.txt")); } public void testGetPathNoEndSeparator() { assertEquals(null, FilenameUtils.getPath(null)); assertEquals("", FilenameUtils.getPath("noseperator.inthispath")); assertEquals("", FilenameUtils.getPathNoEndSeparator("/noseperator.inthispath")); assertEquals("", FilenameUtils.getPathNoEndSeparator("\\noseperator.inthispath")); assertEquals("a/b", FilenameUtils.getPathNoEndSeparator("a/b/c.txt")); assertEquals("a/b", FilenameUtils.getPathNoEndSeparator("a/b/c")); assertEquals("a/b/c", FilenameUtils.getPathNoEndSeparator("a/b/c/")); assertEquals("a\\b", FilenameUtils.getPathNoEndSeparator("a\\b\\c")); assertEquals(null, FilenameUtils.getPathNoEndSeparator(":")); assertEquals(null, FilenameUtils.getPathNoEndSeparator("1:/a/b/c.txt")); assertEquals(null, FilenameUtils.getPathNoEndSeparator("1:")); assertEquals(null, FilenameUtils.getPathNoEndSeparator("1:a")); assertEquals(null, FilenameUtils.getPathNoEndSeparator("///a/b/c.txt")); assertEquals(null, FilenameUtils.getPathNoEndSeparator("//a")); assertEquals("", FilenameUtils.getPathNoEndSeparator("")); assertEquals("", FilenameUtils.getPathNoEndSeparator("C:")); assertEquals("", FilenameUtils.getPathNoEndSeparator("C:/")); assertEquals("", FilenameUtils.getPathNoEndSeparator("//server/")); assertEquals("", FilenameUtils.getPathNoEndSeparator("~")); assertEquals("", FilenameUtils.getPathNoEndSeparator("~/")); assertEquals("", FilenameUtils.getPathNoEndSeparator("~user")); assertEquals("", FilenameUtils.getPathNoEndSeparator("~user/")); assertEquals("a/b", FilenameUtils.getPathNoEndSeparator("a/b/c.txt")); assertEquals("a/b", FilenameUtils.getPathNoEndSeparator("/a/b/c.txt")); assertEquals("", FilenameUtils.getPathNoEndSeparator("C:a")); assertEquals("a/b", FilenameUtils.getPathNoEndSeparator("C:a/b/c.txt")); assertEquals("a/b", FilenameUtils.getPathNoEndSeparator("C:/a/b/c.txt")); assertEquals("a/b", FilenameUtils.getPathNoEndSeparator("//server/a/b/c.txt")); assertEquals("a/b", FilenameUtils.getPathNoEndSeparator("~/a/b/c.txt")); assertEquals("a/b", FilenameUtils.getPathNoEndSeparator("~user/a/b/c.txt")); } public void testGetFullPath() { assertEquals(null, FilenameUtils.getFullPath(null)); assertEquals("", FilenameUtils.getFullPath("noseperator.inthispath")); assertEquals("a/b/", FilenameUtils.getFullPath("a/b/c.txt")); assertEquals("a/b/", FilenameUtils.getFullPath("a/b/c")); assertEquals("a/b/c/", FilenameUtils.getFullPath("a/b/c/")); assertEquals("a\\b\\", FilenameUtils.getFullPath("a\\b\\c")); assertEquals(null, FilenameUtils.getFullPath(":")); assertEquals(null, FilenameUtils.getFullPath("1:/a/b/c.txt")); assertEquals(null, FilenameUtils.getFullPath("1:")); assertEquals(null, FilenameUtils.getFullPath("1:a")); assertEquals(null, FilenameUtils.getFullPath("///a/b/c.txt")); assertEquals(null, FilenameUtils.getFullPath("//a")); assertEquals("", FilenameUtils.getFullPath("")); assertEquals("C:", FilenameUtils.getFullPath("C:")); assertEquals("C:/", FilenameUtils.getFullPath("C:/")); assertEquals("//server/", FilenameUtils.getFullPath("//server/")); assertEquals("~/", FilenameUtils.getFullPath("~")); assertEquals("~/", FilenameUtils.getFullPath("~/")); assertEquals("~user/", FilenameUtils.getFullPath("~user")); assertEquals("~user/", FilenameUtils.getFullPath("~user/")); assertEquals("a/b/", FilenameUtils.getFullPath("a/b/c.txt")); assertEquals("/a/b/", FilenameUtils.getFullPath("/a/b/c.txt")); assertEquals("C:", FilenameUtils.getFullPath("C:a")); assertEquals("C:a/b/", FilenameUtils.getFullPath("C:a/b/c.txt")); assertEquals("C:/a/b/", FilenameUtils.getFullPath("C:/a/b/c.txt")); assertEquals("//server/a/b/", FilenameUtils.getFullPath("//server/a/b/c.txt")); assertEquals("~/a/b/", FilenameUtils.getFullPath("~/a/b/c.txt")); assertEquals("~user/a/b/", FilenameUtils.getFullPath("~user/a/b/c.txt")); } public void testGetFullPathNoEndSeparator() { assertEquals(null, FilenameUtils.getFullPathNoEndSeparator(null)); assertEquals("", FilenameUtils.getFullPathNoEndSeparator("noseperator.inthispath")); assertEquals("a/b", FilenameUtils.getFullPathNoEndSeparator("a/b/c.txt")); assertEquals("a/b", FilenameUtils.getFullPathNoEndSeparator("a/b/c")); assertEquals("a/b/c", FilenameUtils.getFullPathNoEndSeparator("a/b/c/")); assertEquals("a\\b", FilenameUtils.getFullPathNoEndSeparator("a\\b\\c")); assertEquals(null, FilenameUtils.getFullPathNoEndSeparator(":")); assertEquals(null, FilenameUtils.getFullPathNoEndSeparator("1:/a/b/c.txt")); assertEquals(null, FilenameUtils.getFullPathNoEndSeparator("1:")); assertEquals(null, FilenameUtils.getFullPathNoEndSeparator("1:a")); assertEquals(null, FilenameUtils.getFullPathNoEndSeparator("///a/b/c.txt")); assertEquals(null, FilenameUtils.getFullPathNoEndSeparator("//a")); assertEquals("", FilenameUtils.getFullPathNoEndSeparator("")); assertEquals("C:", FilenameUtils.getFullPathNoEndSeparator("C:")); assertEquals("C:/", FilenameUtils.getFullPathNoEndSeparator("C:/")); assertEquals("//server/", FilenameUtils.getFullPathNoEndSeparator("//server/")); assertEquals("~", FilenameUtils.getFullPathNoEndSeparator("~")); assertEquals("~/", FilenameUtils.getFullPathNoEndSeparator("~/")); assertEquals("~user", FilenameUtils.getFullPathNoEndSeparator("~user")); assertEquals("~user/", FilenameUtils.getFullPathNoEndSeparator("~user/")); assertEquals("a/b", FilenameUtils.getFullPathNoEndSeparator("a/b/c.txt")); assertEquals("/a/b", FilenameUtils.getFullPathNoEndSeparator("/a/b/c.txt")); assertEquals("C:", FilenameUtils.getFullPathNoEndSeparator("C:a")); assertEquals("C:a/b", FilenameUtils.getFullPathNoEndSeparator("C:a/b/c.txt")); assertEquals("C:/a/b", FilenameUtils.getFullPathNoEndSeparator("C:/a/b/c.txt")); assertEquals("//server/a/b", FilenameUtils.getFullPathNoEndSeparator("//server/a/b/c.txt")); assertEquals("~/a/b", FilenameUtils.getFullPathNoEndSeparator("~/a/b/c.txt")); assertEquals("~user/a/b", FilenameUtils.getFullPathNoEndSeparator("~user/a/b/c.txt")); } /** * Test for https://issues.apache.org/jira/browse/IO-248 */ public void testGetFullPathNoEndSeparator_IO_248() { // Test single separator assertEquals("/", FilenameUtils.getFullPathNoEndSeparator("/")); assertEquals("\\", FilenameUtils.getFullPathNoEndSeparator("\\")); // Test one level directory assertEquals("/", FilenameUtils.getFullPathNoEndSeparator("/abc")); assertEquals("\\", FilenameUtils.getFullPathNoEndSeparator("\\abc")); // Test one level directory assertEquals("/abc", FilenameUtils.getFullPathNoEndSeparator("/abc/xyz")); assertEquals("\\abc", FilenameUtils.getFullPathNoEndSeparator("\\abc\\xyz")); } public void testGetName() { assertEquals(null, FilenameUtils.getName(null)); assertEquals("noseperator.inthispath", FilenameUtils.getName("noseperator.inthispath")); assertEquals("c.txt", FilenameUtils.getName("a/b/c.txt")); assertEquals("c", FilenameUtils.getName("a/b/c")); assertEquals("", FilenameUtils.getName("a/b/c/")); assertEquals("c", FilenameUtils.getName("a\\b\\c")); } public void testGetBaseName() { assertEquals(null, FilenameUtils.getBaseName(null)); assertEquals("noseperator", FilenameUtils.getBaseName("noseperator.inthispath")); assertEquals("c", FilenameUtils.getBaseName("a/b/c.txt")); assertEquals("c", FilenameUtils.getBaseName("a/b/c")); assertEquals("", FilenameUtils.getBaseName("a/b/c/")); assertEquals("c", FilenameUtils.getBaseName("a\\b\\c")); assertEquals("file.txt", FilenameUtils.getBaseName("file.txt.bak")); } public void testGetExtension() { assertEquals(null, FilenameUtils.getExtension(null)); assertEquals("ext", FilenameUtils.getExtension("file.ext")); assertEquals("", FilenameUtils.getExtension("README")); assertEquals("com", FilenameUtils.getExtension("domain.dot.com")); assertEquals("jpeg", FilenameUtils.getExtension("image.jpeg")); assertEquals("", FilenameUtils.getExtension("a.b/c")); assertEquals("txt", FilenameUtils.getExtension("a.b/c.txt")); assertEquals("", FilenameUtils.getExtension("a/b/c")); assertEquals("", FilenameUtils.getExtension("a.b\\c")); assertEquals("txt", FilenameUtils.getExtension("a.b\\c.txt")); assertEquals("", FilenameUtils.getExtension("a\\b\\c")); assertEquals("", FilenameUtils.getExtension("C:\\temp\\foo.bar\\README")); assertEquals("ext", FilenameUtils.getExtension("../filename.ext")); } public void testRemoveExtension() { assertEquals(null, FilenameUtils.removeExtension(null)); assertEquals("file", FilenameUtils.removeExtension("file.ext")); assertEquals("README", FilenameUtils.removeExtension("README")); assertEquals("domain.dot", FilenameUtils.removeExtension("domain.dot.com")); assertEquals("image", FilenameUtils.removeExtension("image.jpeg")); assertEquals("a.b/c", FilenameUtils.removeExtension("a.b/c")); assertEquals("a.b/c", FilenameUtils.removeExtension("a.b/c.txt")); assertEquals("a/b/c", FilenameUtils.removeExtension("a/b/c")); assertEquals("a.b\\c", FilenameUtils.removeExtension("a.b\\c")); assertEquals("a.b\\c", FilenameUtils.removeExtension("a.b\\c.txt")); assertEquals("a\\b\\c", FilenameUtils.removeExtension("a\\b\\c")); assertEquals("C:\\temp\\foo.bar\\README", FilenameUtils.removeExtension("C:\\temp\\foo.bar\\README")); assertEquals("../filename", FilenameUtils.removeExtension("../filename.ext")); } //----------------------------------------------------------------------- public void testEquals() { assertTrue(FilenameUtils.equals(null, null)); assertFalse(FilenameUtils.equals(null, "")); assertFalse(FilenameUtils.equals("", null)); assertTrue(FilenameUtils.equals("", "")); assertTrue(FilenameUtils.equals("file.txt", "file.txt")); assertFalse(FilenameUtils.equals("file.txt", "FILE.TXT")); assertFalse(FilenameUtils.equals("a\\b\\file.txt", "a/b/file.txt")); } public void testEqualsOnSystem() { assertTrue(FilenameUtils.equalsOnSystem(null, null)); assertFalse(FilenameUtils.equalsOnSystem(null, "")); assertFalse(FilenameUtils.equalsOnSystem("", null)); assertTrue(FilenameUtils.equalsOnSystem("", "")); assertTrue(FilenameUtils.equalsOnSystem("file.txt", "file.txt")); assertEquals(WINDOWS, FilenameUtils.equalsOnSystem("file.txt", "FILE.TXT")); assertFalse(FilenameUtils.equalsOnSystem("a\\b\\file.txt", "a/b/file.txt")); } //----------------------------------------------------------------------- public void testEqualsNormalized() { assertTrue(FilenameUtils.equalsNormalized(null, null)); assertFalse(FilenameUtils.equalsNormalized(null, "")); assertFalse(FilenameUtils.equalsNormalized("", null)); assertTrue(FilenameUtils.equalsNormalized("", "")); assertTrue(FilenameUtils.equalsNormalized("file.txt", "file.txt")); assertFalse(FilenameUtils.equalsNormalized("file.txt", "FILE.TXT")); assertTrue(FilenameUtils.equalsNormalized("a\\b\\file.txt", "a/b/file.txt")); assertFalse(FilenameUtils.equalsNormalized("a/b/", "a/b")); } public void testEqualsNormalizedOnSystem() { assertTrue(FilenameUtils.equalsNormalizedOnSystem(null, null)); assertFalse(FilenameUtils.equalsNormalizedOnSystem(null, "")); assertFalse(FilenameUtils.equalsNormalizedOnSystem("", null)); assertTrue(FilenameUtils.equalsNormalizedOnSystem("", "")); assertTrue(FilenameUtils.equalsNormalizedOnSystem("file.txt", "file.txt")); assertEquals(WINDOWS, FilenameUtils.equalsNormalizedOnSystem("file.txt", "FILE.TXT")); assertTrue(FilenameUtils.equalsNormalizedOnSystem("a\\b\\file.txt", "a/b/file.txt")); assertFalse(FilenameUtils.equalsNormalizedOnSystem("a/b/", "a/b")); } /** * Test for https://issues.apache.org/jira/browse/IO-128 */ public void testEqualsNormalizedError_IO_128() { try { FilenameUtils.equalsNormalizedOnSystem("//file.txt", "file.txt"); fail("Invalid normalized first file"); } catch(NullPointerException e) { // expected result } try { FilenameUtils.equalsNormalizedOnSystem("file.txt", "//file.txt"); fail("Invalid normalized second file"); } catch(NullPointerException e) { // expected result } try { FilenameUtils.equalsNormalizedOnSystem("//file.txt", "//file.txt"); fail("Invalid normalized both filse"); } catch(NullPointerException e) { // expected result } } public void testEquals_fullControl() { assertFalse(FilenameUtils.equals("file.txt", "FILE.TXT", true, IOCase.SENSITIVE)); assertTrue(FilenameUtils.equals("file.txt", "FILE.TXT", true, IOCase.INSENSITIVE)); assertEquals(WINDOWS, FilenameUtils.equals("file.txt", "FILE.TXT", true, IOCase.SYSTEM)); assertFalse(FilenameUtils.equals("file.txt", "FILE.TXT", true, null)); } //----------------------------------------------------------------------- public void testIsExtension() { assertFalse(FilenameUtils.isExtension(null, (String) null)); assertFalse(FilenameUtils.isExtension("file.txt", (String) null)); assertTrue(FilenameUtils.isExtension("file", (String) null)); assertFalse(FilenameUtils.isExtension("file.txt", "")); assertTrue(FilenameUtils.isExtension("file", "")); assertTrue(FilenameUtils.isExtension("file.txt", "txt")); assertFalse(FilenameUtils.isExtension("file.txt", "rtf")); assertFalse(FilenameUtils.isExtension("a/b/file.txt", (String) null)); assertFalse(FilenameUtils.isExtension("a/b/file.txt", "")); assertTrue(FilenameUtils.isExtension("a/b/file.txt", "txt")); assertFalse(FilenameUtils.isExtension("a/b/file.txt", "rtf")); assertFalse(FilenameUtils.isExtension("a.b/file.txt", (String) null)); assertFalse(FilenameUtils.isExtension("a.b/file.txt", "")); assertTrue(FilenameUtils.isExtension("a.b/file.txt", "txt")); assertFalse(FilenameUtils.isExtension("a.b/file.txt", "rtf")); assertFalse(FilenameUtils.isExtension("a\\b\\file.txt", (String) null)); assertFalse(FilenameUtils.isExtension("a\\b\\file.txt", "")); assertTrue(FilenameUtils.isExtension("a\\b\\file.txt", "txt")); assertFalse(FilenameUtils.isExtension("a\\b\\file.txt", "rtf")); assertFalse(FilenameUtils.isExtension("a.b\\file.txt", (String) null)); assertFalse(FilenameUtils.isExtension("a.b\\file.txt", "")); assertTrue(FilenameUtils.isExtension("a.b\\file.txt", "txt")); assertFalse(FilenameUtils.isExtension("a.b\\file.txt", "rtf")); assertFalse(FilenameUtils.isExtension("a.b\\file.txt", "TXT")); } public void testIsExtensionArray() { assertFalse(FilenameUtils.isExtension(null, (String[]) null)); assertFalse(FilenameUtils.isExtension("file.txt", (String[]) null)); assertTrue(FilenameUtils.isExtension("file", (String[]) null)); assertFalse(FilenameUtils.isExtension("file.txt", new String[0])); assertTrue(FilenameUtils.isExtension("file.txt", new String[] {"txt"})); assertFalse(FilenameUtils.isExtension("file.txt", new String[] {"rtf"})); assertTrue(FilenameUtils.isExtension("file", new String[] {"rtf", ""})); assertTrue(FilenameUtils.isExtension("file.txt", new String[] {"rtf", "txt"})); assertFalse(FilenameUtils.isExtension("a/b/file.txt", (String[]) null)); assertFalse(FilenameUtils.isExtension("a/b/file.txt", new String[0])); assertTrue(FilenameUtils.isExtension("a/b/file.txt", new String[] {"txt"})); assertFalse(FilenameUtils.isExtension("a/b/file.txt", new String[] {"rtf"})); assertTrue(FilenameUtils.isExtension("a/b/file.txt", new String[] {"rtf", "txt"})); assertFalse(FilenameUtils.isExtension("a.b/file.txt", (String[]) null)); assertFalse(FilenameUtils.isExtension("a.b/file.txt", new String[0])); assertTrue(FilenameUtils.isExtension("a.b/file.txt", new String[] {"txt"})); assertFalse(FilenameUtils.isExtension("a.b/file.txt", new String[] {"rtf"})); assertTrue(FilenameUtils.isExtension("a.b/file.txt", new String[] {"rtf", "txt"})); assertFalse(FilenameUtils.isExtension("a\\b\\file.txt", (String[]) null)); assertFalse(FilenameUtils.isExtension("a\\b\\file.txt", new String[0])); assertTrue(FilenameUtils.isExtension("a\\b\\file.txt", new String[] {"txt"})); assertFalse(FilenameUtils.isExtension("a\\b\\file.txt", new String[] {"rtf"})); assertTrue(FilenameUtils.isExtension("a\\b\\file.txt", new String[] {"rtf", "txt"})); assertFalse(FilenameUtils.isExtension("a.b\\file.txt", (String[]) null)); assertFalse(FilenameUtils.isExtension("a.b\\file.txt", new String[0])); assertTrue(FilenameUtils.isExtension("a.b\\file.txt", new String[] {"txt"})); assertFalse(FilenameUtils.isExtension("a.b\\file.txt", new String[] {"rtf"})); assertTrue(FilenameUtils.isExtension("a.b\\file.txt", new String[] {"rtf", "txt"})); assertFalse(FilenameUtils.isExtension("a.b\\file.txt", new String[] {"TXT"})); assertFalse(FilenameUtils.isExtension("a.b\\file.txt", new String[] {"TXT", "RTF"})); } public void testIsExtensionCollection() { assertFalse(FilenameUtils.isExtension(null, (Collection) null)); assertFalse(FilenameUtils.isExtension("file.txt", (Collection) null)); assertTrue(FilenameUtils.isExtension("file", (Collection) null)); assertFalse(FilenameUtils.isExtension("file.txt", new ArrayList())); assertTrue(FilenameUtils.isExtension("file.txt", new ArrayList(Arrays.asList(new String[] {"txt"})))); assertFalse(FilenameUtils.isExtension("file.txt", new ArrayList(Arrays.asList(new String[] {"rtf"})))); assertTrue(FilenameUtils.isExtension("file", new ArrayList(Arrays.asList(new String[] {"rtf", ""})))); assertTrue(FilenameUtils.isExtension("file.txt", new ArrayList(Arrays.asList(new String[] {"rtf", "txt"})))); assertFalse(FilenameUtils.isExtension("a/b/file.txt", (Collection) null)); assertFalse(FilenameUtils.isExtension("a/b/file.txt", new ArrayList())); assertTrue(FilenameUtils.isExtension("a/b/file.txt", new ArrayList(Arrays.asList(new String[] {"txt"})))); assertFalse(FilenameUtils.isExtension("a/b/file.txt", new ArrayList(Arrays.asList(new String[] {"rtf"})))); assertTrue(FilenameUtils.isExtension("a/b/file.txt", new ArrayList(Arrays.asList(new String[] {"rtf", "txt"})))); assertFalse(FilenameUtils.isExtension("a.b/file.txt", (Collection) null)); assertFalse(FilenameUtils.isExtension("a.b/file.txt", new ArrayList())); assertTrue(FilenameUtils.isExtension("a.b/file.txt", new ArrayList(Arrays.asList(new String[] {"txt"})))); assertFalse(FilenameUtils.isExtension("a.b/file.txt", new ArrayList(Arrays.asList(new String[] {"rtf"})))); assertTrue(FilenameUtils.isExtension("a.b/file.txt", new ArrayList(Arrays.asList(new String[] {"rtf", "txt"})))); assertFalse(FilenameUtils.isExtension("a\\b\\file.txt", (Collection) null)); assertFalse(FilenameUtils.isExtension("a\\b\\file.txt", new ArrayList())); assertTrue(FilenameUtils.isExtension("a\\b\\file.txt", new ArrayList(Arrays.asList(new String[] {"txt"})))); assertFalse(FilenameUtils.isExtension("a\\b\\file.txt", new ArrayList(Arrays.asList(new String[] {"rtf"})))); assertTrue(FilenameUtils.isExtension("a\\b\\file.txt", new ArrayList(Arrays.asList(new String[] {"rtf", "txt"})))); assertFalse(FilenameUtils.isExtension("a.b\\file.txt", (Collection) null)); assertFalse(FilenameUtils.isExtension("a.b\\file.txt", new ArrayList())); assertTrue(FilenameUtils.isExtension("a.b\\file.txt", new ArrayList(Arrays.asList(new String[] {"txt"})))); assertFalse(FilenameUtils.isExtension("a.b\\file.txt", new ArrayList(Arrays.asList(new String[] {"rtf"})))); assertTrue(FilenameUtils.isExtension("a.b\\file.txt", new ArrayList(Arrays.asList(new String[] {"rtf", "txt"})))); assertFalse(FilenameUtils.isExtension("a.b\\file.txt", new ArrayList(Arrays.asList(new String[] {"TXT"})))); assertFalse(FilenameUtils.isExtension("a.b\\file.txt", new ArrayList(Arrays.asList(new String[] {"TXT", "RTF"})))); } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/FileUtilsDirectoryContainsTestCase.javalibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/FileUtilsDirectoryContainsTestCase.j0000644000175000017500000001413712125050425033212 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.io.File; import java.io.IOException; import org.apache.commons.io.testtools.FileBasedTestCase; import org.junit.Test; /** * This class ensure the correctness of {@link FileUtils#directoryContains(File,File)}. * * @see FileUtils#directoryContains(File, File) * @since 2.2 * @version $Id: FileUtilsDirectoryContainsTestCase.java 1308109 2012-04-01 13:31:20Z ggregory $ */ public class FileUtilsDirectoryContainsTestCase extends FileBasedTestCase { private File directory1; private File directory2; private File directory3; private File file1; private File file1ByRelativeDirectory2; private File file2; private File file2ByRelativeDirectory1; private File file3; final File top = getTestDirectory(); public FileUtilsDirectoryContainsTestCase(String name) { super(name); } @Override protected void setUp() throws Exception { top.mkdirs(); directory1 = new File(top, "directory1"); directory2 = new File(top, "directory2"); directory3 = new File(directory2, "directory3"); directory1.mkdir(); directory2.mkdir(); directory3.mkdir(); file1 = new File(directory1, "file1"); file2 = new File(directory2, "file2"); file3 = new File(top, "file3"); // Tests case with relative path file1ByRelativeDirectory2 = new File(getTestDirectory(), "directory2/../directory1/file1"); file2ByRelativeDirectory1 = new File(getTestDirectory(), "directory1/../directory2/file2"); FileUtils.touch(file1); FileUtils.touch(file2); FileUtils.touch(file3); } @Override protected void tearDown() throws Exception { FileUtils.deleteDirectory(top); } @Test public void testCanonicalPath() throws IOException { assertTrue(FileUtils.directoryContains(directory1, file1ByRelativeDirectory2)); assertTrue(FileUtils.directoryContains(directory2, file2ByRelativeDirectory1)); assertFalse(FileUtils.directoryContains(directory1, file2ByRelativeDirectory1)); assertFalse(FileUtils.directoryContains(directory2, file1ByRelativeDirectory2)); } @Test public void testDirectoryContainsDirectory() throws IOException { assertTrue(FileUtils.directoryContains(top, directory1)); assertTrue(FileUtils.directoryContains(top, directory2)); assertTrue(FileUtils.directoryContains(top, directory3)); assertTrue(FileUtils.directoryContains(directory2, directory3)); } @Test public void testDirectoryContainsFile() throws IOException { assertTrue(FileUtils.directoryContains(directory1, file1)); assertTrue(FileUtils.directoryContains(directory2, file2)); } @Test public void testDirectoryDoesNotContainFile() throws IOException { assertFalse(FileUtils.directoryContains(directory1, file2)); assertFalse(FileUtils.directoryContains(directory2, file1)); assertFalse(FileUtils.directoryContains(directory1, file3)); assertFalse(FileUtils.directoryContains(directory2, file3)); } @Test public void testDirectoryDoesNotContainsDirectory() throws IOException { assertFalse(FileUtils.directoryContains(directory1, top)); assertFalse(FileUtils.directoryContains(directory2, top)); assertFalse(FileUtils.directoryContains(directory3, top)); assertFalse(FileUtils.directoryContains(directory3, directory2)); } @Test public void testDirectoryDoesNotExist() throws IOException { final File dir = new File("DOESNOTEXIST"); assertFalse(dir.exists()); try { assertFalse(FileUtils.directoryContains(dir, file1)); fail("Expected " + IllegalArgumentException.class.getName()); } catch (IllegalArgumentException e) { // expected } } @Test public void testSameFile() throws IOException { try { assertTrue(FileUtils.directoryContains(file1, file1)); fail("Expected " + IllegalArgumentException.class.getName()); } catch (IllegalArgumentException e) { // expected } } @Test public void testFileDoesNotExist() throws IOException { assertFalse(FileUtils.directoryContains(top, null)); final File file = new File("DOESNOTEXIST"); assertFalse(file.exists()); assertFalse(FileUtils.directoryContains(top, file)); } /** * Test to demonstrate a file which does not exist returns false * @throws IOException */ @Test public void testFileDoesNotExistBug() throws IOException { final File file = new File(top, "DOESNOTEXIST"); assertTrue("Check directory exists", top.exists()); assertFalse("Check file does not exist", file.exists()); assertFalse("Direcory does not contain unrealized file", FileUtils.directoryContains(top, file)); } @Test public void testUnrealizedContainment() throws IOException { final File dir = new File("DOESNOTEXIST"); final File file = new File(dir, "DOESNOTEXIST2"); assertFalse(dir.exists()); assertFalse(file.exists()); try { assertTrue(FileUtils.directoryContains(dir, file)); } catch (IllegalArgumentException e) { // expected } } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/CharsetsTestCase.java0000644000175000017500000000423612125050425030171 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.nio.charset.Charset; import junit.framework.Assert; import org.junit.Test; /** * Tests {@link Charsets}. * * @version $Id: CharEncodingTest.java 1298985 2012-03-09 19:12:49Z ggregory $ */ public class CharsetsTestCase { @Test public void testToCharset() { Assert.assertEquals(Charset.defaultCharset(), Charsets.toCharset((String) null)); Assert.assertEquals(Charset.defaultCharset(), Charsets.toCharset((Charset) null)); Assert.assertEquals(Charset.defaultCharset(), Charsets.toCharset(Charset.defaultCharset())); Assert.assertEquals(Charset.forName("UTF-8"), Charsets.toCharset(Charset.forName("UTF-8"))); } @Test public void testIso8859_1() { Assert.assertEquals("ISO-8859-1", Charsets.ISO_8859_1.name()); } @Test public void testUsAscii() { Assert.assertEquals("US-ASCII", Charsets.US_ASCII.name()); } @Test public void testUtf16() { Assert.assertEquals("UTF-16", Charsets.UTF_16.name()); } @Test public void testUtf16Be() { Assert.assertEquals("UTF-16BE", Charsets.UTF_16BE.name()); } @Test public void testUtf16Le() { Assert.assertEquals("UTF-16LE", Charsets.UTF_16LE.name()); } @Test public void testUtf8() { Assert.assertEquals("UTF-8", Charsets.UTF_8.name()); } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/filefilter/0000755000175000017500000000000012125050425026236 5ustar ebourgebourglibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/filefilter/FileFilterTestCase.java0000644000175000017500000015007612125050425032573 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.filefilter; import java.io.File; import java.io.FileFilter; import java.io.FilenameFilter; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOCase; import org.apache.commons.io.IOUtils; import org.apache.commons.io.testtools.FileBasedTestCase; /** * Used to test FileFilterUtils. */ public class FileFilterTestCase extends FileBasedTestCase { /** * The subversion directory name. */ static final String SVN_DIR_NAME = ".svn"; private static final boolean WINDOWS = File.separatorChar == '\\'; public FileFilterTestCase(String name) { super(name); } @Override public void setUp() { getTestDirectory().mkdirs(); } @Override public void tearDown() throws Exception { FileUtils.deleteDirectory(getTestDirectory()); } public void assertFiltering(IOFileFilter filter, File file, boolean expected) throws Exception { // Note. This only tests the (File, String) version if the parent of // the File passed in is not null assertEquals( "Filter(File) " + filter.getClass().getName() + " not " + expected + " for " + file, expected, filter.accept(file)); if (file != null && file.getParentFile() != null) { assertEquals( "Filter(File, String) " + filter.getClass().getName() + " not " + expected + " for " + file, expected, filter.accept(file.getParentFile(), file.getName())); } else if (file == null) { assertEquals( "Filter(File, String) " + filter.getClass().getName() + " not " + expected + " for null", expected, filter.accept(file)); } assertNotNull(filter.toString()); } public void testSuffix() throws Exception { IOFileFilter filter = new SuffixFileFilter(new String[] { "tes", "est" }); File testFile = new File( "test" ); File fredFile = new File( "fred" ); assertFiltering(filter, new File("fred.tes"), true); assertFiltering(filter, new File("fred.est"), true); assertFiltering(filter, new File("fred.EST"), false); //case-sensitive assertFiltering(filter, new File("fred.exe"), false); filter = FileFilterUtils.or( FileFilterUtils.suffixFileFilter( "tes" ), FileFilterUtils.suffixFileFilter( "est" ) ); assertFiltering(filter, new File("fred"), false); assertFiltering(filter, new File(".tes"), true); assertFiltering(filter, new File("fred.test"), true); filter = new SuffixFileFilter("est"); assertFiltering(filter, new File("test"), true); assertFiltering(filter, new File("fred"), false); assertTrue( filter.accept( testFile.getParentFile(), testFile.getName() ) ); assertTrue( !filter.accept( fredFile.getParentFile(), fredFile.getName() ) ); List prefixes = Arrays.asList( new String[] { "ood", "red" } ); IOFileFilter listFilter = new SuffixFileFilter( prefixes ); assertTrue( !listFilter.accept( testFile.getParentFile(), testFile.getName() ) ); assertTrue( listFilter.accept( fredFile.getParentFile(), fredFile.getName() ) ); try { new SuffixFileFilter((String) null); fail(); } catch (IllegalArgumentException ex) { } try { new SuffixFileFilter((String[]) null); fail(); } catch (IllegalArgumentException ex) { } try { new SuffixFileFilter((List) null); fail(); } catch (IllegalArgumentException ex) { } } public void testSuffixCaseInsensitive() throws Exception { IOFileFilter filter = new SuffixFileFilter(new String[] { "tes", "est" }, IOCase.INSENSITIVE); assertFiltering(filter, new File("foo.tes"), true); assertFiltering(filter, new File("foo.est"), true); assertFiltering(filter, new File("foo.EST"), true); //case-sensitive assertFiltering(filter, new File("foo.TES"), true); //case-sensitive assertFiltering(filter, new File("foo.exe"), false); filter = new SuffixFileFilter("est", IOCase.INSENSITIVE); assertFiltering(filter, new File("test"), true); assertFiltering(filter, new File("TEST"), true); List suffixes = Arrays.asList( new String[] { "tes", "est" } ); filter = new SuffixFileFilter(suffixes, IOCase.INSENSITIVE); assertFiltering(filter, new File("bar.tes"), true); assertFiltering(filter, new File("bar.est"), true); assertFiltering(filter, new File("bar.EST"), true); //case-sensitive assertFiltering(filter, new File("bar.TES"), true); //case-sensitive assertFiltering(filter, new File("bar.exe"), false); try { new SuffixFileFilter((String) null, IOCase.INSENSITIVE); fail(); } catch (IllegalArgumentException ex) { } try { new SuffixFileFilter((String[]) null, IOCase.INSENSITIVE); fail(); } catch (IllegalArgumentException ex) { } try { new SuffixFileFilter((List) null, IOCase.INSENSITIVE); fail(); } catch (IllegalArgumentException ex) { } // FileFilterUtils.suffixFileFilter(String, IOCase) tests filter = FileFilterUtils.suffixFileFilter("est", IOCase.INSENSITIVE); assertFiltering(filter, new File("test"), true); assertFiltering(filter, new File("TEST"), true); try { FileFilterUtils.suffixFileFilter((String) null, IOCase.INSENSITIVE); fail(); } catch (IllegalArgumentException ex) { } } public void testDirectory() throws Exception { // XXX: This test presumes the current working dir is the base dir of the source checkout. IOFileFilter filter = new DirectoryFileFilter(); assertFiltering(filter, new File("src/"), true); assertFiltering(filter, new File("src/main/java/"), true); assertFiltering(filter, new File("pom.xml"), false); assertFiltering(filter, new File("imaginary"), false); assertFiltering(filter, new File("imaginary/"), false); assertFiltering(filter, new File("LICENSE.txt"), false); assertSame(DirectoryFileFilter.DIRECTORY, DirectoryFileFilter.INSTANCE); } public void testFiles() throws Exception { // XXX: This test presumes the current working dir is the base dir of the source checkout. IOFileFilter filter = FileFileFilter.FILE; assertFiltering(filter, new File("src/"), false); assertFiltering(filter, new File("src/java/"), false); assertFiltering(filter, new File("pom.xml"), true); assertFiltering(filter, new File("imaginary"), false); assertFiltering(filter, new File("imaginary/"), false); assertFiltering(filter, new File("LICENSE.txt"), true); } public void testPrefix() throws Exception { IOFileFilter filter = new PrefixFileFilter(new String[] { "foo", "bar" }); File testFile = new File( "test" ); File fredFile = new File( "fred" ); assertFiltering(filter, new File("foo.test"), true); assertFiltering(filter, new File("FOO.test"), false); //case-sensitive assertFiltering(filter, new File("foo"), true); assertFiltering(filter, new File("bar"), true); assertFiltering(filter, new File("food/"), true); filter = FileFilterUtils.prefixFileFilter( "bar" ); assertFiltering(filter, new File("barred\\"), true); assertFiltering(filter, new File("test"), false); assertFiltering(filter, new File("fo_o.test"), false); assertFiltering(filter, new File("abar.exe"), false); filter = new PrefixFileFilter("tes"); assertFiltering(filter, new File("test"), true); assertFiltering(filter, new File("fred"), false); assertTrue( filter.accept( testFile.getParentFile(), testFile.getName() ) ); assertTrue( !filter.accept( fredFile.getParentFile(), fredFile.getName() ) ); List prefixes = Arrays.asList( new String[] { "foo", "fre" } ); IOFileFilter listFilter = new PrefixFileFilter( prefixes ); assertTrue( !listFilter.accept( testFile.getParentFile(), testFile.getName() ) ); assertTrue( listFilter.accept( fredFile.getParentFile(), fredFile.getName() ) ); try { new PrefixFileFilter((String) null); fail(); } catch (IllegalArgumentException ex) { } try { new PrefixFileFilter((String[]) null); fail(); } catch (IllegalArgumentException ex) { } try { new PrefixFileFilter((List) null); fail(); } catch (IllegalArgumentException ex) { } } public void testPrefixCaseInsensitive() throws Exception { IOFileFilter filter = new PrefixFileFilter(new String[] { "foo", "bar" }, IOCase.INSENSITIVE); assertFiltering(filter, new File("foo.test1"), true); assertFiltering(filter, new File("bar.test1"), true); assertFiltering(filter, new File("FOO.test1"), true); //case-sensitive assertFiltering(filter, new File("BAR.test1"), true); //case-sensitive filter = new PrefixFileFilter("bar", IOCase.INSENSITIVE); assertFiltering(filter, new File("foo.test2"), false); assertFiltering(filter, new File("bar.test2"), true); assertFiltering(filter, new File("FOO.test2"), false); //case-sensitive assertFiltering(filter, new File("BAR.test2"), true); //case-sensitive List prefixes = Arrays.asList( new String[] { "foo", "bar" } ); filter = new PrefixFileFilter(prefixes, IOCase.INSENSITIVE); assertFiltering(filter, new File("foo.test3"), true); assertFiltering(filter, new File("bar.test3"), true); assertFiltering(filter, new File("FOO.test3"), true); //case-sensitive assertFiltering(filter, new File("BAR.test3"), true); //case-sensitive try { new PrefixFileFilter((String) null, IOCase.INSENSITIVE); fail(); } catch (IllegalArgumentException ex) { } try { new PrefixFileFilter((String[]) null, IOCase.INSENSITIVE); fail(); } catch (IllegalArgumentException ex) { } try { new PrefixFileFilter((List) null, IOCase.INSENSITIVE); fail(); } catch (IllegalArgumentException ex) { } // FileFilterUtils.prefixFileFilter(String, IOCase) tests filter = FileFilterUtils.prefixFileFilter("bar", IOCase.INSENSITIVE); assertFiltering(filter, new File("foo.test2"), false); assertFiltering(filter, new File("bar.test2"), true); assertFiltering(filter, new File("FOO.test2"), false); //case-sensitive assertFiltering(filter, new File("BAR.test2"), true); //case-sensitive try { FileFilterUtils.prefixFileFilter((String) null, IOCase.INSENSITIVE); fail(); } catch (IllegalArgumentException ex) { } } public void testNameFilter() throws Exception { IOFileFilter filter = new NameFileFilter(new String[] { "foo", "bar" }); assertFiltering(filter, new File("foo"), true); assertFiltering(filter, new File("bar"), true); assertFiltering(filter, new File("fred"), false); filter = new NameFileFilter(new String[] { "foo", "bar" }, IOCase.SENSITIVE); assertFiltering(filter, new File("foo"), true); assertFiltering(filter, new File("bar"), true); assertFiltering(filter, new File("FOO"), false); assertFiltering(filter, new File("BAR"), false); filter = new NameFileFilter(new String[] { "foo", "bar" }, IOCase.INSENSITIVE); assertFiltering(filter, new File("foo"), true); assertFiltering(filter, new File("bar"), true); assertFiltering(filter, new File("FOO"), true); assertFiltering(filter, new File("BAR"), true); filter = new NameFileFilter(new String[] { "foo", "bar" }, IOCase.SYSTEM); assertFiltering(filter, new File("foo"), true); assertFiltering(filter, new File("bar"), true); assertFiltering(filter, new File("FOO"), WINDOWS); assertFiltering(filter, new File("BAR"), WINDOWS); filter = new NameFileFilter(new String[] { "foo", "bar" }, (IOCase) null); assertFiltering(filter, new File("foo"), true); assertFiltering(filter, new File("bar"), true); assertFiltering(filter, new File("FOO"), false); assertFiltering(filter, new File("BAR"), false); // repeat for a List java.util.ArrayList list = new java.util.ArrayList(); list.add("foo"); list.add("bar"); filter = new NameFileFilter(list); assertFiltering(filter, new File("foo"), true); assertFiltering(filter, new File("bar"), true); assertFiltering(filter, new File("fred"), false); filter = new NameFileFilter("foo"); assertFiltering(filter, new File("foo"), true); assertFiltering(filter, new File("FOO"), false); //case-sensitive assertFiltering(filter, new File("barfoo"), false); assertFiltering(filter, new File("foobar"), false); assertFiltering(filter, new File("fred"), false); // FileFilterUtils.nameFileFilter(String, IOCase) tests filter = FileFilterUtils.nameFileFilter("foo", IOCase.INSENSITIVE); assertFiltering(filter, new File("foo"), true); assertFiltering(filter, new File("FOO"), true); //case-insensitive assertFiltering(filter, new File("barfoo"), false); assertFiltering(filter, new File("foobar"), false); assertFiltering(filter, new File("fred"), false); } public void testNameFilterNullArgument() throws Exception { String test = null; try { new NameFileFilter(test); fail( "constructing a NameFileFilter with a null String argument should fail."); } catch( IllegalArgumentException iae ) { } try { FileFilterUtils.nameFileFilter(test, IOCase.INSENSITIVE); fail( "constructing a NameFileFilter with a null String argument should fail."); } catch( IllegalArgumentException iae ) { } } public void testNameFilterNullArrayArgument() throws Exception { String[] test = null; try { new NameFileFilter(test); fail( "constructing a NameFileFilter with a null String[] argument should fail."); } catch( IllegalArgumentException iae ) { } } public void testNameFilterNullListArgument() throws Exception { List test = null; try { new NameFileFilter(test); fail( "constructing a NameFileFilter with a null List argument should fail."); } catch( IllegalArgumentException iae ) { } } public void testTrue() throws Exception { IOFileFilter filter = FileFilterUtils.trueFileFilter(); assertFiltering(filter, new File("foo.test"), true); assertFiltering(filter, new File("foo"), true); assertFiltering(filter, null, true); assertSame(TrueFileFilter.TRUE, TrueFileFilter.INSTANCE); } public void testFalse() throws Exception { IOFileFilter filter = FileFilterUtils.falseFileFilter(); assertFiltering(filter, new File("foo.test"), false); assertFiltering(filter, new File("foo"), false); assertFiltering(filter, null, false); assertSame(FalseFileFilter.FALSE, FalseFileFilter.INSTANCE); } public void testNot() throws Exception { IOFileFilter filter = FileFilterUtils.notFileFilter(FileFilterUtils.trueFileFilter()); assertFiltering(filter, new File("foo.test"), false); assertFiltering(filter, new File("foo"), false); assertFiltering(filter, null, false); try { new NotFileFilter(null); fail(); } catch (IllegalArgumentException ex) { } } public void testAnd() throws Exception { IOFileFilter trueFilter = TrueFileFilter.INSTANCE; IOFileFilter falseFilter = FalseFileFilter.INSTANCE; assertFiltering(new AndFileFilter(trueFilter, trueFilter), new File("foo.test"), true); assertFiltering(new AndFileFilter(trueFilter, falseFilter), new File("foo.test"), false); assertFiltering(new AndFileFilter(falseFilter, trueFilter), new File("foo.test"), false); assertFiltering(new AndFileFilter(falseFilter, falseFilter), new File("foo.test"), false); List filters = new ArrayList(); assertFiltering( new AndFileFilter( filters ), new File( "test" ), false ); assertFiltering( new AndFileFilter(), new File( "test" ), false ); try { new AndFileFilter(falseFilter, null); fail(); } catch (IllegalArgumentException ex) { } try { new AndFileFilter(null, falseFilter); fail(); } catch (IllegalArgumentException ex) { } AndFileFilter f = new AndFileFilter((List) null); assertTrue(f.getFileFilters().isEmpty()); assertNotNull(f.toString()); // TODO better tests } public void testOr() throws Exception { IOFileFilter trueFilter = TrueFileFilter.INSTANCE; IOFileFilter falseFilter = FalseFileFilter.INSTANCE; File testFile = new File( "foo.test" ); assertFiltering(new OrFileFilter(trueFilter, trueFilter), testFile, true); assertFiltering(new OrFileFilter(trueFilter, falseFilter), testFile, true); assertFiltering(new OrFileFilter(falseFilter, trueFilter), testFile, true); assertFiltering(new OrFileFilter(falseFilter, falseFilter), testFile, false); assertFiltering(new OrFileFilter(), testFile, false); List filters = new ArrayList(); filters.add( trueFilter ); filters.add( falseFilter ); OrFileFilter orFilter = new OrFileFilter( filters ); assertFiltering(orFilter, testFile, true); assertEquals( orFilter.getFileFilters(), filters ); orFilter.removeFileFilter( trueFilter ); assertFiltering(orFilter, testFile, false); orFilter.setFileFilters( filters ); assertFiltering(orFilter, testFile, true); assertTrue( orFilter.accept( testFile.getParentFile(), testFile.getName() ) ); orFilter.removeFileFilter( trueFilter ); assertTrue( !orFilter.accept( testFile.getParentFile(), testFile.getName() ) ); try { new OrFileFilter(falseFilter, null); fail(); } catch (IllegalArgumentException ex) { } OrFileFilter f = new OrFileFilter((List) null); assertTrue(f.getFileFilters().isEmpty()); } public void testFileFilterUtils_and() throws Exception { IOFileFilter trueFilter = TrueFileFilter.INSTANCE; IOFileFilter falseFilter = FalseFileFilter.INSTANCE; assertFiltering(FileFilterUtils.and(trueFilter, trueFilter, trueFilter), new File("foo.test"), true); assertFiltering(FileFilterUtils.and(trueFilter, falseFilter, trueFilter), new File("foo.test"), false); assertFiltering(FileFilterUtils.and(falseFilter, trueFilter), new File("foo.test"), false); assertFiltering(FileFilterUtils.and(falseFilter, falseFilter), new File("foo.test"), false); } public void testFileFilterUtils_or() throws Exception { IOFileFilter trueFilter = TrueFileFilter.INSTANCE; IOFileFilter falseFilter = FalseFileFilter.INSTANCE; File testFile = new File( "foo.test" ); assertFiltering(FileFilterUtils.or(trueFilter, trueFilter), testFile, true); assertFiltering(FileFilterUtils.or(trueFilter, trueFilter, falseFilter), testFile, true); assertFiltering(FileFilterUtils.or(falseFilter, trueFilter), testFile, true); assertFiltering(FileFilterUtils.or(falseFilter, falseFilter, falseFilter), testFile, false); } @SuppressWarnings("deprecation") public void testDeprecatedWildcard() throws Exception { IOFileFilter filter = new WildcardFilter("*.txt"); List patternList = Arrays.asList( new String[] { "*.txt", "*.xml", "*.gif" } ); IOFileFilter listFilter = new WildcardFilter( patternList ); File txtFile = new File( "test.txt" ); File bmpFile = new File( "test.bmp" ); File dir = new File( "src/java" ); assertFiltering(filter, new File("log.txt"), true); // assertFiltering(filter, new File("log.txt.bak"), false); filter = new WildcardFilter("log?.txt"); assertFiltering(filter, new File("log1.txt"), true); assertFiltering(filter, new File("log12.txt"), false); filter = new WildcardFilter("open??.????04"); assertFiltering(filter, new File("openAB.102504"), true); assertFiltering(filter, new File("openA.102504"), false); assertFiltering(filter, new File("openXY.123103"), false); // assertFiltering(filter, new File("openAB.102504.old"), false); filter = new WildcardFilter(new String[] {"*.java", "*.class"}); assertFiltering(filter, new File("Test.java"), true); assertFiltering(filter, new File("Test.class"), true); assertFiltering(filter, new File("Test.jsp"), false); assertFiltering(listFilter, new File("Test.txt"), true); assertFiltering(listFilter, new File("Test.xml"), true); assertFiltering(listFilter, new File("Test.gif"), true); assertFiltering(listFilter, new File("Test.bmp"), false); assertTrue( listFilter.accept( txtFile ) ); assertTrue( !listFilter.accept( bmpFile ) ); assertTrue( !listFilter.accept( dir ) ); assertTrue( listFilter.accept( txtFile.getParentFile(), txtFile.getName() ) ); assertTrue( !listFilter.accept( bmpFile.getParentFile(), bmpFile.getName() ) ); assertTrue( !listFilter.accept( dir.getParentFile(), dir.getName() ) ); try { new WildcardFilter((String) null); fail(); } catch (IllegalArgumentException ex) { // expected } try { new WildcardFilter((String[]) null); fail(); } catch (IllegalArgumentException ex) { // expected } try { new WildcardFilter((List) null); fail(); } catch (IllegalArgumentException ex) { // expected } } public void testWildcard() throws Exception { IOFileFilter filter = new WildcardFileFilter("*.txt"); assertFiltering(filter, new File("log.txt"), true); assertFiltering(filter, new File("log.TXT"), false); filter = new WildcardFileFilter("*.txt", IOCase.SENSITIVE); assertFiltering(filter, new File("log.txt"), true); assertFiltering(filter, new File("log.TXT"), false); filter = new WildcardFileFilter("*.txt", IOCase.INSENSITIVE); assertFiltering(filter, new File("log.txt"), true); assertFiltering(filter, new File("log.TXT"), true); filter = new WildcardFileFilter("*.txt", IOCase.SYSTEM); assertFiltering(filter, new File("log.txt"), true); assertFiltering(filter, new File("log.TXT"), WINDOWS); filter = new WildcardFileFilter("*.txt", (IOCase) null); assertFiltering(filter, new File("log.txt"), true); assertFiltering(filter, new File("log.TXT"), false); filter = new WildcardFileFilter(new String[] {"*.java", "*.class"}); assertFiltering(filter, new File("Test.java"), true); assertFiltering(filter, new File("Test.class"), true); assertFiltering(filter, new File("Test.jsp"), false); filter = new WildcardFileFilter(new String[] {"*.java", "*.class"}, IOCase.SENSITIVE); assertFiltering(filter, new File("Test.java"), true); assertFiltering(filter, new File("Test.JAVA"), false); filter = new WildcardFileFilter(new String[] {"*.java", "*.class"}, IOCase.INSENSITIVE); assertFiltering(filter, new File("Test.java"), true); assertFiltering(filter, new File("Test.JAVA"), true); filter = new WildcardFileFilter(new String[] {"*.java", "*.class"}, IOCase.SYSTEM); assertFiltering(filter, new File("Test.java"), true); assertFiltering(filter, new File("Test.JAVA"), WINDOWS); filter = new WildcardFileFilter(new String[] {"*.java", "*.class"}, (IOCase) null); assertFiltering(filter, new File("Test.java"), true); assertFiltering(filter, new File("Test.JAVA"), false); List patternList = Arrays.asList( new String[] { "*.txt", "*.xml", "*.gif" } ); IOFileFilter listFilter = new WildcardFileFilter( patternList ); assertFiltering(listFilter, new File("Test.txt"), true); assertFiltering(listFilter, new File("Test.xml"), true); assertFiltering(listFilter, new File("Test.gif"), true); assertFiltering(listFilter, new File("Test.bmp"), false); File txtFile = new File( "test.txt" ); File bmpFile = new File( "test.bmp" ); File dir = new File( "src/java" ); assertTrue( listFilter.accept( txtFile ) ); assertTrue( !listFilter.accept( bmpFile ) ); assertTrue( !listFilter.accept( dir ) ); assertTrue( listFilter.accept( txtFile.getParentFile(), txtFile.getName() ) ); assertTrue( !listFilter.accept( bmpFile.getParentFile(), bmpFile.getName() ) ); assertTrue( !listFilter.accept( dir.getParentFile(), dir.getName() ) ); try { new WildcardFileFilter((String) null); fail(); } catch (IllegalArgumentException ex) {} try { new WildcardFileFilter((String[]) null); fail(); } catch (IllegalArgumentException ex) {} try { new WildcardFileFilter((List) null); fail(); } catch (IllegalArgumentException ex) {} } public void testDelegateFileFilter() throws Exception { OrFileFilter orFilter = new OrFileFilter(); File testFile = new File( "test.txt" ); IOFileFilter filter = new DelegateFileFilter((FileFilter) orFilter); assertFiltering( filter, testFile, false ); assertNotNull(filter.toString()); // TODO better test filter = new DelegateFileFilter((FilenameFilter) orFilter); assertFiltering( filter, testFile, false ); assertNotNull(filter.toString()); // TODO better test try { new DelegateFileFilter((FileFilter) null); fail(); } catch( IllegalArgumentException iae ) { } try { new DelegateFileFilter((FilenameFilter) null); fail(); } catch( IllegalArgumentException iae ) { } } public void testMakeCVSAware() throws Exception { IOFileFilter filter1 = FileFilterUtils.makeCVSAware(null); IOFileFilter filter2 = FileFilterUtils.makeCVSAware(FileFilterUtils .nameFileFilter("test-file1.txt")); File file = new File(getTestDirectory(), "CVS"); file.mkdirs(); assertFiltering(filter1, file, false); assertFiltering(filter2, file, false); FileUtils.deleteDirectory(file); file = new File(getTestDirectory(), "test-file1.txt"); createFile(file, 0); assertFiltering(filter1, file, true); assertFiltering(filter2, file, true); file = new File(getTestDirectory(), "test-file2.log"); createFile(file, 0); assertFiltering(filter1, file, true); assertFiltering(filter2, file, false); file = new File(getTestDirectory(), "CVS"); createFile(file, 0); assertFiltering(filter1, file, true); assertFiltering(filter2, file, false); } public void testMakeSVNAware() throws Exception { IOFileFilter filter1 = FileFilterUtils.makeSVNAware(null); IOFileFilter filter2 = FileFilterUtils.makeSVNAware(FileFilterUtils .nameFileFilter("test-file1.txt")); File file = new File(getTestDirectory(), SVN_DIR_NAME); file.mkdirs(); assertFiltering(filter1, file, false); assertFiltering(filter2, file, false); FileUtils.deleteDirectory(file); file = new File(getTestDirectory(), "test-file1.txt"); createFile(file, 0); assertFiltering(filter1, file, true); assertFiltering(filter2, file, true); file = new File(getTestDirectory(), "test-file2.log"); createFile(file, 0); assertFiltering(filter1, file, true); assertFiltering(filter2, file, false); file = new File(getTestDirectory(), SVN_DIR_NAME); createFile(file, 0); assertFiltering(filter1, file, true); assertFiltering(filter2, file, false); } public void testAgeFilter() throws Exception { File oldFile = new File(getTestDirectory(), "old.txt"); File reference = new File(getTestDirectory(), "reference.txt"); File newFile = new File(getTestDirectory(), "new.txt"); createFile(oldFile, 0); do { try { Thread.sleep(1000); } catch(InterruptedException ie) { // ignore } createFile(reference, 0); } while( oldFile.lastModified() == reference.lastModified() ); Date date = new Date(); long now = date.getTime(); do { try { Thread.sleep(1000); } catch(InterruptedException ie) { // ignore } createFile(newFile, 0); } while( reference.lastModified() == newFile.lastModified() ); IOFileFilter filter1 = FileFilterUtils.ageFileFilter(now); IOFileFilter filter2 = FileFilterUtils.ageFileFilter(now, true); IOFileFilter filter3 = FileFilterUtils.ageFileFilter(now, false); IOFileFilter filter4 = FileFilterUtils.ageFileFilter(date); IOFileFilter filter5 = FileFilterUtils.ageFileFilter(date, true); IOFileFilter filter6 = FileFilterUtils.ageFileFilter(date, false); IOFileFilter filter7 = FileFilterUtils.ageFileFilter(reference); IOFileFilter filter8 = FileFilterUtils.ageFileFilter(reference, true); IOFileFilter filter9 = FileFilterUtils.ageFileFilter(reference, false); assertFiltering(filter1, oldFile, true); assertFiltering(filter2, oldFile, true); assertFiltering(filter3, oldFile, false); assertFiltering(filter4, oldFile, true); assertFiltering(filter5, oldFile, true); assertFiltering(filter6, oldFile, false); assertFiltering(filter7, oldFile, true); assertFiltering(filter8, oldFile, true); assertFiltering(filter9, oldFile, false); assertFiltering(filter1, newFile, false); assertFiltering(filter2, newFile, false); assertFiltering(filter3, newFile, true); assertFiltering(filter4, newFile, false); assertFiltering(filter5, newFile, false); assertFiltering(filter6, newFile, true); assertFiltering(filter7, newFile, false); assertFiltering(filter8, newFile, false); assertFiltering(filter9, newFile, true); } public void testSizeFilter() throws Exception { File smallFile = new File(getTestDirectory(), "small.txt"); createFile(smallFile, 32); File largeFile = new File(getTestDirectory(), "large.txt"); createFile(largeFile, 128); IOFileFilter filter1 = FileFilterUtils.sizeFileFilter(64); IOFileFilter filter2 = FileFilterUtils.sizeFileFilter(64, true); IOFileFilter filter3 = FileFilterUtils.sizeFileFilter(64, false); assertFiltering(filter1, smallFile, false); assertFiltering(filter2, smallFile, false); assertFiltering(filter3, smallFile, true); assertFiltering(filter1, largeFile, true); assertFiltering(filter2, largeFile, true); assertFiltering(filter3, largeFile, false); // size range tests IOFileFilter filter4 = FileFilterUtils.sizeRangeFileFilter(33, 127); IOFileFilter filter5 = FileFilterUtils.sizeRangeFileFilter(32, 127); IOFileFilter filter6 = FileFilterUtils.sizeRangeFileFilter(33, 128); IOFileFilter filter7 = FileFilterUtils.sizeRangeFileFilter(31, 129); IOFileFilter filter8 = FileFilterUtils.sizeRangeFileFilter(128, 128); assertFiltering(filter4, smallFile, false); assertFiltering(filter4, largeFile, false); assertFiltering(filter5, smallFile, true); assertFiltering(filter5, largeFile, false); assertFiltering(filter6, smallFile, false); assertFiltering(filter6, largeFile, true); assertFiltering(filter7, smallFile, true); assertFiltering(filter7, largeFile, true); assertFiltering(filter8, largeFile, true); try { FileFilterUtils.sizeFileFilter(-1); fail(); } catch (IllegalArgumentException ex) { // expected } } public void testHidden() throws Exception { File hiddenDir = new File(SVN_DIR_NAME); if (hiddenDir.exists()) { assertFiltering(HiddenFileFilter.HIDDEN, hiddenDir, hiddenDir.isHidden()); assertFiltering(HiddenFileFilter.VISIBLE, hiddenDir, !hiddenDir.isHidden()); } assertFiltering(HiddenFileFilter.HIDDEN, getTestDirectory(), false); assertFiltering(HiddenFileFilter.VISIBLE, getTestDirectory(), true); } public void testCanRead() throws Exception { File readOnlyFile = new File(getTestDirectory(), "read-only-file1.txt"); createFile(readOnlyFile, 32); readOnlyFile.setReadOnly(); assertFiltering(CanReadFileFilter.CAN_READ, readOnlyFile, true); assertFiltering(CanReadFileFilter.CANNOT_READ, readOnlyFile, false); assertFiltering(CanReadFileFilter.READ_ONLY, readOnlyFile, true); readOnlyFile.delete(); } public void testCanWrite() throws Exception { File readOnlyFile = new File(getTestDirectory(), "read-only-file2.txt"); createFile(readOnlyFile, 32); readOnlyFile.setReadOnly(); assertFiltering(CanWriteFileFilter.CAN_WRITE, getTestDirectory(), true); assertFiltering(CanWriteFileFilter.CANNOT_WRITE, getTestDirectory(), false); assertFiltering(CanWriteFileFilter.CAN_WRITE, readOnlyFile, false); assertFiltering(CanWriteFileFilter.CANNOT_WRITE, readOnlyFile, true); readOnlyFile.delete(); } public void testEmpty() throws Exception { // Empty Dir File emptyDir = new File(getTestDirectory(), "empty-dir"); emptyDir.mkdirs(); assertFiltering(EmptyFileFilter.EMPTY, emptyDir, true); assertFiltering(EmptyFileFilter.NOT_EMPTY, emptyDir, false); // Empty File File emptyFile = new File(emptyDir, "empty-file.txt"); createFile(emptyFile, 0); assertFiltering(EmptyFileFilter.EMPTY, emptyFile, true); assertFiltering(EmptyFileFilter.NOT_EMPTY, emptyFile, false); // Not Empty Dir assertFiltering(EmptyFileFilter.EMPTY, emptyDir, false); assertFiltering(EmptyFileFilter.NOT_EMPTY, emptyDir, true); // Not Empty File File notEmptyFile = new File(emptyDir, "not-empty-file.txt"); createFile(notEmptyFile, 32); assertFiltering(EmptyFileFilter.EMPTY, notEmptyFile, false); assertFiltering(EmptyFileFilter.NOT_EMPTY, notEmptyFile, true); FileUtils.forceDelete(emptyDir); } //----------------------------------------------------------------------- public void testMakeDirectoryOnly() throws Exception { assertSame(DirectoryFileFilter.DIRECTORY, FileFilterUtils.makeDirectoryOnly(null)); IOFileFilter filter = FileFilterUtils.makeDirectoryOnly( FileFilterUtils.nameFileFilter("B")); File fileA = new File(getTestDirectory(), "A"); File fileB = new File(getTestDirectory(), "B"); fileA.mkdirs(); fileB.mkdirs(); assertFiltering(filter, fileA, false); assertFiltering(filter, fileB, true); FileUtils.deleteDirectory(fileA); FileUtils.deleteDirectory(fileB); createFile(fileA, 32); createFile(fileB, 32); assertFiltering(filter, fileA, false); assertFiltering(filter, fileB, false); fileA.delete(); fileB.delete(); } //----------------------------------------------------------------------- public void testMakeFileOnly() throws Exception { assertSame(FileFileFilter.FILE, FileFilterUtils.makeFileOnly(null)); IOFileFilter filter = FileFilterUtils.makeFileOnly( FileFilterUtils.nameFileFilter("B")); File fileA = new File(getTestDirectory(), "A"); File fileB = new File(getTestDirectory(), "B"); fileA.mkdirs(); fileB.mkdirs(); assertFiltering(filter, fileA, false); assertFiltering(filter, fileB, false); FileUtils.deleteDirectory(fileA); FileUtils.deleteDirectory(fileB); createFile(fileA, 32); createFile(fileB, 32); assertFiltering(filter, fileA, false); assertFiltering(filter, fileB, true); fileA.delete(); fileB.delete(); } //----------------------------------------------------------------------- public void testMagicNumberFileFilterBytes() throws Exception { byte[] classFileMagicNumber = new byte[] {(byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE}; String xmlFileContent = "\n" + "text"; File classFileA = new File(getTestDirectory(), "A.class"); File xmlFileB = new File(getTestDirectory(), "B.xml"); File emptyFile = new File(getTestDirectory(), "C.xml"); File dir = new File(getTestDirectory(), "D"); dir.mkdirs(); OutputStream classFileAStream = FileUtils.openOutputStream(classFileA); IOUtils.write(classFileMagicNumber, classFileAStream); generateTestData(classFileAStream, 32); classFileAStream.close(); FileUtils.write(xmlFileB, xmlFileContent); FileUtils.touch(emptyFile); IOFileFilter filter = new MagicNumberFileFilter(classFileMagicNumber); assertFiltering(filter, classFileA, true); assertFiltering(filter, xmlFileB, false); assertFiltering(filter, emptyFile, false); assertFiltering(filter, dir, false); filter = FileFilterUtils.magicNumberFileFilter(classFileMagicNumber); assertFiltering(filter, classFileA, true); assertFiltering(filter, xmlFileB, false); assertFiltering(filter, emptyFile, false); assertFiltering(filter, dir, false); } public void testMagicNumberFileFilterBytesOffset() throws Exception { byte[] tarMagicNumber = new byte[] {0x75, 0x73, 0x74, 0x61, 0x72}; long tarMagicNumberOffset = 257; File tarFileA = new File(getTestDirectory(), "A.tar"); File randomFileB = new File(getTestDirectory(), "B.txt"); File dir = new File(getTestDirectory(), "D"); dir.mkdirs(); OutputStream tarFileAStream = FileUtils.openOutputStream(tarFileA); generateTestData(tarFileAStream, tarMagicNumberOffset); IOUtils.write(tarMagicNumber, tarFileAStream); tarFileAStream.close(); createFile(randomFileB, 2 * tarMagicNumberOffset); IOFileFilter filter = new MagicNumberFileFilter(tarMagicNumber, tarMagicNumberOffset); assertFiltering(filter, tarFileA, true); assertFiltering(filter, randomFileB, false); assertFiltering(filter, dir, false); filter = FileFilterUtils.magicNumberFileFilter(tarMagicNumber, tarMagicNumberOffset); assertFiltering(filter, tarFileA, true); assertFiltering(filter, randomFileB, false); assertFiltering(filter, dir, false); } public void testMagicNumberFileFilterString() throws Exception { byte[] classFileMagicNumber = new byte[] {(byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE}; String xmlFileContent = "\n" + "text"; String xmlMagicNumber = " fileList = Arrays.asList(fileA, fileB); IOFileFilter filter = FileFilterUtils.nameFileFilter("A"); File[] filtered = FileFilterUtils.filter(filter, fileList); assertEquals(1, filtered.length); assertEquals(fileA, filtered[0]); } /** * Test method for {@link FileFilterUtils#filter(IOFileFilter, File...)} * that tests {@code null} parameters and {@code null} elements * in the provided list. */ public void testFilterArrayNullParameters() throws Exception { File fileA = newFile("A"); File fileB = newFile("B"); try { FileFilterUtils.filter(null, fileA, fileB); fail(); } catch (IllegalArgumentException iae) { // Test passes, exception thrown for null filter } IOFileFilter filter = FileFilterUtils.trueFileFilter(); try { FileFilterUtils.filter(filter, fileA, null); fail(); } catch (IllegalArgumentException iae) { // Test passes, exception thrown for list containing null } File[] filtered = FileFilterUtils.filter(filter, (File[])null); assertEquals(0, filtered.length); } /** * Test method for {@link FileFilterUtils#filterList(IOFileFilter, java.lang.Iterable)} * that tests that the method properly filters files from the list. */ public void testFilterList() throws Exception { File fileA = newFile("A"); File fileB = newFile("B"); List fileList = Arrays.asList(fileA, fileB); IOFileFilter filter = FileFilterUtils.nameFileFilter("A"); List filteredList = FileFilterUtils.filterList(filter, fileList); assertTrue(filteredList.contains(fileA)); assertFalse(filteredList.contains(fileB)); } /** * Test method for {@link FileFilterUtils#filterList(IOFileFilter, File...)} * that tests that the method properly filters files from the list. */ public void testFilterList_fromArray() throws Exception { File fileA = newFile("A"); File fileB = newFile("B"); IOFileFilter filter = FileFilterUtils.nameFileFilter("A"); List filteredList = FileFilterUtils.filterList(filter, fileA, fileB); assertTrue(filteredList.contains(fileA)); assertFalse(filteredList.contains(fileB)); } /** * Test method for {@link FileFilterUtils#filterList(IOFileFilter, java.lang.Iterable)} * that tests {@code null} parameters and {@code null} elements * in the provided list. */ public void testFilterListNullParameters() { try { FileFilterUtils.filterList(null, Collections.emptyList()); fail(); } catch (IllegalArgumentException iae) { // Test passes, exception thrown for null filter } IOFileFilter filter = FileFilterUtils.trueFileFilter(); try { FileFilterUtils.filterList(filter, Arrays.asList((File) null)); fail(); } catch (IllegalArgumentException iae) { // Test passes, exception thrown for list containing null } List filteredList = FileFilterUtils.filterList(filter, (List)null); assertEquals(0, filteredList.size()); } /** * Test method for {@link FileFilterUtils#filterSet(IOFileFilter, java.lang.Iterable)} * that tests that the method properly filters files from the set. */ public void testFilterSet() throws Exception { File fileA = newFile("A"); File fileB = newFile("B"); Set fileList = new HashSet(Arrays.asList(fileA, fileB)); IOFileFilter filter = FileFilterUtils.nameFileFilter("A"); Set filteredSet = FileFilterUtils.filterSet(filter, fileList); assertTrue(filteredSet.contains(fileA)); assertFalse(filteredSet.contains(fileB)); } /** * Test method for {@link FileFilterUtils#filterSet(IOFileFilter, File...)} * that tests that the method properly filters files from the set. */ public void testFilterSet_fromArray() throws Exception { File fileA = newFile("A"); File fileB = newFile("B"); IOFileFilter filter = FileFilterUtils.nameFileFilter("A"); Set filteredSet = FileFilterUtils.filterSet(filter, fileA, fileB); assertTrue(filteredSet.contains(fileA)); assertFalse(filteredSet.contains(fileB)); } /** * Test method for {@link FileFilterUtils#filterSet(IOFileFilter, java.lang.Iterable)} * that tests {@code null} parameters and {@code null} elements * in the provided set. */ public void testFilterSetNullParameters() { try { FileFilterUtils.filterSet(null, Collections.emptySet()); fail(); } catch (IllegalArgumentException iae) { // Test passes, exception thrown for null filter } IOFileFilter filter = FileFilterUtils.trueFileFilter(); try { FileFilterUtils.filterSet(filter, new HashSet(Arrays.asList((File) null))); fail(); } catch (IllegalArgumentException iae) { // Test passes, exception thrown for set containing null } Set filteredSet = FileFilterUtils.filterSet(filter, (Set)null); assertEquals(0, filteredSet.size()); } public void testEnsureTestCoverage() { assertNotNull(new FileFilterUtils()); // dummy for test coverage } public void testNullFilters() { try { FileFilterUtils.toList((IOFileFilter)null); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { // expected } try { FileFilterUtils.toList(new IOFileFilter[]{null}); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { // expected } } public void testDelegation() { // TODO improve these tests assertNotNull(FileFilterUtils.asFileFilter((FileFilter)FalseFileFilter.INSTANCE)); assertNotNull(FileFilterUtils.asFileFilter((FilenameFilter)FalseFileFilter.INSTANCE).toString()); } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/filefilter/OrFileFilterTestCase.java0000644000175000017500000002403612125050425033070 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.filefilter; import java.util.ArrayList; import java.util.List; public class OrFileFilterTestCase extends ConditionalFileFilterAbstractTestCase { private static final String DEFAULT_WORKING_PATH = "./OrFileFilterTestCase/"; private static final String WORKING_PATH_NAME_PROPERTY_KEY = OrFileFilterTestCase.class.getName() + ".workingDirectory"; private List> testFilters; private List testTrueResults; private List testFalseResults; private List testFileResults; private List testFilenameResults; public OrFileFilterTestCase(final String name) { super(name); } @Override public void setUp() throws Exception { super.setUp(); this.setUpTestFilters(); } @Override protected IOFileFilter buildFilterUsingAdd(final List filters) { OrFileFilter filter = new OrFileFilter(); for(int i = 0; i < filters.size(); i++) { filter.addFileFilter(filters.get(i)); } return filter; } @Override protected IOFileFilter buildFilterUsingConstructor(final List filters) { return new OrFileFilter(filters); } @Override protected ConditionalFileFilter getConditionalFileFilter() { return new OrFileFilter(); } @Override protected String getDefaultWorkingPath() { return DEFAULT_WORKING_PATH; } @Override protected List getFalseResults() { return this.testFalseResults; } @Override protected List getFileResults() { return this.testFileResults; } @Override protected List getFilenameResults() { return this.testFilenameResults; } @Override protected List> getTestFilters() { return this.testFilters; } @Override protected List getTrueResults() { return this.testTrueResults; } @Override protected String getWorkingPathNamePropertyKey() { return WORKING_PATH_NAME_PROPERTY_KEY; } private void setUpTestFilters() { // filters //tests this.testFilters = new ArrayList>(); this.testTrueResults = new ArrayList(); this.testFalseResults = new ArrayList(); this.testFileResults = new ArrayList(); this.testFilenameResults = new ArrayList(); // test 0 - add empty elements { testFilters.add(0, null); testTrueResults.add(0, null); testFalseResults.add(0, null); testFileResults.add(0, null); testFilenameResults.add(0, null); } // test 1 - Test conditional or with all filters returning true { // test 1 filters List filters = new ArrayList(); filters.add(trueFilters[1]); filters.add(trueFilters[2]); filters.add(trueFilters[3]); // test 1 true results boolean[] trueResults = new boolean[] {true, false, false}; // test 1 false results boolean[] falseResults = new boolean[] {false, false, false}; testFilters.add(1, filters); testTrueResults.add(1, trueResults); testFalseResults.add(1, falseResults); testFileResults.add(1, Boolean.TRUE); testFilenameResults.add(1, Boolean.TRUE); } // test 2 - Test conditional or with first filter returning false { // test 2 filters List filters = new ArrayList(); filters.add(falseFilters[1]); filters.add(trueFilters[1]); filters.add(trueFilters[2]); filters.add(trueFilters[3]); filters.add(falseFilters[2]); filters.add(falseFilters[3]); // test 2 true results boolean[] trueResults = new boolean[] {true, false, false}; // test 2 false results boolean[] falseResults = new boolean[] {true, false, false}; testFilters.add(2, filters); testTrueResults.add(2, trueResults); testFalseResults.add(2, falseResults); testFileResults.add(2, Boolean.TRUE); testFilenameResults.add(2, Boolean.TRUE); } // test 3 - Test conditional or with second filter returning false { // test 3 filters List filters = new ArrayList(); filters.add(trueFilters[1]); filters.add(falseFilters[1]); filters.add(trueFilters[2]); filters.add(trueFilters[3]); filters.add(falseFilters[2]); filters.add(falseFilters[3]); // test 3 true results boolean[] trueResults = new boolean[] {true, false, false}; // test 3 false results boolean[] falseResults = new boolean[] {false, false, false}; testFilters.add(3, filters); testTrueResults.add(3, trueResults); testFalseResults.add(3, falseResults); testFileResults.add(3, Boolean.TRUE); testFilenameResults.add(3, Boolean.TRUE); } // test 4 - Test conditional or with third filter returning false { // test 4 filters List filters = new ArrayList(); filters.add(trueFilters[1]); filters.add(trueFilters[2]); filters.add(falseFilters[1]); filters.add(trueFilters[3]); filters.add(falseFilters[2]); filters.add(falseFilters[3]); // test 4 true results boolean[] trueResults = new boolean[] {true, false, false}; // test 4 false results boolean[] falseResults = new boolean[] {false, false, false}; testFilters.add(4, filters); testTrueResults.add(4, trueResults); testFalseResults.add(4, falseResults); testFileResults.add(4, Boolean.TRUE); testFilenameResults.add(4, Boolean.TRUE); } // test 5 - Test conditional or with first and third filters returning false { // test 5 filters List filters = new ArrayList(); filters.add(falseFilters[1]); filters.add(trueFilters[1]); filters.add(falseFilters[2]); filters.add(falseFilters[3]); filters.add(trueFilters[2]); filters.add(trueFilters[3]); // test 5 true results boolean[] trueResults = new boolean[] {true, false, false}; // test 5 false results boolean[] falseResults = new boolean[] {true, false, false}; testFilters.add(5, filters); testTrueResults.add(5, trueResults); testFalseResults.add(5, falseResults); testFileResults.add(5, Boolean.TRUE); testFilenameResults.add(5, Boolean.TRUE); } // test 6 - Test conditional or with second and third filters returning false { List filters = new ArrayList(); filters.add(trueFilters[1]); filters.add(falseFilters[1]); filters.add(falseFilters[2]); filters.add(trueFilters[2]); filters.add(trueFilters[3]); filters.add(falseFilters[3]); // test 6 true results boolean[] trueResults = new boolean[] {true, false, false}; // test 6 false results boolean[] falseResults = new boolean[] {false, false, false}; testFilters.add(6, filters); testTrueResults.add(6, trueResults); testFalseResults.add(6, falseResults); testFileResults.add(6, Boolean.TRUE); testFilenameResults.add(6, Boolean.TRUE); } // test 7 - Test conditional or with first and second filters returning false { List filters = new ArrayList(); filters.add(falseFilters[1]); filters.add(falseFilters[2]); filters.add(trueFilters[1]); filters.add(falseFilters[3]); filters.add(trueFilters[2]); filters.add(trueFilters[3]); // test 7 true results boolean[] trueResults = new boolean[] {true, false, false}; // test 7 false results boolean[] falseResults = new boolean[] {true, true, false}; testFilters.add(7, filters); testTrueResults.add(7, trueResults); testFalseResults.add(7, falseResults); testFileResults.add(7, Boolean.TRUE); testFilenameResults.add(7, Boolean.TRUE); } // test 8 - Test conditional or with fourth filter returning false { List filters = new ArrayList(); filters.add(trueFilters[1]); filters.add(trueFilters[2]); filters.add(trueFilters[3]); filters.add(falseFilters[1]); // test 8 true results boolean[] trueResults = new boolean[] {true, false, false}; // test 8 false results boolean[] falseResults = new boolean[] {false, false, false}; testFilters.add(8, filters); testTrueResults.add(8, trueResults); testFalseResults.add(8, falseResults); testFileResults.add(8, Boolean.TRUE); testFilenameResults.add(8, Boolean.TRUE); } // test 9 - Test conditional or with all filters returning false { List filters = new ArrayList(); filters.add(falseFilters[1]); filters.add(falseFilters[2]); filters.add(falseFilters[3]); // test 9 true results boolean[] trueResults = new boolean[] {false, false, false}; // test 9 false results boolean[] falseResults = new boolean[] {true, true, true}; testFilters.add(9, filters); testTrueResults.add(9, trueResults); testFalseResults.add(9, falseResults); testFileResults.add(9, Boolean.FALSE); testFilenameResults.add(9, Boolean.FALSE); } } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/filefilter/RegexFileFilterTestCase.javalibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/filefilter/RegexFileFilterTestCase.j0000644000175000017500000001053012125050425033064 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.filefilter; import java.io.File; import java.util.regex.Pattern; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOCase; import org.apache.commons.io.testtools.FileBasedTestCase; /** * Used to test RegexFileFilterUtils. */ public class RegexFileFilterTestCase extends FileBasedTestCase { public RegexFileFilterTestCase(String name) { super(name); } @Override public void setUp() { getTestDirectory().mkdirs(); } @Override public void tearDown() throws Exception { FileUtils.deleteDirectory(getTestDirectory()); } public void assertFiltering(IOFileFilter filter, File file, boolean expected) throws Exception { // Note. This only tests the (File, String) version if the parent of // the File passed in is not null assertEquals( "Filter(File) " + filter.getClass().getName() + " not " + expected + " for " + file, expected, filter.accept(file)); if (file != null && file.getParentFile() != null) { assertEquals( "Filter(File, String) " + filter.getClass().getName() + " not " + expected + " for " + file, expected, filter.accept(file.getParentFile(), file.getName())); } else if (file == null) { assertEquals( "Filter(File, String) " + filter.getClass().getName() + " not " + expected + " for null", expected, filter.accept(file)); } } public void testRegex() throws Exception { IOFileFilter filter = new RegexFileFilter("^.*[tT]est(-\\d+)?\\.java$"); assertFiltering(filter, new File("Test.java"), true); assertFiltering(filter, new File("test-10.java"), true); assertFiltering(filter, new File("test-.java"), false); filter = new RegexFileFilter("^[Tt]est.java$"); assertFiltering(filter, new File("Test.java"), true); assertFiltering(filter, new File("test.java"), true); assertFiltering(filter, new File("tEST.java"), false); filter = new RegexFileFilter(Pattern.compile("^test.java$", Pattern.CASE_INSENSITIVE)); assertFiltering(filter, new File("Test.java"), true); assertFiltering(filter, new File("test.java"), true); assertFiltering(filter, new File("tEST.java"), true); filter = new RegexFileFilter("^test.java$", Pattern.CASE_INSENSITIVE); assertFiltering(filter, new File("Test.java"), true); assertFiltering(filter, new File("test.java"), true); assertFiltering(filter, new File("tEST.java"), true); filter = new RegexFileFilter("^test.java$", IOCase.INSENSITIVE); assertFiltering(filter, new File("Test.java"), true); assertFiltering(filter, new File("test.java"), true); assertFiltering(filter, new File("tEST.java"), true); try { new RegexFileFilter((String)null); fail(); } catch (IllegalArgumentException ex) { // expected } try { new RegexFileFilter((String)null, Pattern.CASE_INSENSITIVE); fail(); } catch (IllegalArgumentException ex) { // expected } try { new RegexFileFilter((String)null, IOCase.INSENSITIVE); fail(); } catch (IllegalArgumentException ex) { // expected } try { new RegexFileFilter((java.util.regex.Pattern)null); fail(); } catch (IllegalArgumentException ex) { // expected } } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/filefilter/AndFileFilterTestCase.javalibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/filefilter/AndFileFilterTestCase.jav0000644000175000017500000002407212125050425033051 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.filefilter; import java.util.ArrayList; import java.util.List; public class AndFileFilterTestCase extends ConditionalFileFilterAbstractTestCase { private static final String DEFAULT_WORKING_PATH = "./AndFileFilterTestCase/"; private static final String WORKING_PATH_NAME_PROPERTY_KEY = AndFileFilterTestCase.class.getName() + ".workingDirectory"; private List> testFilters; private List testTrueResults; private List testFalseResults; private List testFileResults; private List testFilenameResults; public AndFileFilterTestCase(final String name) { super(name); } @Override public void setUp() throws Exception { super.setUp(); this.setUpTestFilters(); } @Override protected IOFileFilter buildFilterUsingAdd(final List filters) { AndFileFilter filter = new AndFileFilter(); for(int i = 0; i < filters.size(); i++) { filter.addFileFilter(filters.get(i)); } return filter; } @Override protected IOFileFilter buildFilterUsingConstructor(final List filters) { return new AndFileFilter(filters); } @Override protected ConditionalFileFilter getConditionalFileFilter() { return new AndFileFilter(); } @Override protected String getDefaultWorkingPath() { return DEFAULT_WORKING_PATH; } @Override protected List getFalseResults() { return this.testFalseResults; } @Override protected List getFileResults() { return this.testFileResults; } @Override protected List getFilenameResults() { return this.testFilenameResults; } @Override protected List> getTestFilters() { return this.testFilters; } @Override protected List getTrueResults() { return this.testTrueResults; } @Override protected String getWorkingPathNamePropertyKey() { return WORKING_PATH_NAME_PROPERTY_KEY; } private void setUpTestFilters() { // filters //tests this.testFilters = new ArrayList>(); this.testTrueResults = new ArrayList(); this.testFalseResults = new ArrayList(); this.testFileResults = new ArrayList(); this.testFilenameResults = new ArrayList(); // test 0 - add empty elements { testFilters.add(0, null); testTrueResults.add(0, null); testFalseResults.add(0, null); testFileResults.add(0, null); testFilenameResults.add(0, null); } // test 1 - Test conditional and with all filters returning true { // test 1 filters List filters = new ArrayList(); filters.add(trueFilters[1]); filters.add(trueFilters[2]); filters.add(trueFilters[3]); // test 1 true results boolean[] trueResults = new boolean[] {true, true, true}; // test 1 false results boolean[] falseResults = new boolean[] {false, false, false}; testFilters.add(1, filters); testTrueResults.add(1, trueResults); testFalseResults.add(1, falseResults); testFileResults.add(1, Boolean.TRUE); testFilenameResults.add(1, Boolean.TRUE); } // test 2 - Test conditional and with first filter returning false { // test 2 filters List filters = new ArrayList(); filters.add(falseFilters[1]); filters.add(trueFilters[1]); filters.add(trueFilters[2]); filters.add(trueFilters[3]); filters.add(falseFilters[2]); filters.add(falseFilters[3]); // test 2 true results boolean[] trueResults = new boolean[] {false, false, false}; // test 2 false results boolean[] falseResults = new boolean[] {true, false, false}; testFilters.add(2, filters); testTrueResults.add(2, trueResults); testFalseResults.add(2, falseResults); testFileResults.add(2, Boolean.FALSE); testFilenameResults.add(2, Boolean.FALSE); } // test 3 - Test conditional and with second filter returning false { // test 3 filters List filters = new ArrayList(); filters.add(trueFilters[1]); filters.add(falseFilters[1]); filters.add(trueFilters[2]); filters.add(trueFilters[3]); filters.add(falseFilters[2]); filters.add(falseFilters[3]); // test 3 true results boolean[] trueResults = new boolean[] {true, false, false}; // test 3 false results boolean[] falseResults = new boolean[] {true, false, false}; testFilters.add(3, filters); testTrueResults.add(3, trueResults); testFalseResults.add(3, falseResults); testFileResults.add(3, Boolean.FALSE); testFilenameResults.add(3, Boolean.FALSE); } // test 4 - Test conditional and with third filter returning false { // test 4 filters List filters = new ArrayList(); filters.add(trueFilters[1]); filters.add(trueFilters[2]); filters.add(falseFilters[1]); filters.add(trueFilters[3]); filters.add(falseFilters[2]); filters.add(falseFilters[3]); // test 4 true results boolean[] trueResults = new boolean[] {true, true, false}; // test 4 false results boolean[] falseResults = new boolean[] {true, false, false}; testFilters.add(4, filters); testTrueResults.add(4, trueResults); testFalseResults.add(4, falseResults); testFileResults.add(4, Boolean.FALSE); testFilenameResults.add(4, Boolean.FALSE); } // test 5 - Test conditional and with first and third filters returning false { // test 5 filters List filters = new ArrayList(); filters.add(falseFilters[1]); filters.add(trueFilters[1]); filters.add(falseFilters[2]); filters.add(falseFilters[3]); filters.add(trueFilters[2]); filters.add(trueFilters[3]); // test 5 true results boolean[] trueResults = new boolean[] {false, false, false}; // test 5 false results boolean[] falseResults = new boolean[] {true, false, false}; testFilters.add(5, filters); testTrueResults.add(5, trueResults); testFalseResults.add(5, falseResults); testFileResults.add(5, Boolean.FALSE); testFilenameResults.add(5, Boolean.FALSE); } // test 6 - Test conditional and with second and third filters returning false { List filters = new ArrayList(); filters.add(trueFilters[1]); filters.add(falseFilters[1]); filters.add(falseFilters[2]); filters.add(trueFilters[2]); filters.add(trueFilters[3]); filters.add(falseFilters[3]); // test 6 true results boolean[] trueResults = new boolean[] {true, false, false}; // test 6 false results boolean[] falseResults = new boolean[] {true, false, false}; testFilters.add(6, filters); testTrueResults.add(6, trueResults); testFalseResults.add(6, falseResults); testFileResults.add(6, Boolean.FALSE); testFilenameResults.add(6, Boolean.FALSE); } // test 7 - Test conditional and with first and second filters returning false { List filters = new ArrayList(); filters.add(falseFilters[1]); filters.add(falseFilters[2]); filters.add(trueFilters[3]); filters.add(falseFilters[3]); filters.add(trueFilters[2]); filters.add(trueFilters[3]); // test 7 true results boolean[] trueResults = new boolean[] {false, false, false}; // test 7 false results boolean[] falseResults = new boolean[] {true, false, false}; testFilters.add(7, filters); testTrueResults.add(7, trueResults); testFalseResults.add(7, falseResults); testFileResults.add(7, Boolean.FALSE); testFilenameResults.add(7, Boolean.FALSE); } // test 8 - Test conditional and with fourth filters returning false { List filters = new ArrayList(); filters.add(trueFilters[1]); filters.add(trueFilters[2]); filters.add(trueFilters[3]); filters.add(falseFilters[1]); // test 8 true results boolean[] trueResults = new boolean[] {true, true, true}; // test 8 false results boolean[] falseResults = new boolean[] {true, false, false}; testFilters.add(8, filters); testTrueResults.add(8, trueResults); testFalseResults.add(8, falseResults); testFileResults.add(8, Boolean.FALSE); testFilenameResults.add(8, Boolean.FALSE); } // test 9 - Test conditional and with all filters returning false { List filters = new ArrayList(); filters.add(falseFilters[1]); filters.add(falseFilters[2]); filters.add(falseFilters[3]); // test 9 true results boolean[] trueResults = new boolean[] {false, false, false}; // test 9 false results boolean[] falseResults = new boolean[] {true, false, false}; testFilters.add(9, filters); testTrueResults.add(9, trueResults); testFalseResults.add(9, falseResults); testFileResults.add(9, Boolean.FALSE); testFilenameResults.add(9, Boolean.FALSE); } } } ././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/filefilter/ConditionalFileFilterAbstractTestCase.javalibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/filefilter/ConditionalFileFilterAbst0000644000175000017500000001714112125050425033210 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.filefilter; import java.io.File; import java.util.ArrayList; import java.util.List; public abstract class ConditionalFileFilterAbstractTestCase extends IOFileFilterAbstractTestCase { private static final String TEST_FILE_NAME_PREFIX = "TestFile"; private static final String TEST_FILE_TYPE = ".tst"; protected TesterTrueFileFilter[] trueFilters; protected TesterFalseFileFilter[] falseFilters; private File file; private File workingPath; public ConditionalFileFilterAbstractTestCase(final String name) { super(name); } @Override public void setUp() throws Exception { this.workingPath = this.determineWorkingDirectoryPath(this.getWorkingPathNamePropertyKey(), this.getDefaultWorkingPath()); this.file = new File(this.workingPath, TEST_FILE_NAME_PREFIX + 1 + TEST_FILE_TYPE); this.trueFilters = new TesterTrueFileFilter[4]; this.falseFilters = new TesterFalseFileFilter[4]; this.trueFilters[1] = new TesterTrueFileFilter(); this.trueFilters[2] = new TesterTrueFileFilter(); this.trueFilters[3] = new TesterTrueFileFilter(); this.falseFilters[1] = new TesterFalseFileFilter(); this.falseFilters[2] = new TesterFalseFileFilter(); this.falseFilters[3] = new TesterFalseFileFilter(); } public void testAdd() { List filters = new ArrayList(); ConditionalFileFilter fileFilter = this.getConditionalFileFilter(); filters.add(new TesterTrueFileFilter()); filters.add(new TesterTrueFileFilter()); filters.add(new TesterTrueFileFilter()); filters.add(new TesterTrueFileFilter()); for(int i = 0; i < filters.size(); i++) { assertEquals("file filters count: ", i, fileFilter.getFileFilters().size()); fileFilter.addFileFilter(filters.get(i)); assertEquals("file filters count: ", i+1, fileFilter.getFileFilters().size()); } for (IOFileFilter filter : fileFilter.getFileFilters()) { assertTrue("found file filter", filters.contains(filter)); } assertEquals("file filters count", filters.size(), fileFilter.getFileFilters().size()); } public void testRemove() { List filters = new ArrayList(); ConditionalFileFilter fileFilter = this.getConditionalFileFilter(); filters.add(new TesterTrueFileFilter()); filters.add(new TesterTrueFileFilter()); filters.add(new TesterTrueFileFilter()); filters.add(new TesterTrueFileFilter()); for(int i = 0; i < filters.size(); i++) { fileFilter.removeFileFilter(filters.get(i)); assertTrue("file filter removed", !fileFilter.getFileFilters().contains(filters.get(i))); } assertEquals("file filters count", 0, fileFilter.getFileFilters().size()); } public void testNoFilters() throws Exception { ConditionalFileFilter fileFilter = this.getConditionalFileFilter(); File file = new File(this.workingPath, TEST_FILE_NAME_PREFIX + 1 + TEST_FILE_TYPE); assertFileFiltering(1, (IOFileFilter) fileFilter, file, false); assertFilenameFiltering(1, (IOFileFilter) fileFilter, file, false); } public void testFilterBuiltUsingConstructor() throws Exception { List> testFilters = this.getTestFilters(); List testTrueResults = this.getTrueResults(); List testFalseResults = this.getFalseResults(); List testFileResults = this.getFileResults(); List testFilenameResults = this.getFilenameResults(); for(int i = 1; i < testFilters.size(); i++) { List filters = testFilters.get(i); boolean[] trueResults = testTrueResults.get(i); boolean[] falseResults = testFalseResults.get(i); boolean fileResults = testFileResults.get(i).booleanValue(); boolean filenameResults = testFilenameResults.get(i).booleanValue(); // Test conditional AND filter created by passing filters to the constructor IOFileFilter filter = this.buildFilterUsingConstructor(filters); // Test as a file filter this.resetTrueFilters(this.trueFilters); this.resetFalseFilters(this.falseFilters); this.assertFileFiltering(i, filter, this.file, fileResults); this.assertTrueFiltersInvoked(i, trueFilters, trueResults); this.assertFalseFiltersInvoked(i, falseFilters, falseResults); // Test as a filename filter this.resetTrueFilters(this.trueFilters); this.resetFalseFilters(this.falseFilters); this.assertFilenameFiltering(i, filter, this.file, filenameResults); this.assertTrueFiltersInvoked(i, trueFilters, trueResults); this.assertFalseFiltersInvoked(i, falseFilters, falseResults); } } public void testFilterBuiltUsingAdd() throws Exception { List> testFilters = this.getTestFilters(); List testTrueResults = this.getTrueResults(); List testFalseResults = this.getFalseResults(); List testFileResults = this.getFileResults(); List testFilenameResults = this.getFilenameResults(); for(int i = 1; i < testFilters.size(); i++) { List filters = testFilters.get(i); boolean[] trueResults = testTrueResults.get(i); boolean[] falseResults = testFalseResults.get(i); boolean fileResults = testFileResults.get(i).booleanValue(); boolean filenameResults = testFilenameResults.get(i).booleanValue(); // Test conditional AND filter created by passing filters to the constructor IOFileFilter filter = this.buildFilterUsingAdd(filters); // Test as a file filter this.resetTrueFilters(this.trueFilters); this.resetFalseFilters(this.falseFilters); this.assertFileFiltering(i, filter, this.file, fileResults); this.assertTrueFiltersInvoked(i, trueFilters, trueResults); this.assertFalseFiltersInvoked(i, falseFilters, falseResults); // Test as a filename filter this.resetTrueFilters(this.trueFilters); this.resetFalseFilters(this.falseFilters); this.assertFilenameFiltering(i, filter, this.file, filenameResults); this.assertTrueFiltersInvoked(i, trueFilters, trueResults); this.assertFalseFiltersInvoked(i, falseFilters, falseResults); } } protected abstract ConditionalFileFilter getConditionalFileFilter(); protected abstract IOFileFilter buildFilterUsingAdd(List filters); protected abstract IOFileFilter buildFilterUsingConstructor(List filters); protected abstract List> getTestFilters(); protected abstract List getTrueResults(); protected abstract List getFalseResults(); protected abstract List getFileResults(); protected abstract List getFilenameResults(); protected abstract String getWorkingPathNamePropertyKey(); protected abstract String getDefaultWorkingPath(); } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/filefilter/IOFileFilterAbstractTestCase.javalibcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/filefilter/IOFileFilterAbstractTestC0000644000175000017500000001223612125050425033071 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.filefilter; import java.io.File; import junit.framework.TestCase; public abstract class IOFileFilterAbstractTestCase extends TestCase { /** * Constructs a new instance of * IOFileFilterAbstractTestCase. */ public IOFileFilterAbstractTestCase(final String name) { super(name); } public boolean assertFileFiltering(final int testNumber, final IOFileFilter filter, final File file, final boolean expected) throws Exception { assertEquals( "test " + testNumber + " Filter(File) " + filter.getClass().getName() + " not " + expected + " for " + file, expected, filter.accept(file)); return true; // return is irrelevant } public boolean assertFilenameFiltering(final int testNumber, final IOFileFilter filter, final File file, final boolean expected) throws Exception { // Assumes file has parent and is not passed as null assertEquals( "test " + testNumber + " Filter(File, String) " + filter.getClass().getName() + " not " + expected + " for " + file, expected, filter.accept(file.getParentFile(), file.getName())); return true; // return is irrelevant } public void assertFiltering(final int testNumber, final IOFileFilter filter, final File file, final boolean expected) throws Exception { // Note. This only tests the (File, String) version if the parent of // the File passed in is not null assertEquals( "test " + testNumber + " Filter(File) " + filter.getClass().getName() + " not " + expected + " for " + file, expected, filter.accept(file)); if (file != null && file.getParentFile() != null) { assertEquals( "test " + testNumber + " Filter(File, String) " + filter.getClass().getName() + " not " + expected + " for " + file, expected, filter.accept(file.getParentFile(), file.getName())); } else if (file == null) { assertEquals( "test " + testNumber + " Filter(File, String) " + filter.getClass().getName() + " not " + expected + " for null", expected, filter.accept(file)); } } public void assertTrueFiltersInvoked(final int testNumber, final TesterTrueFileFilter[] filters, final boolean[] invoked) { for(int i = 1; i < filters.length; i++) { assertEquals("test " + testNumber + " filter " + i + " invoked", invoked[i-1], filters[i].isInvoked()); } } public void assertFalseFiltersInvoked(final int testNumber, final TesterFalseFileFilter[] filters, final boolean[] invoked) { for(int i = 1; i < filters.length; i++) { assertEquals("test " + testNumber + " filter " + i + " invoked", invoked[i-1], filters[i].isInvoked()); } } public File determineWorkingDirectoryPath(final String key, final String defaultPath) { // Look for a system property to specify the working directory String workingPathName = System.getProperty(key, defaultPath); return new File(workingPathName); } public void resetFalseFilters(TesterFalseFileFilter[] filters) { for (TesterFalseFileFilter filter : filters) { if(filter != null) { filter.reset(); } } } public void resetTrueFilters(TesterTrueFileFilter[] filters) { for (TesterTrueFileFilter filter : filters) { if(filter != null) { filter.reset(); } } } class TesterTrueFileFilter extends TrueFileFilter { private boolean invoked; @Override public boolean accept(File file) { setInvoked(true); return super.accept(file); } @Override public boolean accept(File file, String str) { setInvoked(true); return super.accept(file, str); } public boolean isInvoked() { return this.invoked; } public void setInvoked(boolean invoked) { this.invoked = invoked; } public void reset() { setInvoked(false); } } class TesterFalseFileFilter extends FalseFileFilter { private boolean invoked; @Override public boolean accept(File file) { setInvoked(true); return super.accept(file); } @Override public boolean accept(File file, String str) { setInvoked(true); return super.accept(file, str); } public boolean isInvoked() { return this.invoked; } public void setInvoked(boolean invoked) { this.invoked = invoked; } public void reset() { setInvoked(false); } } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/DemuxTestCase.java0000644000175000017500000001623112125050425027475 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.HashMap; import java.util.Iterator; import java.util.Random; import org.apache.commons.io.input.DemuxInputStream; import org.apache.commons.io.output.ByteArrayOutputStream; import org.apache.commons.io.output.DemuxOutputStream; import org.junit.Test; /** * Basic unit tests for the multiplexing streams. */ public class DemuxTestCase { private static final String T1 = "Thread1"; private static final String T2 = "Thread2"; private static final String T3 = "Thread3"; private static final String T4 = "Thread4"; private static final String DATA1 = "Data for thread1"; private static final String DATA2 = "Data for thread2"; private static final String DATA3 = "Data for thread3"; private static final String DATA4 = "Data for thread4"; private static final Random c_random = new Random(); private HashMap m_outputMap = new HashMap(); private HashMap m_threadMap = new HashMap(); private String getOutput( String threadName ) { ByteArrayOutputStream output = m_outputMap.get( threadName ); assertNotNull( "getOutput()", output ); return output.toString(); } private String getInput( String threadName ) { ReaderThread thread = (ReaderThread)m_threadMap.get( threadName ); assertNotNull( "getInput()", thread ); return thread.getData(); } private void doStart() throws Exception { Iterator iterator = m_threadMap.keySet().iterator(); while( iterator.hasNext() ) { String name = iterator.next(); Thread thread = m_threadMap.get( name ); thread.start(); } } private void doJoin() throws Exception { Iterator iterator = m_threadMap.keySet().iterator(); while( iterator.hasNext() ) { String name = iterator.next(); Thread thread = m_threadMap.get( name ); thread.join(); } } private void startWriter( String name, String data, DemuxOutputStream demux ) throws Exception { ByteArrayOutputStream output = new ByteArrayOutputStream(); m_outputMap.put( name, output ); WriterThread thread = new WriterThread( name, data, output, demux ); m_threadMap.put( name, thread ); } private void startReader( String name, String data, DemuxInputStream demux ) throws Exception { ByteArrayInputStream input = new ByteArrayInputStream( data.getBytes() ); ReaderThread thread = new ReaderThread( name, input, demux ); m_threadMap.put( name, thread ); } @Test public void testOutputStream() throws Exception { DemuxOutputStream output = new DemuxOutputStream(); startWriter( T1, DATA1, output ); startWriter( T2, DATA2, output ); startWriter( T3, DATA3, output ); startWriter( T4, DATA4, output ); doStart(); doJoin(); assertEquals( "Data1", DATA1, getOutput( T1 ) ); assertEquals( "Data2", DATA2, getOutput( T2 ) ); assertEquals( "Data3", DATA3, getOutput( T3 ) ); assertEquals( "Data4", DATA4, getOutput( T4 ) ); } @Test public void testInputStream() throws Exception { DemuxInputStream input = new DemuxInputStream(); startReader( T1, DATA1, input ); startReader( T2, DATA2, input ); startReader( T3, DATA3, input ); startReader( T4, DATA4, input ); doStart(); doJoin(); assertEquals( "Data1", DATA1, getInput( T1 ) ); assertEquals( "Data2", DATA2, getInput( T2 ) ); assertEquals( "Data3", DATA3, getInput( T3 ) ); assertEquals( "Data4", DATA4, getInput( T4 ) ); } private static class ReaderThread extends Thread { private StringBuffer m_buffer = new StringBuffer(); private InputStream m_input; private DemuxInputStream m_demux; ReaderThread( String name, InputStream input, DemuxInputStream demux ) { super( name ); m_input = input; m_demux = demux; } public String getData() { return m_buffer.toString(); } @Override public void run() { m_demux.bindStream( m_input ); try { int ch = m_demux.read(); while( -1 != ch ) { //System.out.println( "Reading: " + (char)ch ); m_buffer.append( (char)ch ); int sleepTime = Math.abs( c_random.nextInt() % 10 ); Thread.sleep( sleepTime ); ch = m_demux.read(); } } catch( Exception e ) { e.printStackTrace(); } } } private static class WriterThread extends Thread { private byte[] m_data; private OutputStream m_output; private DemuxOutputStream m_demux; WriterThread( String name, String data, OutputStream output, DemuxOutputStream demux ) { super( name ); m_output = output; m_demux = demux; m_data = data.getBytes(); } @Override public void run() { m_demux.bindStream( m_output ); for (byte element : m_data) { try { //System.out.println( "Writing: " + (char)m_data[ i ] ); m_demux.write( element ); int sleepTime = Math.abs( c_random.nextInt() % 10 ); Thread.sleep( sleepTime ); } catch( Exception e ) { e.printStackTrace(); } } } } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/FileCleaningTrackerTestCase.java0000644000175000017500000002704412125050425032253 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.io.File; import java.io.RandomAccessFile; import java.lang.ref.ReferenceQueue; import java.util.ArrayList; import java.util.List; import org.apache.commons.io.testtools.FileBasedTestCase; /** * This is used to test {@link FileCleaningTracker} for correctness. * * @version $Id: FileCleaningTrackerTestCase.java 1302056 2012-03-18 03:03:38Z ggregory $ * @see FileCleaningTracker */ public class FileCleaningTrackerTestCase extends FileBasedTestCase { protected FileCleaningTracker newInstance() { return new FileCleaningTracker(); } private File testFile; private FileCleaningTracker theInstance; public FileCleaningTrackerTestCase(String name) { super(name); testFile = new File(getTestDirectory(), "file-test.txt"); } /** @see junit.framework.TestCase#setUp() */ @Override protected void setUp() throws Exception { theInstance = newInstance(); getTestDirectory().mkdirs(); } /** @see junit.framework.TestCase#tearDown() */ @Override protected void tearDown() throws Exception { FileUtils.deleteDirectory(getTestDirectory()); // reset file cleaner class, so as not to break other tests /** * The following block of code can possibly be removed when the * deprecated {@link FileCleaner} is gone. The question is, whether * we want to support reuse of {@link FileCleaningTracker} instances, * which we should, IMO, not. */ { theInstance.q = new ReferenceQueue(); theInstance.trackers.clear(); theInstance.deleteFailures.clear(); theInstance.exitWhenFinished = false; theInstance.reaper = null; } theInstance = null; } //----------------------------------------------------------------------- public void testFileCleanerFile() throws Exception { String path = testFile.getPath(); assertFalse(testFile.exists()); RandomAccessFile r = new RandomAccessFile(testFile, "rw"); assertTrue(testFile.exists()); assertEquals(0, theInstance.getTrackCount()); theInstance.track(path, r); assertEquals(1, theInstance.getTrackCount()); r.close(); testFile = null; r = null; waitUntilTrackCount(); pauseForDeleteToComplete(new File(path)); assertEquals(0, theInstance.getTrackCount()); assertEquals(showFailures(), false, new File(path).exists()); } public void testFileCleanerDirectory() throws Exception { createFile(testFile, 100); assertTrue(testFile.exists()); assertTrue(getTestDirectory().exists()); Object obj = new Object(); assertEquals(0, theInstance.getTrackCount()); theInstance.track(getTestDirectory(), obj); assertEquals(1, theInstance.getTrackCount()); obj = null; waitUntilTrackCount(); assertEquals(0, theInstance.getTrackCount()); assertTrue(testFile.exists()); // not deleted, as dir not empty assertTrue(testFile.getParentFile().exists()); // not deleted, as dir not empty } public void testFileCleanerDirectory_NullStrategy() throws Exception { createFile(testFile, 100); assertTrue(testFile.exists()); assertTrue(getTestDirectory().exists()); Object obj = new Object(); assertEquals(0, theInstance.getTrackCount()); theInstance.track(getTestDirectory(), obj, (FileDeleteStrategy) null); assertEquals(1, theInstance.getTrackCount()); obj = null; waitUntilTrackCount(); assertEquals(0, theInstance.getTrackCount()); assertTrue(testFile.exists()); // not deleted, as dir not empty assertTrue(testFile.getParentFile().exists()); // not deleted, as dir not empty } public void testFileCleanerDirectory_ForceStrategy() throws Exception { createFile(testFile, 100); assertTrue(testFile.exists()); assertTrue(getTestDirectory().exists()); Object obj = new Object(); assertEquals(0, theInstance.getTrackCount()); theInstance.track(getTestDirectory(), obj, FileDeleteStrategy.FORCE); assertEquals(1, theInstance.getTrackCount()); obj = null; waitUntilTrackCount(); pauseForDeleteToComplete(testFile.getParentFile()); assertEquals(0, theInstance.getTrackCount()); assertEquals(showFailures(), false, new File(testFile.getPath()).exists()); assertEquals(showFailures(), false, testFile.getParentFile().exists()); } public void testFileCleanerNull() throws Exception { try { theInstance.track((File) null, new Object()); fail(); } catch (NullPointerException ex) { // expected } try { theInstance.track((File) null, new Object(), FileDeleteStrategy.NORMAL); fail(); } catch (NullPointerException ex) { // expected } try { theInstance.track((String) null, new Object()); fail(); } catch (NullPointerException ex) { // expected } try { theInstance.track((String) null, new Object(), FileDeleteStrategy.NORMAL); fail(); } catch (NullPointerException ex) { // expected } } public void testFileCleanerExitWhenFinishedFirst() throws Exception { assertFalse(theInstance.exitWhenFinished); theInstance.exitWhenFinished(); assertTrue(theInstance.exitWhenFinished); assertEquals(null, theInstance.reaper); waitUntilTrackCount(); assertEquals(0, theInstance.getTrackCount()); assertTrue(theInstance.exitWhenFinished); assertEquals(null, theInstance.reaper); } public void testFileCleanerExitWhenFinished_NoTrackAfter() throws Exception { assertFalse(theInstance.exitWhenFinished); theInstance.exitWhenFinished(); assertTrue(theInstance.exitWhenFinished); assertEquals(null, theInstance.reaper); String path = testFile.getPath(); Object marker = new Object(); try { theInstance.track(path, marker); fail(); } catch (IllegalStateException ex) { // expected } assertTrue(theInstance.exitWhenFinished); assertEquals(null, theInstance.reaper); } public void testFileCleanerExitWhenFinished1() throws Exception { String path = testFile.getPath(); assertEquals("1-testFile exists", false, testFile.exists()); RandomAccessFile r = new RandomAccessFile(testFile, "rw"); assertEquals("2-testFile exists", true, testFile.exists()); assertEquals("3-Track Count", 0, theInstance.getTrackCount()); theInstance.track(path, r); assertEquals("4-Track Count", 1, theInstance.getTrackCount()); assertEquals("5-exitWhenFinished", false, theInstance.exitWhenFinished); assertEquals("6-reaper.isAlive", true, theInstance.reaper.isAlive()); assertEquals("7-exitWhenFinished", false, theInstance.exitWhenFinished); theInstance.exitWhenFinished(); assertEquals("8-exitWhenFinished", true, theInstance.exitWhenFinished); assertEquals("9-reaper.isAlive", true, theInstance.reaper.isAlive()); r.close(); testFile = null; r = null; waitUntilTrackCount(); pauseForDeleteToComplete(new File(path)); assertEquals("10-Track Count", 0, theInstance.getTrackCount()); assertEquals("11-testFile exists " + showFailures(), false, new File(path).exists()); assertEquals("12-exitWhenFinished", true, theInstance.exitWhenFinished); assertEquals("13-reaper.isAlive", false, theInstance.reaper.isAlive()); } public void testFileCleanerExitWhenFinished2() throws Exception { String path = testFile.getPath(); assertFalse(testFile.exists()); RandomAccessFile r = new RandomAccessFile(testFile, "rw"); assertTrue(testFile.exists()); assertEquals(0, theInstance.getTrackCount()); theInstance.track(path, r); assertEquals(1, theInstance.getTrackCount()); assertFalse(theInstance.exitWhenFinished); assertTrue(theInstance.reaper.isAlive()); r.close(); testFile = null; r = null; waitUntilTrackCount(); pauseForDeleteToComplete(new File(path)); assertEquals(0, theInstance.getTrackCount()); assertEquals(showFailures(), false, new File(path).exists()); assertFalse(theInstance.exitWhenFinished); assertTrue(theInstance.reaper.isAlive()); assertFalse(theInstance.exitWhenFinished); theInstance.exitWhenFinished(); for (int i = 0; i < 20 && theInstance.reaper.isAlive(); i++) { Thread.sleep(500L); // allow reaper thread to die } assertTrue(theInstance.exitWhenFinished); assertFalse(theInstance.reaper.isAlive()); } //----------------------------------------------------------------------- private void pauseForDeleteToComplete(File file) { int count = 0; while(file.exists() && count++ < 40) { try { Thread.sleep(500L); } catch (InterruptedException e) { } file = new File(file.getPath()); } } private String showFailures() throws Exception { if (theInstance.deleteFailures.size() == 1) { return "[Delete Failed: " + theInstance.deleteFailures.get(0) + "]"; } else { return "[Delete Failures: " + theInstance.deleteFailures.size() + "]"; } } private void waitUntilTrackCount() throws Exception { System.gc(); Thread.sleep(500); int count = 0; while(theInstance.getTrackCount() != 0 && count++ < 5) { List list = new ArrayList(); try { long i = 0; while (theInstance.getTrackCount() != 0) { list.add("A Big String A Big String A Big String A Big String A Big String A Big String A Big String A Big String A Big String A Big String " + (i++)); } } catch (Throwable ignored) { } list = null; System.gc(); Thread.sleep(1000); } if (theInstance.getTrackCount() != 0) { throw new IllegalStateException("Your JVM is not releasing References, try running the testcase with less memory (-Xmx)"); } } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/ByteOrderMarkTestCase.java0000644000175000017500000001337712125050425031135 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.nio.charset.Charset; import java.util.Arrays; import org.apache.commons.io.testtools.FileBasedTestCase; /** * Test for {@link ByteOrderMark}. * * @version $Id: ByteOrderMarkTestCase.java 1310395 2012-04-06 15:17:38Z ggregory $ */ public class ByteOrderMarkTestCase extends FileBasedTestCase { private static final ByteOrderMark TEST_BOM_1 = new ByteOrderMark("test1", 1); private static final ByteOrderMark TEST_BOM_2 = new ByteOrderMark("test2", 1, 2); private static final ByteOrderMark TEST_BOM_3 = new ByteOrderMark("test3", 1, 2, 3); public ByteOrderMarkTestCase(String name) { super(name); } /** Test {@link ByteOrderMark#getCharsetName()} */ public void testCharsetName() { assertEquals("test1 name", "test1", TEST_BOM_1.getCharsetName()); assertEquals("test2 name", "test2", TEST_BOM_2.getCharsetName()); assertEquals("test3 name", "test3", TEST_BOM_3.getCharsetName()); } /** Tests that {@link ByteOrderMark#getCharsetName()} can be loaded as a {@link java.nio.charset.Charset} as advertised. */ public void testConstantCharsetNames() { assertNotNull(Charset.forName(ByteOrderMark.UTF_8.getCharsetName())); assertNotNull(Charset.forName(ByteOrderMark.UTF_16BE.getCharsetName())); assertNotNull(Charset.forName(ByteOrderMark.UTF_16LE.getCharsetName())); assertNotNull(Charset.forName(ByteOrderMark.UTF_32BE.getCharsetName())); assertNotNull(Charset.forName(ByteOrderMark.UTF_32LE.getCharsetName())); } /** Test {@link ByteOrderMark#length()} */ public void testLength() { assertEquals("test1 length", 1, TEST_BOM_1.length()); assertEquals("test2 length", 2, TEST_BOM_2.length()); assertEquals("test3 length", 3, TEST_BOM_3.length()); } /** Test {@link ByteOrderMark#get(int)} */ public void testGet() { assertEquals("test1 get(0)", 1, TEST_BOM_1.get(0)); assertEquals("test2 get(0)", 1, TEST_BOM_2.get(0)); assertEquals("test2 get(1)", 2, TEST_BOM_2.get(1)); assertEquals("test3 get(0)", 1, TEST_BOM_3.get(0)); assertEquals("test3 get(1)", 2, TEST_BOM_3.get(1)); assertEquals("test3 get(2)", 3, TEST_BOM_3.get(2)); } /** Test {@link ByteOrderMark#getBytes()} */ public void testGetBytes() { assertTrue("test1 bytes", Arrays.equals(TEST_BOM_1.getBytes(), new byte[] {(byte)1})); assertTrue("test1 bytes", Arrays.equals(TEST_BOM_2.getBytes(), new byte[] {(byte)1, (byte)2})); assertTrue("test1 bytes", Arrays.equals(TEST_BOM_3.getBytes(), new byte[] {(byte)1, (byte)2, (byte)3})); } /** Test {@link ByteOrderMark#equals(Object)} */ public void testEquals() { assertTrue("test1 equals", TEST_BOM_1.equals(TEST_BOM_1)); assertTrue("test2 equals", TEST_BOM_2.equals(TEST_BOM_2)); assertTrue("test3 equals", TEST_BOM_3.equals(TEST_BOM_3)); assertFalse("Object not equal", TEST_BOM_1.equals(new Object())); assertFalse("test1-1 not equal", TEST_BOM_1.equals(new ByteOrderMark("1a", 2))); assertFalse("test1-2 not test2", TEST_BOM_1.equals(new ByteOrderMark("1b", 1, 2))); assertFalse("test2 not equal", TEST_BOM_2.equals(new ByteOrderMark("2", 1, 1))); assertFalse("test3 not equal", TEST_BOM_3.equals(new ByteOrderMark("3", 1, 2, 4))); } /** Test {@link ByteOrderMark#hashCode()} */ public void testHashCode() { int bomClassHash = ByteOrderMark.class.hashCode(); assertEquals("hash test1 ", bomClassHash + 1, TEST_BOM_1.hashCode()); assertEquals("hash test2 ", bomClassHash + 3, TEST_BOM_2.hashCode()); assertEquals("hash test3 ", bomClassHash + 6, TEST_BOM_3.hashCode()); } /** Test Erros */ public void testErrors() { try { new ByteOrderMark(null, 1,2,3); fail("null charset name, expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // expected } try { new ByteOrderMark("", 1,2,3); fail("no charset name, expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // expected } try { new ByteOrderMark("a", (int[])null); fail("null bytes, expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // expected } try { new ByteOrderMark("b", new int[0]); fail("empty bytes, expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // expected } } /** Test {@link ByteOrderMark#toString()} */ public void testToString() { assertEquals("test1 ", "ByteOrderMark[test1: 0x1]", TEST_BOM_1.toString()); assertEquals("test2 ", "ByteOrderMark[test2: 0x1,0x2]", TEST_BOM_2.toString()); assertEquals("test3 ", "ByteOrderMark[test3: 0x1,0x2,0x3]", TEST_BOM_3.toString()); } } libcommons-io-java-2.4.orig/src/test/java/org/apache/commons/io/EndianUtilsTest.java0000644000175000017500000002761712125050425030050 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.EOFException; import java.io.IOException; import junit.framework.TestCase; /** * @version $Id: EndianUtilsTest.java 1302056 2012-03-18 03:03:38Z ggregory $ */ public class EndianUtilsTest extends TestCase { public EndianUtilsTest(String name) { super(name); } public void testCtor() { new EndianUtils(); // Constructor does not blow up. } public void testEOFException() throws IOException { ByteArrayInputStream input = new ByteArrayInputStream(new byte[] {}); try { EndianUtils.readSwappedDouble(input); fail("Expected EOFException"); } catch (EOFException e) { // expected } } public void testSwapShort() { assertEquals( (short) 0, EndianUtils.swapShort( (short) 0 ) ); assertEquals( (short) 0x0201, EndianUtils.swapShort( (short) 0x0102 ) ); assertEquals( (short) 0xffff, EndianUtils.swapShort( (short) 0xffff ) ); assertEquals( (short) 0x0102, EndianUtils.swapShort( (short) 0x0201 ) ); } public void testSwapInteger() { assertEquals( 0, EndianUtils.swapInteger( 0 ) ); assertEquals( 0x04030201, EndianUtils.swapInteger( 0x01020304 ) ); assertEquals( 0x01000000, EndianUtils.swapInteger( 0x00000001 ) ); assertEquals( 0x00000001, EndianUtils.swapInteger( 0x01000000 ) ); assertEquals( 0x11111111, EndianUtils.swapInteger( 0x11111111 ) ); assertEquals( 0xabcdef10, EndianUtils.swapInteger( 0x10efcdab ) ); assertEquals( 0xab, EndianUtils.swapInteger( 0xab000000 ) ); } public void testSwapLong() { assertEquals( 0, EndianUtils.swapLong( 0 ) ); assertEquals( 0x0807060504030201L, EndianUtils.swapLong( 0x0102030405060708L ) ); assertEquals( 0xffffffffffffffffL, EndianUtils.swapLong( 0xffffffffffffffffL ) ); assertEquals( 0xab, EndianUtils.swapLong( 0xab00000000000000L ) ); } public void testSwapFloat() { assertEquals( 0.0f, EndianUtils.swapFloat( 0.0f ), 0.0 ); float f1 = Float.intBitsToFloat( 0x01020304 ); float f2 = Float.intBitsToFloat( 0x04030201 ); assertEquals( f2, EndianUtils.swapFloat( f1 ), 0.0 ); } public void testSwapDouble() { assertEquals( 0.0, EndianUtils.swapDouble( 0.0 ), 0.0 ); double d1 = Double.longBitsToDouble( 0x0102030405060708L ); double d2 = Double.longBitsToDouble( 0x0807060504030201L ); assertEquals( d2, EndianUtils.swapDouble( d1 ), 0.0 ); } /** * Tests all swapXxxx methods for symmetry when going from one endian * to another and back again. */ public void testSymmetry() { assertEquals( (short) 0x0102, EndianUtils.swapShort( EndianUtils.swapShort( (short) 0x0102 ) ) ); assertEquals( 0x01020304, EndianUtils.swapInteger( EndianUtils.swapInteger( 0x01020304 ) ) ); assertEquals( 0x0102030405060708L, EndianUtils.swapLong( EndianUtils.swapLong( 0x0102030405060708L ) ) ); float f1 = Float.intBitsToFloat( 0x01020304 ); assertEquals( f1, EndianUtils.swapFloat( EndianUtils.swapFloat( f1 ) ), 0.0 ); double d1 = Double.longBitsToDouble( 0x0102030405060708L ); assertEquals( d1, EndianUtils.swapDouble( EndianUtils.swapDouble( d1 ) ), 0.0 ); } public void testReadSwappedShort() throws IOException { byte[] bytes = new byte[] { 0x02, 0x01 }; assertEquals( 0x0102, EndianUtils.readSwappedShort( bytes, 0 ) ); ByteArrayInputStream input = new ByteArrayInputStream(bytes); assertEquals( 0x0102, EndianUtils.readSwappedShort( input ) ); } public void testWriteSwappedShort() throws IOException { byte[] bytes = new byte[2]; EndianUtils.writeSwappedShort( bytes, 0, (short) 0x0102 ); assertEquals( 0x02, bytes[0] ); assertEquals( 0x01, bytes[1] ); ByteArrayOutputStream baos = new ByteArrayOutputStream(2); EndianUtils.writeSwappedShort( baos, (short) 0x0102 ); bytes = baos.toByteArray(); assertEquals( 0x02, bytes[0] ); assertEquals( 0x01, bytes[1] ); } public void testReadSwappedUnsignedShort() throws IOException { byte[] bytes = new byte[] { 0x02, 0x01 }; assertEquals( 0x00000102, EndianUtils.readSwappedUnsignedShort( bytes, 0 ) ); ByteArrayInputStream input = new ByteArrayInputStream(bytes); assertEquals( 0x00000102, EndianUtils.readSwappedUnsignedShort( input ) ); } public void testReadSwappedInteger() throws IOException { byte[] bytes = new byte[] { 0x04, 0x03, 0x02, 0x01 }; assertEquals( 0x01020304, EndianUtils.readSwappedInteger( bytes, 0 ) ); ByteArrayInputStream input = new ByteArrayInputStream(bytes); assertEquals( 0x01020304, EndianUtils.readSwappedInteger( input ) ); } public void testWriteSwappedInteger() throws IOException { byte[] bytes = new byte[4]; EndianUtils.writeSwappedInteger( bytes, 0, 0x01020304 ); assertEquals( 0x04, bytes[0] ); assertEquals( 0x03, bytes[1] ); assertEquals( 0x02, bytes[2] ); assertEquals( 0x01, bytes[3] ); ByteArrayOutputStream baos = new ByteArrayOutputStream(4); EndianUtils.writeSwappedInteger( baos, 0x01020304 ); bytes = baos.toByteArray(); assertEquals( 0x04, bytes[0] ); assertEquals( 0x03, bytes[1] ); assertEquals( 0x02, bytes[2] ); assertEquals( 0x01, bytes[3] ); } public void testReadSwappedUnsignedInteger() throws IOException { byte[] bytes = new byte[] { 0x04, 0x03, 0x02, 0x01 }; assertEquals( 0x0000000001020304L, EndianUtils.readSwappedUnsignedInteger( bytes, 0 ) ); ByteArrayInputStream input = new ByteArrayInputStream(bytes); assertEquals( 0x0000000001020304L, EndianUtils.readSwappedUnsignedInteger( input ) ); } public void testReadSwappedLong() throws IOException { byte[] bytes = new byte[] { 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01 }; assertEquals( 0x0102030405060708L, EndianUtils.readSwappedLong( bytes, 0 ) ); ByteArrayInputStream input = new ByteArrayInputStream(bytes); assertEquals( 0x0102030405060708L, EndianUtils.readSwappedLong( input ) ); } public void testWriteSwappedLong() throws IOException { byte[] bytes = new byte[8]; EndianUtils.writeSwappedLong( bytes, 0, 0x0102030405060708L ); assertEquals( 0x08, bytes[0] ); assertEquals( 0x07, bytes[1] ); assertEquals( 0x06, bytes[2] ); assertEquals( 0x05, bytes[3] ); assertEquals( 0x04, bytes[4] ); assertEquals( 0x03, bytes[5] ); assertEquals( 0x02, bytes[6] ); assertEquals( 0x01, bytes[7] ); ByteArrayOutputStream baos = new ByteArrayOutputStream(8); EndianUtils.writeSwappedLong( baos, 0x0102030405060708L ); bytes = baos.toByteArray(); assertEquals( 0x08, bytes[0] ); assertEquals( 0x07, bytes[1] ); assertEquals( 0x06, bytes[2] ); assertEquals( 0x05, bytes[3] ); assertEquals( 0x04, bytes[4] ); assertEquals( 0x03, bytes[5] ); assertEquals( 0x02, bytes[6] ); assertEquals( 0x01, bytes[7] ); } public void testReadSwappedFloat() throws IOException { byte[] bytes = new byte[] { 0x04, 0x03, 0x02, 0x01 }; float f1 = Float.intBitsToFloat( 0x01020304 ); float f2 = EndianUtils.readSwappedFloat( bytes, 0 ); assertEquals( f1, f2, 0.0 ); ByteArrayInputStream input = new ByteArrayInputStream(bytes); assertEquals( f1, EndianUtils.readSwappedFloat( input ), 0.0 ); } public void testWriteSwappedFloat() throws IOException { byte[] bytes = new byte[4]; float f1 = Float.intBitsToFloat( 0x01020304 ); EndianUtils.writeSwappedFloat( bytes, 0, f1 ); assertEquals( 0x04, bytes[0] ); assertEquals( 0x03, bytes[1] ); assertEquals( 0x02, bytes[2] ); assertEquals( 0x01, bytes[3] ); ByteArrayOutputStream baos = new ByteArrayOutputStream(4); EndianUtils.writeSwappedFloat( baos, f1 ); bytes = baos.toByteArray(); assertEquals( 0x04, bytes[0] ); assertEquals( 0x03, bytes[1] ); assertEquals( 0x02, bytes[2] ); assertEquals( 0x01, bytes[3] ); } public void testReadSwappedDouble() throws IOException { byte[] bytes = new byte[] { 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01 }; double d1 = Double.longBitsToDouble( 0x0102030405060708L ); double d2 = EndianUtils.readSwappedDouble( bytes, 0 ); assertEquals( d1, d2, 0.0 ); ByteArrayInputStream input = new ByteArrayInputStream(bytes); assertEquals( d1, EndianUtils.readSwappedDouble( input ), 0.0 ); } public void testWriteSwappedDouble() throws IOException { byte[] bytes = new byte[8]; double d1 = Double.longBitsToDouble( 0x0102030405060708L ); EndianUtils.writeSwappedDouble( bytes, 0, d1 ); assertEquals( 0x08, bytes[0] ); assertEquals( 0x07, bytes[1] ); assertEquals( 0x06, bytes[2] ); assertEquals( 0x05, bytes[3] ); assertEquals( 0x04, bytes[4] ); assertEquals( 0x03, bytes[5] ); assertEquals( 0x02, bytes[6] ); assertEquals( 0x01, bytes[7] ); ByteArrayOutputStream baos = new ByteArrayOutputStream(8); EndianUtils.writeSwappedDouble( baos, d1 ); bytes = baos.toByteArray(); assertEquals( 0x08, bytes[0] ); assertEquals( 0x07, bytes[1] ); assertEquals( 0x06, bytes[2] ); assertEquals( 0x05, bytes[3] ); assertEquals( 0x04, bytes[4] ); assertEquals( 0x03, bytes[5] ); assertEquals( 0x02, bytes[6] ); assertEquals( 0x01, bytes[7] ); } // tests #IO-101 public void testSymmetryOfLong() { double[] tests = new double[] {34.345, -345.5645, 545.12, 10.043, 7.123456789123}; for (double test : tests) { // testing the real problem byte[] buffer = new byte[8]; long ln1 = Double.doubleToLongBits( test ); EndianUtils.writeSwappedLong(buffer, 0, ln1); long ln2 = EndianUtils.readSwappedLong(buffer, 0); assertEquals( ln1, ln2 ); // testing the bug report buffer = new byte[8]; EndianUtils.writeSwappedDouble(buffer, 0, test); double val = EndianUtils.readSwappedDouble(buffer, 0); assertEquals( test, val, 0 ); } } // tests #IO-117 public void testUnsignedOverrun() throws Exception { byte[] target = new byte[] { 0, 0, 0, (byte)0x80 }; long expected = 0x80000000L; long actual = EndianUtils.readSwappedUnsignedInteger(target, 0); assertEquals("readSwappedUnsignedInteger(byte[], int) was incorrect", expected, actual); ByteArrayInputStream in = new ByteArrayInputStream(target); actual = EndianUtils.readSwappedUnsignedInteger(in); assertEquals("readSwappedUnsignedInteger(InputStream) was incorrect", expected, actual); } } libcommons-io-java-2.4.orig/src/test/resources/0000755000175000017500000000000012125050425021110 5ustar ebourgebourglibcommons-io-java-2.4.orig/src/test/resources/test-file-iso8859-1.bin0000644000175000017500000000262612125050425024770 0ustar ebourgebourgA Test Line. Special chars: ÄäÜüÖöß Ăáéíďçń ©µĄŁ±˛® A Test Line. Special chars: ÄäÜüÖöß Ăáéíďçń ©µĄŁ±˛ A Test Line. Special chars: ÄäÜüÖöß Ăáéíďçń ©µĄŁ± A Test Line. Special chars: ÄäÜüÖöß Ăáéíďçń ©µĄŁ A Test Line. Special chars: ÄäÜüÖöß Ăáéíďçń ©µĄ A Test Line. Special chars: ÄäÜüÖöß Ăáéíďçń ©µ A Test Line. Special chars: ÄäÜüÖöß Ăáéíďçń © A Test Line. Special chars: ÄäÜüÖöß Ăáéíďçń A Test Line. Special chars: ÄäÜüÖöß Ăáéíďçń A Test Line. Special chars: ÄäÜüÖöß Ăáéíďçń A Test Line. Special chars: ÄäÜüÖöß Ăáéíďç A Test Line. Special chars: ÄäÜüÖöß Ăáéíď A Test Line. Special chars: ÄäÜüÖöß Ăáéí A Test Line. Special chars: ÄäÜüÖöß Ăáé A Test Line. Special chars: ÄäÜüÖöß Ăá A Test Line. Special chars: ÄäÜüÖöß Ă A Test Line. Special chars: ÄäÜüÖöß A Test Line. Special chars: ÄäÜüÖöß A Test Line. Special chars: ÄäÜüÖö A Test Line. Special chars: ÄäÜüÖ A Test Line. Special chars: ÄäÜü A Test Line. Special chars: ÄäÜ A Test Line. Special chars: Ää A Test Line. Special chars: Ä A Test Line. Special chars: A Test Line. Special chars: A Test Line. Special chars A Test Line. Special char A Test Line. Special cha A Test Line. Special ch A Test Line. Special c A Test Line. Special A Test Line. Special A Test Line. Specia A Test Line. Speci A Test Line. Spec A Test Line. Spe A Test Line. Sp A Test Line. S A Test Line. A Test Line. A Test Line A Test Lin A Test Li A Test L A Test A Test A Tes A Te A T A A libcommons-io-java-2.4.orig/src/test/resources/test-file-20byteslength.bin0000644000175000017500000000002412125050425026162 0ustar ebourgebourg123456789 123456789 libcommons-io-java-2.4.orig/src/test/resources/test-file-utf8-win-linebr.bin0000644000175000017500000000325112125050425026427 0ustar ebourgebourgA Test Line. Special chars: ÄäÜüÖöß Ăáéíïçñ ©µ¥£±²® A Test Line. Special chars: ÄäÜüÖöß Ăáéíïçñ ©µ¥£±² A Test Line. Special chars: ÄäÜüÖöß Ăáéíïçñ ©µ¥£± A Test Line. Special chars: ÄäÜüÖöß Ăáéíïçñ ©µ¥£ A Test Line. Special chars: ÄäÜüÖöß Ăáéíïçñ ©µ¥ A Test Line. Special chars: ÄäÜüÖöß Ăáéíïçñ ©µ A Test Line. Special chars: ÄäÜüÖöß Ăáéíïçñ © A Test Line. Special chars: ÄäÜüÖöß Ăáéíïçñ A Test Line. Special chars: ÄäÜüÖöß Ăáéíïçñ A Test Line. Special chars: ÄäÜüÖöß Ăáéíïçñ A Test Line. Special chars: ÄäÜüÖöß Ăáéíïç A Test Line. Special chars: ÄäÜüÖöß Ăáéíï A Test Line. Special chars: ÄäÜüÖöß Ăáéí A Test Line. Special chars: ÄäÜüÖöß Ăáé A Test Line. Special chars: ÄäÜüÖöß Ăá A Test Line. Special chars: ÄäÜüÖöß Ă A Test Line. Special chars: ÄäÜüÖöß A Test Line. Special chars: ÄäÜüÖöß A Test Line. Special chars: ÄäÜüÖö A Test Line. Special chars: ÄäÜüÖ A Test Line. Special chars: ÄäÜü A Test Line. Special chars: ÄäÜ A Test Line. Special chars: Ää A Test Line. Special chars: Ă„ A Test Line. Special chars: A Test Line. Special chars: A Test Line. Special chars A Test Line. Special char A Test Line. Special cha A Test Line. Special ch A Test Line. Special c A Test Line. Special A Test Line. Special A Test Line. Specia A Test Line. Speci A Test Line. Spec A Test Line. Spe A Test Line. Sp A Test Line. S A Test Line. A Test Line. A Test Line A Test Lin A Test Li A Test L A Test A Test A Tes A Te A T A A libcommons-io-java-2.4.orig/src/test/resources/test-file-empty.bin0000644000175000017500000000000012125050425024620 0ustar ebourgebourglibcommons-io-java-2.4.orig/src/test/resources/test-file-iso8859-1-shortlines-win-linebr.bin0000644000175000017500000000001712125050425031214 0ustar ebourgebourg1 2 3 libcommons-io-java-2.4.orig/src/test/resources/test-file-utf8.bin0000644000175000017500000000325112125050425024363 0ustar ebourgebourgA Test Line. Special chars: ÄäÜüÖöß Ăáéíïçñ ©µ¥£±²® A Test Line. Special chars: ÄäÜüÖöß Ăáéíïçñ ©µ¥£±² A Test Line. Special chars: ÄäÜüÖöß Ăáéíïçñ ©µ¥£± A Test Line. Special chars: ÄäÜüÖöß Ăáéíïçñ ©µ¥£ A Test Line. Special chars: ÄäÜüÖöß Ăáéíïçñ ©µ¥ A Test Line. Special chars: ÄäÜüÖöß Ăáéíïçñ ©µ A Test Line. Special chars: ÄäÜüÖöß Ăáéíïçñ © A Test Line. Special chars: ÄäÜüÖöß Ăáéíïçñ A Test Line. Special chars: ÄäÜüÖöß Ăáéíïçñ A Test Line. Special chars: ÄäÜüÖöß Ăáéíïçñ A Test Line. Special chars: ÄäÜüÖöß Ăáéíïç A Test Line. Special chars: ÄäÜüÖöß Ăáéíï A Test Line. Special chars: ÄäÜüÖöß Ăáéí A Test Line. Special chars: ÄäÜüÖöß Ăáé A Test Line. Special chars: ÄäÜüÖöß Ăá A Test Line. Special chars: ÄäÜüÖöß Ă A Test Line. Special chars: ÄäÜüÖöß A Test Line. Special chars: ÄäÜüÖöß A Test Line. Special chars: ÄäÜüÖö A Test Line. Special chars: ÄäÜüÖ A Test Line. Special chars: ÄäÜü A Test Line. Special chars: ÄäÜ A Test Line. Special chars: Ää A Test Line. Special chars: Ă„ A Test Line. Special chars: A Test Line. Special chars: A Test Line. Special chars A Test Line. Special char A Test Line. Special cha A Test Line. Special ch A Test Line. Special c A Test Line. Special A Test Line. Special A Test Line. Specia A Test Line. Speci A Test Line. Spec A Test Line. Spe A Test Line. Sp A Test Line. S A Test Line. A Test Line. A Test Line A Test Lin A Test Li A Test L A Test A Test A Tes A Te A T A A libcommons-io-java-2.4.orig/src/test/resources/org/0000755000175000017500000000000011765740035021713 5ustar ebourgebourglibcommons-io-java-2.4.orig/src/test/resources/org/apache/0000755000175000017500000000000011765740035023134 5ustar ebourgebourglibcommons-io-java-2.4.orig/src/test/resources/org/apache/commons/0000755000175000017500000000000011765740035024607 5ustar ebourgebourglibcommons-io-java-2.4.orig/src/test/resources/org/apache/commons/io/0000755000175000017500000000000012125050425025202 5ustar ebourgebourglibcommons-io-java-2.4.orig/src/test/resources/org/apache/commons/io/FileUtilsTestDataLF.dat0000644000175000017500000000000612125050425031444 0ustar ebourgebourg1 2 3 libcommons-io-java-2.4.orig/src/test/resources/org/apache/commons/io/FileUtilsTestDataCRLF.dat0000644000175000017500000000000612125050425031671 0ustar ebourgebourg1 2 3 libcommons-io-java-2.4.orig/src/test/resources/org/apache/commons/io/FileUtilsTestDataCR.dat0000644000175000017500000000000512125050425031446 0ustar ebourgebourg1 2 3libcommons-io-java-2.4.orig/src/test/resources/org/apache/commons/io/testfileBOM.xml0000644000175000017500000001536312125050425030111 0ustar ebourgebourg Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, At accusam aliquyam diam diam dolore dolores duo eirmod eos erat, et nonumy sed tempor et et invidunt justo labore Stet clita ea et gubergren, kasd magna no rebum. sanctus sea sed takimata ut vero voluptua. est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat. Consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo libcommons-io-java-2.4.orig/src/test/resources/org/apache/commons/io/testfileNoBOM.xml0000644000175000017500000001536012125050425030403 0ustar ebourgebourg Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, At accusam aliquyam diam diam dolore dolores duo eirmod eos erat, et nonumy sed tempor et et invidunt justo labore Stet clita ea et gubergren, kasd magna no rebum. sanctus sea sed takimata ut vero voluptua. est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat. Consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo libcommons-io-java-2.4.orig/src/test/resources/test-file-utf8-cr-only.bin0000644000175000017500000000325012125050425025743 0ustar ebourgebourgA Test Line. Special chars: ÄäÜüÖöß Ăáéíïçñ ©µ¥£±²® A Test Line. Special chars: ÄäÜüÖöß Ăáéíïçñ ©µ¥£±² A Test Line. Special chars: ÄäÜüÖöß Ăáéíïçñ ©µ¥£± A Test Line. Special chars: ÄäÜüÖöß Ăáéíïçñ ©µ¥£ A Test Line. Special chars: ÄäÜüÖöß Ăáéíïçñ ©µ¥ A Test Line. Special chars: ÄäÜüÖöß Ăáéíïçñ ©µ A Test Line. Special chars: ÄäÜüÖöß Ăáéíïçñ © A Test Line. Special chars: ÄäÜüÖöß Ăáéíïçñ A Test Line. Special chars: ÄäÜüÖöß Ăáéíïçñ A Test Line. Special chars: ÄäÜüÖöß Ăáéíïçñ A Test Line. Special chars: ÄäÜüÖöß Ăáéíïç A Test Line. Special chars: ÄäÜüÖöß Ăáéíï A Test Line. Special chars: ÄäÜüÖöß Ăáéí A Test Line. Special chars: ÄäÜüÖöß Ăáé A Test Line. Special chars: ÄäÜüÖöß Ăá A Test Line. Special chars: ÄäÜüÖöß Ă A Test Line. Special chars: ÄäÜüÖöß A Test Line. Special chars: ÄäÜüÖöß A Test Line. Special chars: ÄäÜüÖö A Test Line. Special chars: ÄäÜüÖ A Test Line. Special chars: ÄäÜü A Test Line. Special chars: ÄäÜ A Test Line. Special chars: Ää A Test Line. Special chars: Ă„ A Test Line. Special chars: A Test Line. Special chars: A Test Line. Special chars A Test Line. Special char A Test Line. Special cha A Test Line. Special ch A Test Line. Special c A Test Line. Special A Test Line. Special A Test Line. Specia A Test Line. Speci A Test Line. Spec A Test Line. Spe A Test Line. Sp A Test Line. S A Test Line. A Test Line. A Test Line A Test Lin A Test Li A Test L A Test A Test A Tes A Te A T A Alibcommons-io-java-2.4.orig/src/test/resources/test-file-utf16le.bin0000644000175000017500000000545412125050425024772 0ustar ebourgebourgA Test Line. Special chars: ÄäÜüÖöß Ăáéíďçń ©µĄŁ±˛® A Test Line. Special chars: ÄäÜüÖöß Ăáéíďçń ©µĄŁ±˛ A Test Line. Special chars: ÄäÜüÖöß Ăáéíďçń ©µĄŁ± A Test Line. Special chars: ÄäÜüÖöß Ăáéíďçń ©µĄŁ A Test Line. Special chars: ÄäÜüÖöß Ăáéíďçń ©µĄ A Test Line. Special chars: ÄäÜüÖöß Ăáéíďçń ©µ A Test Line. Special chars: ÄäÜüÖöß Ăáéíďçń © A Test Line. Special chars: ÄäÜüÖöß Ăáéíďçń A Test Line. Special chars: ÄäÜüÖöß Ăáéíďçń A Test Line. Special chars: ÄäÜüÖöß Ăáéíďçń A Test Line. Special chars: ÄäÜüÖöß Ăáéíďç A Test Line. Special chars: ÄäÜüÖöß Ăáéíď A Test Line. Special chars: ÄäÜüÖöß Ăáéí A Test Line. Special chars: ÄäÜüÖöß Ăáé A Test Line. Special chars: ÄäÜüÖöß Ăá A Test Line. Special chars: ÄäÜüÖöß Ă A Test Line. Special chars: ÄäÜüÖöß A Test Line. Special chars: ÄäÜüÖöß A Test Line. Special chars: ÄäÜüÖö A Test Line. Special chars: ÄäÜüÖ A Test Line. Special chars: ÄäÜü A Test Line. Special chars: ÄäÜ A Test Line. Special chars: Ää A Test Line. Special chars: Ä A Test Line. Special chars: A Test Line. Special chars: A Test Line. Special chars A Test Line. Special char A Test Line. Special cha A Test Line. Special ch A Test Line. Special c A Test Line. Special A Test Line. Special A Test Line. Specia A Test Line. Speci A Test Line. Spec A Test Line. Spe A Test Line. Sp A Test Line. S A Test Line. A Test Line. A Test Line A Test Lin A Test Li A Test L A Test A Test A Tes A Te A T A A libcommons-io-java-2.4.orig/src/test/resources/test-file-utf16be.bin0000644000175000017500000000545412125050425024760 0ustar ebourgebourgA Test Line. Special chars: ÄäÜüÖöß Ăáéíďçń ©µĄŁ±˛® A Test Line. Special chars: ÄäÜüÖöß Ăáéíďçń ©µĄŁ±˛ A Test Line. Special chars: ÄäÜüÖöß Ăáéíďçń ©µĄŁ± A Test Line. Special chars: ÄäÜüÖöß Ăáéíďçń ©µĄŁ A Test Line. Special chars: ÄäÜüÖöß Ăáéíďçń ©µĄ A Test Line. Special chars: ÄäÜüÖöß Ăáéíďçń ©µ A Test Line. Special chars: ÄäÜüÖöß Ăáéíďçń © A Test Line. Special chars: ÄäÜüÖöß Ăáéíďçń A Test Line. Special chars: ÄäÜüÖöß Ăáéíďçń A Test Line. Special chars: ÄäÜüÖöß Ăáéíďçń A Test Line. Special chars: ÄäÜüÖöß Ăáéíďç A Test Line. Special chars: ÄäÜüÖöß Ăáéíď A Test Line. Special chars: ÄäÜüÖöß Ăáéí A Test Line. Special chars: ÄäÜüÖöß Ăáé A Test Line. Special chars: ÄäÜüÖöß Ăá A Test Line. Special chars: ÄäÜüÖöß Ă A Test Line. Special chars: ÄäÜüÖöß A Test Line. Special chars: ÄäÜüÖöß A Test Line. Special chars: ÄäÜüÖö A Test Line. Special chars: ÄäÜüÖ A Test Line. Special chars: ÄäÜü A Test Line. Special chars: ÄäÜ A Test Line. Special chars: Ää A Test Line. Special chars: Ä A Test Line. Special chars: A Test Line. Special chars: A Test Line. Special chars A Test Line. Special char A Test Line. Special cha A Test Line. Special ch A Test Line. Special c A Test Line. Special A Test Line. Special A Test Line. Specia A Test Line. Speci A Test Line. Spec A Test Line. Spe A Test Line. Sp A Test Line. S A Test Line. A Test Line. A Test Line A Test Lin A Test Li A Test L A Test A Test A Tes A Te A T A A libcommons-io-java-2.4.orig/src/test/resources/test-file-shiftjis.bin0000644000175000017500000000006512125050425025320 0ustar ebourgebourgHiragana letters: ‚ź‚ ‚ˇ‚˘‚Ł Kanji letters: –ľ—AŽq‹ž libcommons-io-java-2.4.orig/src/media/0000755000175000017500000000000012125050425017176 5ustar ebourgebourglibcommons-io-java-2.4.orig/src/media/logo.gif0000644000175000017500000001047112125050425020630 0ustar ebourgebourgGIF89aťg÷  !!!"""###$$$%%%'''((())),,,...000111222333444555777888:::;;;<<<===>>>???@@@AAABBBCCCDDDEEEFFFGGGHHHIIIJJJKKKLLLMMMNNNOOOPPPQQQRRRSSSTTTUUUVVVWWWXXXZZZ[[[\\\]]]^^^___```aaabbbcccdddeeefffhhhjjjkkklllmmmnnnoooppprrrssstttuuuvvvwwwxxxyyyzzz{{{|||}}}~~~€€€‚‚‚„„„………†††‡‡‡‰‰‰ŠŠŠ‹‹‹ŽŽŽŹŹŹ‘‘‘’’’“““”””•••–––———™™™ššš›››śśśźźź   ˇˇˇ˘˘˘ŁŁŁ¤¤¤ĄĄĄ¦¦¦§§§¨¨¨©©©ŞŞŞ«««¬¬¬­­­ŻŻŻ°°°±±±˛˛˛łłł´´´µµµ¶¶¶···şşş»»»˝˝˝ľľľżżżŔŔŔÁÁÁĂĂĂÄÄÄĹĹĹĆĆĆÇÇÇČČČÉÉÉĘĘĘËËËĚĚĚÍÍÍÎÎÎĎĎĎĐĐĐŃŃŃŇŇŇÓÓÓÔÔÔŐŐŐÖÖÖ×××ŘŘŘŮŮŮÚÚÚŰŰŰÜÜÜÝÝÝŢŢŢßßßŕŕŕáááâââäääĺĺĺćććçççčččéééęęęëëëěěěíííîîîďďďđđđńńńňňňóóóôôôőőőööö÷÷÷řřřůůůúúúűűűüüüýýýţţţ˙˙˙!ů é,ťgţÓ N@‹%Zz€@°!A0´°SäĂ‹éśŔ±‚Ć)r´€Ńá‡4^4PÂFŚ%ž°˘†  1 h9D€N8Ů!ć=ÓĐ)UĘLL‚’Č8[Şt'S`ĂFˇĂ#mKĎ˝šňS`Sĺ––[EĂa,l` )FµŮ’9,şF5YH!FťąT2Řúb jT‘ÁAp˛ĄćA¸(CšRpĽfA[şlÄE µ–KU‹›Ňrb˛P:ĹŰŇnTK9ĐH-¸°\ţB·ÇÖRoć–B«‘I¶ŰTMQnČ ÔŇcŞbY[ęGAJ˝ţD[ęz©0 Ł,ĺ«ôTŮA¡sf…€űřC÷ +Á É CÎÜ€Dč˘TÍf:¦đ€čđŠR˘,bŘ!' NN9ţ 4\rĐpA ¤ŔGZŮp±ß,G(€4H˘” )@‹R‘Ś`ŕ7¬˘T%ď÷ -IŘ×@ }¤Ą‹wa€ :°|pŁ%J5A `Ů2dŇP :Ć0P­ Ó dh%J=1čü'8–{BŔ :“0Đpčłbś<śłT&ěi:Ţ,@Đ$†a±ç}y(Ç@J˘ĂI{fˇ”†¦C…Rx@R˙‰¤šÎ)óU``Cá(©rˇd64€*čLÓ€@ň2Ŕ­YđŤR‹;čd٦‰J±Ŕ¬@x˘5 l›i*Jµ!í@ř))iMâ 0 :ť¤ę:Ô0Ű `¤mâ$"yŔ ¤< Éťa¨fÜwťčŔ`qC(BŞĂéâđJâđ(čČ‘*±Â,+kC<§ˇJ"â°č“*Îč`đr°| sM¤/;D¦@lŚ­ŻL¬Ô Jd:ç,‹Ń•Pc;sŃŤ TQ$:3§AZsMĐ!č@ó“’V„-č`c1şč´b»ţ·˛‚ŻÜ¸ř…a6Ş=Đč€sź(ľ:ÜžŽŔbëŕ8Š„ál Ў>(u‚ä9ÁęJŞö T[ťŽu”*Ă{6éM= îéXˇ8¨%FMĚ'ą‘c€ŚN†§#ꆛjË}U(ő@óÍ ” ¨Ł'F+(%AŞäń›RĘhÁĐ@Â;AťFĂ»ďč„ë †OŚä¨ ă†ň+‰|4†ß ă>XP ˝r"Ą¤ {20\řĐ?vMŕ ĎX (®•Y ăŘst€¶ÁM‹SŠ­‡ŽađĎĘ«ŃńĂůÎ…‚RHB&(ĺÝţ‹•RAľ AÇ’ă… 4PJBX Ą+ĽHńp‘ţý[2Ä|jXŔŢ'ŽâB dÜGIBąvź<'©Ň!:P“,‚?!Ŕv2=isP˛Ĺ~1Ă ăEĆhC3*5¸Ŕž¶#7*%Ž™ ţR€DL‡[“:G ˛‹D1 $*8d˘Ăđ $¨"4 §ČüY˛‹0có(YF.*A)]h^!Đ!Žx t(pŃ5†±Ź@p–R(ŕ"$8żče(řŐ€ÁE0)t<Áb˝d!/âĹ“†•ä˙bŞŽ#`Ä ž˛‡HÁíçrAŮ<Ó1BtđBďqÎä čÉ*gÇ63ř —§ }ąĐ†ÔS3$ăEn¸1ć…ČAH° ĄpBý$A+ČFq@A hč˘Ć…q(ĺĄŕD-pC©)FM„,6 c,eŘX<µřKz’č¤CąŇ®¦c®PĘ9lÁ‰Nôb)Ž ZĽt*Ç‚¦ăDG/‡JŇ>xčŘF Î˙č'*`Pz6‡$B _ľ‘© }Í35đâŽ{ĽÁ ůČE]ňţŇÁĐŁhśvcrźáLyŽÖElž'ś“'1®îyL:`›6“Ł py‘gs Ľ!LG ¦,ŕś+…mѵÔKÂĄ6[cC70Ş“gYp-ěčŮlöłĎ@í_ž6 Ĺfa°Á ňčŔfp‚V`ńeP*2858ţW8;ŘKPfÚ`@ařev`„mćIKČ„?POH_¨  ¶*_v†1gŹ„eHâ1†1e†h8he–I†r„E č‡rH‡a‡)˙_6{¸`Pfňó‡†& ÜFr(‡x‚é€2_ÖUa`T^ć F6 @f‰T1EбPfŤ3f)čdU#‰‘F‰J(iă@ńŠÂPfň7f­ôeH~ťf ćć…ťv;ńŠVőeŁ3fËPf €‹‘v Đ’}óŠĹče8đ‰özNVĄ(iĹ †˘ŠKaYőŤš ećäč` …éhhëx+-Żh e÷Ř` PfͰŹyF ě*îyâňŠ~ňeJ'd8Pf®Ŕl6 '+ިwóŠóeËp o^ ůeĂP Qc‰cç0˙Żřlf(©`łPfsĐ’W& 0Y4„¨'łőŠôeĽdgSfMŕ“M >#7qH”’óŠP^ 9i`¦SfŐ†_ @8eR¤óŠłÂfp·bňen¤…^ö ř#9_Řq÷‹šČŚą•~_Ć’pédľ0—Íł„Cő_hém=ćAe,idů^ţ§wéŠyÖöeľđM¦G_Ć …–FĆ ‹Bég€†–é°m |YW_f J“¦™|Ôw—™‰ŮWŐÔfY€ađQe·id»pš|WdYč}C–—Alö ëfaxČfŔʎ{˙ş0&—zuĐ›Ášéŕ—eÖ 9HabgZ5¤— ŞĹ‚“דĐůŚŇ™€qlFU ađyö ň2x'ź÷©—Jˇ2hžé°†ćü×_ Ŕ z7ŁG· Ş pСřů›9ń ‡Ć ćŰ×fł€SŞ ˘9÷ ˘töD# zvŤŕö”@xmćurcsµ<r˙Ó*c iŘ@5Đ…:1„€Łz†ÓqE:Łé lŔĄ4hg¶OžÖ € (@s-†JŕIi° W5G ׳‡Ir"Ú_ŕYµć Ĺ iQkÖ°[ĹU§9Ů˙aŠi,čU7n©ö Ź…=š^ě–źaꨒV›Ă;±Y©y`]¤šÚuY¦q¶¤‘WŞeFR€Ş©j©S©®zeâ˛:«ˇ*`đŰ‘«NÖ ˛÷©B¦Şµę¸@¬F– „ůlÁG«1ĐŞÄę kŕ2ČJeĘZŕü™«ĄĐy“Ziß ®˙樷Zä)­bH­ŕ—qm®ńx®­–®űĹ'= ŰP¦|]˝úl Đ\Đű°ë°×Ca’Cŕµ€«şĘ sPÜęŻňj_YG±â1@t0 Ł  łŕ ·Ŕ Ł@ t -pŤ{"Ż&˛ńú`:k_8űł9«ł@;;libcommons-io-java-2.4.orig/src/media/io-logo-white.xcf0000644000175000017500000004740712125050425022377 0ustar ebourgebourggimp xcf filećZBBLK gimp-commentCreated with The GIMPgimp-image-grid(style solid) (fgcolor (color-rgba 0.000000 0.000000 0.000000 1.000000)) (bgcolor (color-rgba 1.000000 1.000000 1.000000 1.000000)) (xspacing 10.000000) (yspacing 10.000000) (spacing-unit inches) (xoffset 0.000000) (yoffset 0.000000) (offset-unit inches) Ć0<Ý$M( TM˙     ŇHL8gimp-text-layer(text "TM") (font "Sans") (font-size 8.000000) (font-size-unit pixels) (hinting yes) (antialias yes) (language "en-us") (base-direction ltr) (color (color-rgb 0.000000 0.000000 0.000000)) (justify left) (box-mode fixed) (box-width 12.000000) (box-height 11.000000) (box-unit pixels) ­ Á Ń„„„#°öɰĄ-É>ÉöČ8ÂxˇĐöČ8€˛8wČöČ8€PŰČöČ8€?ČúČ8€ţČ+ Text Layer˙     Ş-J×+ë+ű   ţU Uţ8 űqŞâ˙˙űâŞqűUqĆ˙˙űâqU8ůŤ˙˙ĆqUUůŞâ˙˙ŤţĆ˙˙ţ úq˙˙â8úq˙˙â8ţU˙˙ţĆ űŞ˙˙Şúâ˙˙UţU˙˙ţŞűŞ˙˙â ţU˙˙ţUţU˙˙ţŞţq˙˙ţ8 ţŤ˙˙ţ8ţU˙˙ţŞţ8˙˙ţĆ ţ˙˙ţâţU˙˙ţŞţĆ˙˙ţU ţĆ˙˙ţqţU˙˙ţŞţ8˙˙ţq˙˙ţâţU˙˙ţŞţŤ˙˙ţĆţ8˙˙ţ8ţU˙˙ţŞţâ˙˙ţŞ˙ţŤţU˙˙ţŞ˙ţqţâ˙˙ţŞţU˙˙ţŞţU˙˙ţUţŞ˙˙ţU˙˙ţŞţU˙˙ţUţŞ˙˙ţU˙˙ţŞţU˙˙ţUţŞ˙˙ţU˙˙ţŞţU˙˙ţUţŞ˙˙ţU˙˙ţŞţU˙˙ţUţŞ˙˙ţU˙˙ţŞ˙ţqţŞ˙˙ţŞţU˙˙ţŞ˙ţŞţâ˙˙ţŤţU˙˙ţŞţŞ˙˙ţĆ˙ţUţU˙˙ţŞţU˙˙ţ8˙˙ţâţU˙˙ţŞţâ˙˙ţU ţq˙˙ţŤţU˙˙ţŞţq˙˙ţĆ űâ˙˙âţU˙˙ţŞţĆ˙˙ţ8 ţU˙˙ţUţU˙˙ţŞúâ˙˙Ć úâ˙˙ŤţU˙˙ţŞúâ˙˙Ş űŞ˙˙ŞţŞ˙˙ţâ úâ˙˙Şúâ˙˙qţq˙˙ýŞ8 ůŤ˙˙âq8ůUŤ˙˙Ć8ţ8Ş ŞţqüŤâ˙˙ýŞ8!Uţ I<Drop-Shadow#2Ě     Ł&KćI<ţŃI< ˛P  ďö ÷  ú ů   ô  ě  ö ň ë   ÷ ń é öđ ŕ !#$#" đ â #'*++)&#  !!"ń!  á $).1220-*&"  "$%&&%ţ$%%ţ&''ň&%" â #)/48::850,(%$#$%')*++ü*)(''ü()+,,ó+)&" Ć &-4:>@@>;62.+))*,-/010/.,*)(()*,.01210-)$ Ű !)19?DFFD@<84100134676530-+)((í*-0357763/*$ Ć #+4<;<>@ABA?<73.*&%$%(,16:>AA@<71*" Ć %.8AHNQRPMIEBAABDFGGFB>82-($""#&*06>?ADEFEC?;50+'%$%'*/48;989;=?AA@=951-)'&'),/379;;961+$ Ć "*2:@EHHFB>96323479:;;9740-*)((*,/146653/+% Ć '/6<@BB@<840-,,-/2456531/-+)()*+-/011/-)$ Ű $+16:<<:73.+(&&')+-/00/.-+)((ü)*+,,ó+)&# á  &,045530,(%" !"$&()**ü)('&&'ň&%#  â !%),--,)&"!#$%%ţ$##"#"ň! ę #%&&$"ő đ ó ďđ ë   ř ń Ţ   ń  í ů  ţ  ň  đ ú  ÷űü  Ntţţýüüűűűúú ú ú ů ů ů ů ů ů ů ů ů ů ú ú úúűűüüýţ…$×commons˙     ם#í#ů׹ľĽ"c€€€ý8qŞŞüŤUý8UŞŞýq8üq8ýqâ˙˙ýŞ ýqâ˙˙ü⍠úUŞ˙˙Uő8â˙˙Ť8Ş˙˙ţUôUâ˙˙Ť8qâ˙˙ţUüqŞ˙˙ţUúU˙˙ĆţĆ˙˙ţUţq˙˙ţUţŞ˙˙ţŞüŤŞŞ˙˙üUĆűU˙˙âţq˙˙ţâţU˙˙ţUţŞ˙˙ţŞţq˙˙ůŞ˙Ć8˙˙ţţ˙˙ţUţ8˙˙ţĆ ţâ˙˙ţU˙ţŞűâ˙˙ŤţĆ˙˙ţţĆ˙˙ţU ţ8˙˙ţâ˙ţĆţq˙˙ţ8úâ˙˙Uţ8˙˙ ţâ˙˙ţq˙ţŞţĆ˙˙ ţţŞ˙˙ţĆ ţŤ˙˙ţĆ˙űŞ˙˙ţĆ˙ţŞ ţ8˙˙˙űŞU˙˙ţŞţ˙˙ţŞ ˙ţ8˙űŞŤ˙˙ţŞţU˙˙ţŞ ţâ˙˙ţU˙űŞŞ˙˙ţŞţU˙˙ţŞ ţŞ˙˙ţU˙űŞŞ˙˙ţâţU˙˙ ţŞ˙˙ţU˙űŞŞ˙˙ţU˙˙ ţŞ˙˙ţ8˙űŞŞ˙˙ţU˙ţU ţŞ˙˙˙űŞU˙˙ţĆ ţ8ţâ˙˙ţŤ ţŞ˙˙ţĆ˙űŞ8˙˙ţ8 ýUâţŤ˙˙ţĆ ˙ţq˙ţŞţâ˙˙ýâ ü8˙8ţ8˙˙ţ8 ţ˙˙ţ˙ţŞţq˙˙ýŞü8âĆţĆ˙˙ţŤ ţq˙˙ţŤ˙ţŞţâ˙˙ýâ8űq˙˙ţ˙˙ţűâ˙˙â˙ţŞţU˙˙ýâŤUUúŤâ˙˙UţU˙˙ţĆúq˙˙â˙ţŞţU˙ ˙ţUţU˙˙ţŞúU˙˙âţ˙˙ţŞţU˙ ˙ýâU ý8â˙˙ôâqUĆ˙˙Ćţq˙˙ţýĆ˙˙ýŤ ýqâ˙˙ýĆ8üUqĆ˙˙ýâŞýUŞŞýŤUý8qŞŞýU Ş€€€ů8qŞŞŤ8ůUŤŞŞŤ8 ý8ŤůUŤŞŞqůUŞ8Ć˙˙ýĆýqâ˙˙ýĆúqĆ˙˙ýqâ˙˙ţŤýŤ˙˙ţŤ˙˙ţĆý8â˙˙ţâü8ŤĆ˙˙ýĆ˙˙ţqţq˙˙úâŤUUŤ˙˙ůqU˙˙ŞUUýŤâ˙˙ţqüĆŞĆ˙˙öUâ˙ĆqUUĆ˙˙ůŞ˙âŤUUţ8ţ˙˙úâU˙Şýâ˙˙ţâţĆ˙˙űŞ˙Ťţq˙˙űŤŞ˙q ţŤ˙˙ţŞţq˙˙ţ8ţU˙˙ţUţâ˙˙ţU ţ8˙˙ţĆţ8˙˙ţUţU˙˙ţqţŤ˙˙ţq ˙ţŞ˙ţŞţU˙˙ţUţU˙˙ţU ˙ţŞ˙ţŞţU˙˙ţUţU˙˙ţU ˙ţŞ˙ţŞţU˙˙ţUţU˙˙ţU ˙ţŞ˙ţŞţU˙˙ţUţU˙˙ţU ˙ţŞ˙ţŞţU˙˙ţUţU˙˙ţU ˙ţŞ˙ţŞţU˙˙ţUţU˙˙ţU ˙ţŞ˙ţŞţU˙˙ţUţU˙˙ţU ˙ţŞ˙ţŞţU˙˙ţUţU˙˙ţU ˙ţŞ˙ţŞţU˙˙ţUţU˙˙ţU ˙ţŞ˙ţŞţU˙˙ţUţU˙˙ţU ˙ţŞ˙ţŞţU˙˙ţUţU˙˙ţU ˙ţŞ˙ţŞţU˙˙ţUţU˙˙ţU ˙ţŞ˙ţŞţU˙˙ţUţU˙˙ţU ˙ţŞ˙ţŞţU˙˙ţUţU˙˙ţU ˙ţŞ˙ţŞţU˙˙ţUţU˙˙ţU ţ˙˙ţâ˙ţĆţq˙˙ţUţq˙˙ţŤ ţq˙˙ţUţq˙˙ţţĆ˙˙ţĆţĆ˙˙ýâřU8qĆ˙˙÷ŞU88qĆ˙˙÷âŤU8UŤâ˙˙üĆŤUüUŤâ˙˙óâŤUUŞ8qŞ ŞűqqŞ Şýq8Ş Ş Şü8Ş€€€ŞýqüUŤŞŞýŤUü8Ť8ýqŞŞţU˙ţŤ ý8Ć˙˙ýŞ8 ő8Ťâ˙˙UŤ˙˙ýâU˙ţŤ ůĆ˙˙ĆUýUĆ˙˙ţŞüUŞâ˙˙űU8â˙˙űUŞ˙˙ţú8â˙˙ŞţU˙˙ýâŞ˙Uř˙âŤUUŤâ˙˙ţâţU˙˙ţŤúâ˙˙ŞţU˙˙ýâţŞ˙˙űâ˙ŞţĆ˙˙ţUţĆ˙˙ţâţâ˙˙ţţŤ˙˙ţŞţU˙˙ţUţ8˙˙ţŞţŤ˙˙ţq˙˙ţŞ ţâ˙˙ţ8ţU˙˙ţqţâ˙˙ţâţU˙˙ţUţâ˙˙ţU ţŤ˙˙ţĆţU˙˙ţUţŞ˙˙ţU˙˙ţUţU˙˙ţ ţ8˙˙ţţU˙˙ţUţŞ˙˙ţU˙˙ţUţŞ˙˙ ţâ˙˙ţUţU˙˙ţUţŞ˙˙ţU˙˙ţUţĆ˙˙ ţŞ˙˙ţŤţU˙˙ţUţŞ˙˙ţU˙˙ţU˙ ţŤ˙˙ţŞţU˙˙ţUţŞ˙˙ţU˙˙ţU˙ ţU˙˙ţŞţU˙˙ţUţŞ˙˙ţU˙˙ţU˙ţU ţU˙˙ţŞţU˙˙ţUţŞ˙˙ţU˙˙ţU˙ţU ţU˙˙ţŤţU˙˙ţUţŞ˙˙ţU˙˙ţUţŞ˙˙ţŞ ţU˙˙ţUţU˙˙ţUţŞ˙˙ţU˙˙ţUţŤ˙˙ţâ ţU˙˙ţţU˙˙ţUţŞ˙˙ţU˙˙ţUţ8˙˙ţ ţŞ˙˙ţĆţU˙˙ţUţŞ˙˙ţU˙˙ţUţâ˙˙ţŤ ţĆ˙˙ţqţU˙˙ţUţŞ˙˙ţU˙˙ţUţq˙˙ţâ ţ˙˙ţâţU˙˙ţUţŞ˙˙ţU˙˙ţUţĆ˙˙ţqţŤ˙˙ţ8ţU˙˙ţUţŞ˙˙ţU˙˙ţUýâ˙˙ţţ˙˙ţUţU˙˙ţUţŞ˙˙ţU˙˙ţqýâ˙˙ýâúâ˙˙Uţq˙˙ţUţâ˙˙űĆ˙˙ţĆýŞ˙˙őŤ88Ť˙˙âUţâ˙˙ţĆţU˙˙üqŤâ˙˙űĆqUý8Ć˙˙ýâqü8qâ˙˙÷âŤUUŞ˙˙ Şţ8ýUŞŞýq8 ţqŞ Şţ8ŞŞVVV ýUŤŞŞúUŤ óŤ˙˙⪪Ć˙˙ŞĆ˙űĆ˙â8ý8Ć˙˙űŞ˙˙8üâ˙˙ű8˙˙Ćü8˙˙űŤ˙˙ŞýŞ˙űŞ˙˙âýU˙ţŞ˙˙ţqţ˙ţq˙˙ţqţ8ţ˙˙ýĆ8ţŤ˙˙ýĆ ţŞ˙˙ýŤ ţŤ˙˙ýâq ý8â˙˙ýâ ţq˙˙ýâU ýŤ˙˙ýâ ýŞ˙˙ţŤýŞqţU˙˙ţ⪠ţŤ˙˙ýŞ˙ţ˙˙üŞ˙q˙ţĆűŞ˙âţ˙˙ţqűŞ˙˙ŞűŤ˙˙ŞţŞ˙˙ýĆ8öŤ˙˙ŞĆqřŞĆŞŞ˙˙⪪˙ýâqŞţ8ý8ř8UŤŞŞŤUk 5ő8 Drop-ShadowĚ     ˙˙˙ú˙˙˙ú9$­ő8$ÉMMő8$ĺ/59âDąU  ţţţţ řúůů ô  í     ů  ň ÷ ř ř ×  řî ÷ôří  !#$%%÷$# ó!"##$%%ů$" Đ  "$&')*+,,+*'%"!#$&'())*+,,ú*(&#!é !$&(*+-.0122ç1.,)&#! !#$'(*+,--./02344ú31.,)×  #'),-/01346787642/,)(''(*,./11223ű568:;;ű9752ß !&*-/12334679:;<;9742/..č0245677665668:=?ABCB@=:đ "',024566Ů78:<=>>=;97544579;<==<:9878:>á=;:99:<>ABCCB@=;988:=@EIMOPONKâ &-38;==<:8655679;<=>==ĺ>@BEGIIHFC?;9779<@FKPSUVTRĹ $+29=@AA>;853223579:;<==?ADGKMOOMJE@;7556:?EKQVZ[ZXé  (08>CEED@<830..Ü024689;=@CGLPSTSQLGA;63237=CKRX\__]Ă $,5=CGJIGB=72.+))*,.1369<@EJOTWXWTOHA:40/04:AJRY^abač '09AHLNMID>71+(%%Ý'),/26:@FLRW[\[WQIA93.,-17?HQY_cddĂ  )3=ELPRPLF?70*%"!!"$'*.38?FMTZ^_^YSJA92-*+/5=FOX_dfeĂ ",6@HOTUSOIA81*$!!#'+06>ENU\`a`[TKB91,))-3;DNW^cffĂ #-8BKSWYWRLC;2+% !$(.55-'" #'-471,)&%&'*.3:AJRZ_bc`ZSJA93/-/28@HOUY[[Ă !+6ALV]bdd`[TME>83/,*)*+.38?GOV\`a_ZTLC<610149@FMRUWWă (3>IS[aeec_ZSLE?:52/--â/27=DKRX\]\YSME>94336:?EJOQRRĂ %/:EOX_ceeb^XRLFA<741/./149?FMSWYYWSMF@;7557;?CGKLMLĹ !+5@JS[`dec`\WQLFA<741/./15:@FLQTUSPLGB=9778;>ADFGGFĎ &0:DMU\`bba]YTOID?:51.-,.04:?EJMOOMJFA=:88÷:<>@AA@?Ä !*3=FNUZ]_^\YUPJE?:50-*))+.27=AEHIHFC@=:87789:;;:98Đ $-5>FMRVYYXVRNIC>83.*'%$%(+059=@BBA?=:8755ü421Ĺ &-5=DINPRQPMID?:4/*%" !$(,048:;;:875321100/.,+*Ř %,3:?CFHIHEB>94/*%! $(,/133ň10/.-,+*('%$#Ö $*059<>?><:62.)$  #&)+,,ň+*)('&%#" Č !&+.134431.*&"!#$%%$$#"! É !$')**)'%" ň   ő ö ö Ú   ő ô é   ö  ö  ÷ ř řů "    ţü      ú  ô      ř ř   ë  üř  ÷ ó űöř  öî !!ű"#$$%%ű$#"!  !ţ"##ř!ö !!đ"#$%!$&'))*ű+,-.//ő.-,*))()*+,,ě*(%!"$&())**ú+,-.÷ #&*-/12334ü57899ú8764211ü23455í31-*&" #'*-01233í4567'%%&(+/369;<==<<ó=>@ACCDCB@><::ý;=>>ě=:62.)&$$%'+/37:;<=<<ń=>@/--.037<@CEFFţEDDűFGIKMMŢKIGECAABCDFGFEC?:51-+*,.27<@CEFFEDDEFH86558;@DILNOOMLKJJLNPSUVVTROMJHGGIJLMNMKGB=841125:?DILNONMKJJKLN@>==?CHLQTVWVTRPOOPRUX[\]\YVSPMLLMOQSTTRNID?:778;@FKPTVVUSQOO€ĹQSHEDDFJNSX[]][YVSRQRUX\_aba_\XTQONOQTVXXWTPJE@=<=@EKQWZ\\ZXUSQQSVOLKJLOTY]`ba_\XUSRSUY^adfec_[VRPOPRUX[\[YUOJEA@ADJPV[_``^ZWTRRTWUSQPQTY]adedb^YURQRUY^bfhgea\WSONOQUY\^^\XSNHECDHMSY_bcb`\WTQQSV[XUU€;X\`dggfc^YTPOPSW]bfhhfb\WRNLMPTX\_`_[VQLHFGJOU\aded`[WRPOQT_\YXY[^bfhhfb]WRNLMPU[`ehhfb\VPLJKNRW\_a`]YSNJHHKPW]befd`[UPMLNRb_\[[]`dgiifb\UPKIJMRY_dggea[TNJHHKPU[_ba_ZUPKIJLQW]beec_YSNJIKOca^\\^adgiheaZTMIGGJPV]befd`YSLHEFINTZ_ab`\VQLJJMRX]beeb^WQKHGHLda_]]^adghhe`YRKGDEHMT[`dec^XQKFCDGLRY^ab`\WQMJJMRW]bdda\VOIFDFJda_]]^adghgd^XPJEBCFLRY_cdb]WPIDBBEKQX^aba]XRNKKMRW]adc`[UNHDBDHc`^\\^`cfgfc^WOICAAEJQX^bca\VOHCAADJPW]aba]XSNKKMRW]acc`ZTMFBABG`^\[[]_cegfc]VNHC@@DJQX^aba\UNHB@@DIPW]aba^YSOLLNRW]acc_ZSLFB@BF][YXY[^befeb\UNGB?@CIPW]ab`\UNGB@@CIPW]aba^YSOLLNRW\`cb_YRKEA@AEZXVVWY]`deea\UNGB?@CIPW]ab`[UNGB@@CIOW]aba^YTOLLNRW\`bb_YRKEA?AEUTRRTW[_bdda[UMGB?@CIPW\`a`[UNGB@@CIOV\`ba^YTOMLNRW\`ba^YRKEA?AEPONNPTX]acb_[TMFB?@CHOV\_`_ZTMGB@@CHOV\`a`]YTPMMNRW\_a`]XQJEA?AEJIIJLPUZ^``^YSLFA??CHNU[^_^YTMGB@@CHNU[_`_\XSOMLNRV[^`_\WQJD@?ADD€2EHMRW[^^\WQKEA>?BGMSY\]\XRLFA??BGMSY]^][WRNLLMQUY]^]ZUOIC@>@D>=>@CHMSWZZXTNHC?==@EKQVYZXUOJD@>>AEKQVY[ZXTPLJIKNRVY[ZWRLFA>=>B778:>CHNRUUTPKE@=;;>BHMRUVTQLGB><<>CHMRUWVTPLIGGHKOSUVVSOID?<;CHLOPNKGB>:88;>CHLOPPNKHECCDFJMOPPMID?;878;))+.27BFHIHEA=96446:>BFHJIGEB?>>?ADGIIÂGC?:64347"#$'+059=?@?<952/..037;>@A@>:731//147;>@AA@=;9878:=?AAí?<841/./1!$(-1466×41.+)((*,/2578752/,*))*-035788753100134688Č630-*)()+!%(+-.-+)'$#""#%(*-./.,*(%$##$&(+-.//.-+*))ü+,.//ú-+)&$""î$!#$%$#! ë #$%&%$" !#$&&ő%$#"!!"#$%&&ú%#!î óű÷úő őűűî ü  ű ő ű  ó                ő ü 9 ţ,  ú   ô ű üţţ     ů ÷  ţ  ů ÷ üţö ő ú  é ö  ő ůő%%ű$#"!  ü!""##ö"   óë !"#//ő.,+*)(()*+,,ç+)&# !"#$%%ů$#!ô"$')+,,899ő875321122455Ç42/+'" "$%&'()*+,--,+*(&#"!!"$'*.13566BCDCCA?=;::ü;<=>>ĺ<84/*&" "%')*+,-./012344Ę20.,*))*-037;=?@@JLMMLKIFDBAABCEFGFDA=83.)&%%&(*,.01122Ă34689;<<;975321358=AEGIJJQSUVUTQNLIHGHIKMNNLJE@;61.,,-/2456766č5679<>ABCCB@><::;>AFJNQSSÚVY[\\[XUROMLLMORSTSQMHC>964468:;==<;988‰9;>BEHJKJIGECBCFINRVY[[ZZ]`bba^ZVRPNNPRUWYYWTOJEA><=>@ACCB@>;9889;?CHLOQQPOMKJKMQUY]`aa_[_cefeb^YUQOOQSWZ\]\ZVQLHFDEFGII€ůGD@=9778;?DIOSVWWVTRQRTW[_cefebZ_dghgd`ZUQONPSV[^``^[WSOMLLMOPONKGB=86458=CIPUZ\]\ZYWWY\_cghigdY^cghhe`ZUPMLNQUZ^acb_\XUSRSTUVURNIC=74236;AIPW\`aa`^\\]`cfikjhdW]bfhhe`ZTOKJLOTY_bdec`][YXYZ[[ZVQJC<61/028?GOW^bdedb``acehklkhcT[`eggd_XRMIHIMRX^cfgfda_^^€=`a`^ZTLD<50--055.*(*.5>HQZaeggfeddegijjhc]LSZ_bb_ZSLFA@AFLS[bgijjhggÂijkkid]TJ@70+)+/5>GPX_ceedcbbdfhiigb\LSY_bb_YSLEA@AELS[afijihffĺhijjid^ULB92-+,/5=FNV\`bba``Ăbdghhfb\KRY^aa^YRKEA?AEKSZafhihfeddeghigd^VMD<50-.16=EMTY]^^]]…^`ceggea[KRY^aa^YRKEA@AEKSZ`eghfdbaabdefeb^WOF>830037=DKQVXZYYXYZ]`cefd`ZKQX]``]XRKEA@AEKRY_dffdb_^]^_abb`\WPHA:63358>CINRTTÂUWZ]addc_ZJQW\__\WQKEA@AEJQX^bcca^[YXYZ\]^]ZUOIC=86569=BGJMNONNĂPRVZ^aba^XIOUZ]]ZVPJDA?@DIPV[_``]ZWTSRSUWXXVSNIC>:878:=@DFHIHHŰJMRV[^_^[WGMRWYYWSMHB?>?BGMSX[\[XUQNLLěNPQRQOLGC?;9889;>@ABBAÂBDHLQVY[ZXSDJOSUUSOJE@=<=@DJOSVWVSOKHEDEFHIKKJGDA>;97789:;<<;::Ę<>BGLPTVVSO@EIMOOMJE@<989<@EIMPPOLHD@><<=?ABCCB@>;976556ý5433’57;@EJMOOMJ;?CGHIGD@;85457;?CFHIGDA=9654568:;<;:9754221100/.-,+,.049>BFHHFC48?@><-14677641.+*))+.13677530,)&%$$%'(*+,,Ú+*)('&%$"!  "&*.256764&)+-./.,)'%##é$&)+-..,*(%" "#$%%â$#"! #&),-.-+!#$%%˘#" !#$%%$" !#$%$#ä űýú  ű î ú ű   ţů ű   đ  ü      ţ  ú ô üţ   !   ×*   ţţ    ů÷÷ ú     öö ů ô ě ń ţ#$$%ě$" ń -.Ů-,)&"  678ö753/+'"ř!#$%&&ď%$#! @?ę@AA@?<84/*%" !#%(*,--í,+*(&# ýIHGGţHIIŮGEA<71,)&%&'*-/1344321/-*'# ýQPNNÖOPPOMJE?94/-,,.1479:;::8641.*&! ćWUSRRSTUVVTQLF@;632247;>@AAě?=;851-(# ü\YVUUÖWYZ[ZWRMGA<978:=ADFHHGEB?<840*% Đ_[XVUVX[]^^\XRLFA><=?BFJLNNMKHD@<72,'! Đ_[WUTUX[^`a_\VPJEB@ACGKNQSSRPMID@:5/(" Đ_ZVSRSVZ^aba^YTMHDCCFINRUWXWURNID>81*$ Ď^XSPOQTX]acc`\VPJFDEGKPTXZ\[YWSNHB<4-& Ď\VQNMNRV\`cca]WQKGEEGKPUY\^^][WSMG@91)" ĎZTNKJKOTZ_bcb^XRLGEDFJOTY]`aa_\XSLE=5-% ĎYRLIGIMSY^bcb^XRLGDCDHMRW\_bcb`\XRKC:1)  ÎWPJGFGLQX^bcb^XRKFBABEJOUZ^acdc`\WPH?6-$ ÎVOIEDFJPW]acb^XQKEA?@BFKQV[_bddc`[UMD;1( ÎUNHDCEJPV]acb^XQJD@==?CGMRW\`bdcb^XQH?5+" ÎUNHDCEIPV\acb^XQJD?<;;:;=@EINSX\_aa_[UMD:0& ÎTMGDCEIOV\`bb^XQJD>;99;>AEJNSW[]^]ZUNE;1( ÎSMGDCEIOU[`ba^XQJD>;98:<>BFJNRVYZZXSMD;1( ÎRLGCCDINUZ_a`]WQJD>;989::8789:@CFIJJIE@:2*" ÎJEA?>?CHMRUWVSOJD?;75445678:<>@BCCB?:4-& ęEA=;:BFHJIGC?;630/..č/0123455430,'" ę95311247;>@AA?<840.+*))*+ë,--..-+)%! ë1.,**+-025787630-*'%$$%&î'&%$! ü)'%$$đ&(*-./.-+(&#! đ é! !"$%&%$#!ń üńň őřó ţ  ů ů    ô ţ       ű  ţ  řz=,d Background˙     ˙˙˙˙MĎ,dMďNçNóN˙,dN#NANQNaNqNN§N·NÇN×˙˙˙ů˙űúô˙ţ˙:˙ý Ĺ˙˙˙˙˙˙˙˙˙˙˙˙˙ ˙ ˙ ˙ ˙ ˙ ˙ ˙&˙üţýü˙>˙ýţý˙>˙üţ˙ü˙Q˙ ˙ ˙ ˙ ˙ ˙ ˙ ˙ ˙ ˙ ˙ ˙ ˙0˙0˙0˙0˙–2K% libcommons-io-java-2.4.orig/src/main/0000755000175000017500000000000011765740035017057 5ustar ebourgebourglibcommons-io-java-2.4.orig/src/main/java/0000755000175000017500000000000011765740035020000 5ustar ebourgebourglibcommons-io-java-2.4.orig/src/main/java/org/0000755000175000017500000000000011765740035020567 5ustar ebourgebourglibcommons-io-java-2.4.orig/src/main/java/org/apache/0000755000175000017500000000000011765740035022010 5ustar ebourgebourglibcommons-io-java-2.4.orig/src/main/java/org/apache/commons/0000755000175000017500000000000011765740035023463 5ustar ebourgebourglibcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/0000755000175000017500000000000012125050425024056 5ustar ebourgebourglibcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/input/0000755000175000017500000000000012125050425025215 5ustar ebourgebourglibcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/input/DemuxInputStream.java0000644000175000017500000000446512125050425031347 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import java.io.IOException; import java.io.InputStream; /** * Data written to this stream is forwarded to a stream that has been associated * with this thread. * * @version $Id: DemuxInputStream.java 1302056 2012-03-18 03:03:38Z ggregory $ */ public class DemuxInputStream extends InputStream { private final InheritableThreadLocal m_streams = new InheritableThreadLocal(); /** * Bind the specified stream to the current thread. * * @param input the stream to bind * @return the InputStream that was previously active */ public InputStream bindStream( InputStream input ) { InputStream oldValue = m_streams.get(); m_streams.set( input ); return oldValue; } /** * Closes stream associated with current thread. * * @throws IOException if an error occurs */ @Override public void close() throws IOException { InputStream input = m_streams.get(); if( null != input ) { input.close(); } } /** * Read byte from stream associated with current thread. * * @return the byte read from stream * @throws IOException if an error occurs */ @Override public int read() throws IOException { InputStream input = m_streams.get(); if( null != input ) { return input.read(); } else { return -1; } } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/input/ClosedInputStream.java0000644000175000017500000000312312125050425031464 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import java.io.InputStream; /** * Closed input stream. This stream returns -1 to all attempts to read * something from the stream. *

* Typically uses of this class include testing for corner cases in methods * that accept input streams and acting as a sentinel value instead of a * {@code null} input stream. * * @version $Id: ClosedInputStream.java 1307459 2012-03-30 15:11:44Z ggregory $ * @since 1.4 */ public class ClosedInputStream extends InputStream { /** * A singleton. */ public static final ClosedInputStream CLOSED_INPUT_STREAM = new ClosedInputStream(); /** * Returns -1 to indicate that the stream is closed. * * @return always -1 */ @Override public int read() { return -1; } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/input/CharSequenceReader.java0000644000175000017500000001110612125050425031550 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import java.io.Reader; import java.io.Serializable; /** * {@link Reader} implementation that can read from String, StringBuffer, * StringBuilder or CharBuffer. *

* Note: Supports {@link #mark(int)} and {@link #reset()}. * * @version $Id: CharSequenceReader.java 1307461 2012-03-30 15:12:29Z ggregory $ * @since 1.4 */ public class CharSequenceReader extends Reader implements Serializable { private final CharSequence charSequence; private int idx; private int mark; /** * Construct a new instance with the specified character sequence. * * @param charSequence The character sequence, may be {@code null} */ public CharSequenceReader(CharSequence charSequence) { this.charSequence = charSequence != null ? charSequence : ""; } /** * Close resets the file back to the start and removes any marked position. */ @Override public void close() { idx = 0; mark = 0; } /** * Mark the current position. * * @param readAheadLimit ignored */ @Override public void mark(int readAheadLimit) { mark = idx; } /** * Mark is supported (returns true). * * @return {@code true} */ @Override public boolean markSupported() { return true; } /** * Read a single character. * * @return the next character from the character sequence * or -1 if the end has been reached. */ @Override public int read() { if (idx >= charSequence.length()) { return -1; } else { return charSequence.charAt(idx++); } } /** * Read the sepcified number of characters into the array. * * @param array The array to store the characters in * @param offset The starting position in the array to store * @param length The maximum number of characters to read * @return The number of characters read or -1 if there are * no more */ @Override public int read(char[] array, int offset, int length) { if (idx >= charSequence.length()) { return -1; } if (array == null) { throw new NullPointerException("Character array is missing"); } if (length < 0 || offset < 0 || offset + length > array.length) { throw new IndexOutOfBoundsException("Array Size=" + array.length + ", offset=" + offset + ", length=" + length); } int count = 0; for (int i = 0; i < length; i++) { int c = read(); if (c == -1) { return count; } array[offset + i] = (char)c; count++; } return count; } /** * Reset the reader to the last marked position (or the beginning if * mark has not been called). */ @Override public void reset() { idx = mark; } /** * Skip the specified number of characters. * * @param n The number of characters to skip * @return The actual number of characters skipped */ @Override public long skip(long n) { if (n < 0) { throw new IllegalArgumentException( "Number of characters to skip is less than zero: " + n); } if (idx >= charSequence.length()) { return -1; } int dest = (int)Math.min(charSequence.length(), idx + n); int count = dest - idx; idx = dest; return count; } /** * Return a String representation of the underlying * character sequence. * * @return The contents of the character sequence */ @Override public String toString() { return charSequence.toString(); } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/input/TailerListenerAdapter.java0000644000175000017500000000353112125050425032311 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; /** * {@link TailerListener} Adapter. * * @version $Id: TailerListenerAdapter.java 1304052 2012-03-22 20:55:29Z ggregory $ * @since 2.0 */ public class TailerListenerAdapter implements TailerListener { /** * The tailer will call this method during construction, * giving the listener a method of stopping the tailer. * @param tailer the tailer. */ public void init(Tailer tailer) { } /** * This method is called if the tailed file is not found. */ public void fileNotFound() { } /** * Called if a file rotation is detected. * * This method is called before the file is reopened, and fileNotFound may * be called if the new file has not yet been created. */ public void fileRotated() { } /** * Handles a line from a Tailer. * @param line the line. */ public void handle(String line) { } /** * Handles an Exception . * @param ex the exception. */ public void handle(Exception ex) { } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/input/BrokenInputStream.java0000644000175000017500000000544312125050425031502 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import java.io.IOException; import java.io.InputStream; /** * Broken input stream. This stream always throws an {@link IOException} from * all the {@link InputStream} methods where the exception is declared. *

* This class is mostly useful for testing error handling in code that uses an * input stream. * * @since 2.0 */ public class BrokenInputStream extends InputStream { /** * The exception that is thrown by all methods of this class. */ private final IOException exception; /** * Creates a new stream that always throws the given exception. * * @param exception the exception to be thrown */ public BrokenInputStream(IOException exception) { this.exception = exception; } /** * Creates a new stream that always throws an {@link IOException} */ public BrokenInputStream() { this(new IOException("Broken input stream")); } /** * Throws the configured exception. * * @return nothing * @throws IOException always thrown */ @Override public int read() throws IOException { throw exception; } /** * Throws the configured exception. * * @return nothing * @throws IOException always thrown */ @Override public int available() throws IOException { throw exception; } /** * Throws the configured exception. * * @param n ignored * @return nothing * @throws IOException always thrown */ @Override public long skip(long n) throws IOException { throw exception; } /** * Throws the configured exception. * * @throws IOException always thrown */ @Override public void reset() throws IOException { throw exception; } /** * Throws the configured exception. * * @throws IOException always thrown */ @Override public void close() throws IOException { throw exception; } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/input/CountingInputStream.java0000644000175000017500000001126212125050425032044 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import java.io.IOException; import java.io.InputStream; /** * A decorating input stream that counts the number of bytes that have passed * through the stream so far. *

* A typical use case would be during debugging, to ensure that data is being * read as expected. * * @version $Id: CountingInputStream.java 1304052 2012-03-22 20:55:29Z ggregory $ */ public class CountingInputStream extends ProxyInputStream { /** The count of bytes that have passed. */ private long count; /** * Constructs a new CountingInputStream. * * @param in the InputStream to delegate to */ public CountingInputStream(InputStream in) { super(in); } //----------------------------------------------------------------------- /** * Skips the stream over the specified number of bytes, adding the skipped * amount to the count. * * @param length the number of bytes to skip * @return the actual number of bytes skipped * @throws IOException if an I/O error occurs * @see java.io.InputStream#skip(long) */ @Override public synchronized long skip(final long length) throws IOException { final long skip = super.skip(length); this.count += skip; return skip; } /** * Adds the number of read bytes to the count. * * @param n number of bytes read, or -1 if no more bytes are available * @since 2.0 */ @Override protected synchronized void afterRead(int n) { if (n != -1) { this.count += n; } } //----------------------------------------------------------------------- /** * The number of bytes that have passed through this stream. *

* NOTE: From v1.3 this method throws an ArithmeticException if the * count is greater than can be expressed by an int. * See {@link #getByteCount()} for a method using a long. * * @return the number of bytes accumulated * @throws ArithmeticException if the byte count is too large */ public int getCount() { long result = getByteCount(); if (result > Integer.MAX_VALUE) { throw new ArithmeticException("The byte count " + result + " is too large to be converted to an int"); } return (int) result; } /** * Set the byte count back to 0. *

* NOTE: From v1.3 this method throws an ArithmeticException if the * count is greater than can be expressed by an int. * See {@link #resetByteCount()} for a method using a long. * * @return the count previous to resetting * @throws ArithmeticException if the byte count is too large */ public int resetCount() { long result = resetByteCount(); if (result > Integer.MAX_VALUE) { throw new ArithmeticException("The byte count " + result + " is too large to be converted to an int"); } return (int) result; } /** * The number of bytes that have passed through this stream. *

* NOTE: This method is an alternative for getCount() * and was added because that method returns an integer which will * result in incorrect count for files over 2GB. * * @return the number of bytes accumulated * @since 1.3 */ public synchronized long getByteCount() { return this.count; } /** * Set the byte count back to 0. *

* NOTE: This method is an alternative for resetCount() * and was added because that method returns an integer which will * result in incorrect count for files over 2GB. * * @return the count previous to resetting * @since 1.3 */ public synchronized long resetByteCount() { long tmp = this.count; this.count = 0; return tmp; } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/input/NullReader.java0000644000175000017500000002413212125050425030117 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import java.io.EOFException; import java.io.IOException; import java.io.Reader; /** * A functional, light weight {@link Reader} that emulates * a reader of a specified size. *

* This implementation provides a light weight * object for testing with an {@link Reader} * where the contents don't matter. *

* One use case would be for testing the handling of * large {@link Reader} as it can emulate that * scenario without the overhead of actually processing * large numbers of characters - significantly speeding up * test execution times. *

* This implementation returns a space from the method that * reads a character and leaves the array unchanged in the read * methods that are passed a character array. * If alternative data is required the processChar() and * processChars() methods can be implemented to generate * data, for example: * *

 *  public class TestReader extends NullReader {
 *      public TestReader(int size) {
 *          super(size);
 *      }
 *      protected char processChar() {
 *          return ... // return required value here
 *      }
 *      protected void processChars(char[] chars, int offset, int length) {
 *          for (int i = offset; i < length; i++) {
 *              chars[i] = ... // set array value here
 *          }
 *      }
 *  }
 * 
* * @since 1.3 * @version $Id: NullReader.java 1307462 2012-03-30 15:13:11Z ggregory $ */ public class NullReader extends Reader { private final long size; private long position; private long mark = -1; private long readlimit; private boolean eof; private final boolean throwEofException; private final boolean markSupported; /** * Create a {@link Reader} that emulates a specified size * which supports marking and does not throw EOFException. * * @param size The size of the reader to emulate. */ public NullReader(long size) { this(size, true, false); } /** * Create a {@link Reader} that emulates a specified * size with option settings. * * @param size The size of the reader to emulate. * @param markSupported Whether this instance will support * the mark() functionality. * @param throwEofException Whether this implementation * will throw an {@link EOFException} or return -1 when the * end of file is reached. */ public NullReader(long size, boolean markSupported, boolean throwEofException) { this.size = size; this.markSupported = markSupported; this.throwEofException = throwEofException; } /** * Return the current position. * * @return the current position. */ public long getPosition() { return position; } /** * Return the size this {@link Reader} emulates. * * @return The size of the reader to emulate. */ public long getSize() { return size; } /** * Close this Reader - resets the internal state to * the initial values. * * @throws IOException If an error occurs. */ @Override public void close() throws IOException { eof = false; position = 0; mark = -1; } /** * Mark the current position. * * @param readlimit The number of characters before this marked position * is invalid. * @throws UnsupportedOperationException if mark is not supported. */ @Override public synchronized void mark(int readlimit) { if (!markSupported) { throw new UnsupportedOperationException("Mark not supported"); } mark = position; this.readlimit = readlimit; } /** * Indicates whether mark is supported. * * @return Whether mark is supported or not. */ @Override public boolean markSupported() { return markSupported; } /** * Read a character. * * @return Either The character value returned by processChar() * or -1 if the end of file has been reached and * throwEofException is set to {@code false}. * @throws EOFException if the end of file is reached and * throwEofException is set to {@code true}. * @throws IOException if trying to read past the end of file. */ @Override public int read() throws IOException { if (eof) { throw new IOException("Read after end of file"); } if (position == size) { return doEndOfFile(); } position++; return processChar(); } /** * Read some characters into the specified array. * * @param chars The character array to read into * @return The number of characters read or -1 * if the end of file has been reached and * throwEofException is set to {@code false}. * @throws EOFException if the end of file is reached and * throwEofException is set to {@code true}. * @throws IOException if trying to read past the end of file. */ @Override public int read(char[] chars) throws IOException { return read(chars, 0, chars.length); } /** * Read the specified number characters into an array. * * @param chars The character array to read into. * @param offset The offset to start reading characters into. * @param length The number of characters to read. * @return The number of characters read or -1 * if the end of file has been reached and * throwEofException is set to {@code false}. * @throws EOFException if the end of file is reached and * throwEofException is set to {@code true}. * @throws IOException if trying to read past the end of file. */ @Override public int read(char[] chars, int offset, int length) throws IOException { if (eof) { throw new IOException("Read after end of file"); } if (position == size) { return doEndOfFile(); } position += length; int returnLength = length; if (position > size) { returnLength = length - (int)(position - size); position = size; } processChars(chars, offset, returnLength); return returnLength; } /** * Reset the stream to the point when mark was last called. * * @throws UnsupportedOperationException if mark is not supported. * @throws IOException If no position has been marked * or the read limit has been exceed since the last position was * marked. */ @Override public synchronized void reset() throws IOException { if (!markSupported) { throw new UnsupportedOperationException("Mark not supported"); } if (mark < 0) { throw new IOException("No position has been marked"); } if (position > mark + readlimit) { throw new IOException("Marked position [" + mark + "] is no longer valid - passed the read limit [" + readlimit + "]"); } position = mark; eof = false; } /** * Skip a specified number of characters. * * @param numberOfChars The number of characters to skip. * @return The number of characters skipped or -1 * if the end of file has been reached and * throwEofException is set to {@code false}. * @throws EOFException if the end of file is reached and * throwEofException is set to {@code true}. * @throws IOException if trying to read past the end of file. */ @Override public long skip(long numberOfChars) throws IOException { if (eof) { throw new IOException("Skip after end of file"); } if (position == size) { return doEndOfFile(); } position += numberOfChars; long returnLength = numberOfChars; if (position > size) { returnLength = numberOfChars - (position - size); position = size; } return returnLength; } /** * Return a character value for the read() method. *

* This implementation returns zero. * * @return This implementation always returns zero. */ protected int processChar() { // do nothing - overridable by subclass return 0; } /** * Process the characters for the read(char[], offset, length) * method. *

* This implementation leaves the character array unchanged. * * @param chars The character array * @param offset The offset to start at. * @param length The number of characters. */ protected void processChars(char[] chars, int offset, int length) { // do nothing - overridable by subclass } /** * Handle End of File. * * @return -1 if throwEofException is * set to {@code false} * @throws EOFException if throwEofException is set * to {@code true}. */ private int doEndOfFile() throws EOFException { eof = true; if (throwEofException) { throw new EOFException(); } return -1; } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/input/BoundedInputStream.java0000644000175000017500000001564712125050425031651 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import java.io.IOException; import java.io.InputStream; /** * This is a stream that will only supply bytes up to a certain length - if its * position goes above that, it will stop. *

* This is useful to wrap ServletInputStreams. The ServletInputStream will block * if you try to read content from it that isn't there, because it doesn't know * whether the content hasn't arrived yet or whether the content has finished. * So, one of these, initialized with the Content-length sent in the * ServletInputStream's header, will stop it blocking, providing it's been sent * with a correct content length. * * @version $Id: BoundedInputStream.java 1307462 2012-03-30 15:13:11Z ggregory $ * @since 2.0 */ public class BoundedInputStream extends InputStream { /** the wrapped input stream */ private final InputStream in; /** the max length to provide */ private final long max; /** the number of bytes already returned */ private long pos = 0; /** the marked position */ private long mark = -1; /** flag if close shoud be propagated */ private boolean propagateClose = true; /** * Creates a new BoundedInputStream that wraps the given input * stream and limits it to a certain size. * * @param in The wrapped input stream * @param size The maximum number of bytes to return */ public BoundedInputStream(InputStream in, long size) { // Some badly designed methods - eg the servlet API - overload length // such that "-1" means stream finished this.max = size; this.in = in; } /** * Creates a new BoundedInputStream that wraps the given input * stream and is unlimited. * * @param in The wrapped input stream */ public BoundedInputStream(InputStream in) { this(in, -1); } /** * Invokes the delegate's read() method if * the current position is less than the limit. * @return the byte read or -1 if the end of stream or * the limit has been reached. * @throws IOException if an I/O error occurs */ @Override public int read() throws IOException { if (max >= 0 && pos >= max) { return -1; } int result = in.read(); pos++; return result; } /** * Invokes the delegate's read(byte[]) method. * @param b the buffer to read the bytes into * @return the number of bytes read or -1 if the end of stream or * the limit has been reached. * @throws IOException if an I/O error occurs */ @Override public int read(byte[] b) throws IOException { return this.read(b, 0, b.length); } /** * Invokes the delegate's read(byte[], int, int) method. * @param b the buffer to read the bytes into * @param off The start offset * @param len The number of bytes to read * @return the number of bytes read or -1 if the end of stream or * the limit has been reached. * @throws IOException if an I/O error occurs */ @Override public int read(byte[] b, int off, int len) throws IOException { if (max>=0 && pos>=max) { return -1; } long maxRead = max>=0 ? Math.min(len, max-pos) : len; int bytesRead = in.read(b, off, (int)maxRead); if (bytesRead==-1) { return -1; } pos+=bytesRead; return bytesRead; } /** * Invokes the delegate's skip(long) method. * @param n the number of bytes to skip * @return the actual number of bytes skipped * @throws IOException if an I/O error occurs */ @Override public long skip(long n) throws IOException { long toSkip = max>=0 ? Math.min(n, max-pos) : n; long skippedBytes = in.skip(toSkip); pos+=skippedBytes; return skippedBytes; } /** * {@inheritDoc} */ @Override public int available() throws IOException { if (max>=0 && pos>=max) { return 0; } return in.available(); } /** * Invokes the delegate's toString() method. * @return the delegate's toString() */ @Override public String toString() { return in.toString(); } /** * Invokes the delegate's close() method * if {@link #isPropagateClose()} is {@code true}. * @throws IOException if an I/O error occurs */ @Override public void close() throws IOException { if (propagateClose) { in.close(); } } /** * Invokes the delegate's reset() method. * @throws IOException if an I/O error occurs */ @Override public synchronized void reset() throws IOException { in.reset(); pos = mark; } /** * Invokes the delegate's mark(int) method. * @param readlimit read ahead limit */ @Override public synchronized void mark(int readlimit) { in.mark(readlimit); mark = pos; } /** * Invokes the delegate's markSupported() method. * @return true if mark is supported, otherwise false */ @Override public boolean markSupported() { return in.markSupported(); } /** * Indicates whether the {@link #close()} method * should propagate to the underling {@link InputStream}. * * @return {@code true} if calling {@link #close()} * propagates to the close() method of the * underlying stream or {@code false} if it does not. */ public boolean isPropagateClose() { return propagateClose; } /** * Set whether the {@link #close()} method * should propagate to the underling {@link InputStream}. * * @param propagateClose {@code true} if calling * {@link #close()} propagates to the close() * method of the underlying stream or * {@code false} if it does not. */ public void setPropagateClose(boolean propagateClose) { this.propagateClose = propagateClose; } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/input/TailerListener.java0000644000175000017500000000402212125050425031004 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; /** * Listener for events from a {@link Tailer}. * * @version $Id: TailerListener.java 1304052 2012-03-22 20:55:29Z ggregory $ * @since 2.0 */ public interface TailerListener { /** * The tailer will call this method during construction, * giving the listener a method of stopping the tailer. * @param tailer the tailer. */ void init(Tailer tailer); /** * This method is called if the tailed file is not found. *

* Note: this is called from the tailer thread. */ void fileNotFound(); /** * Called if a file rotation is detected. * * This method is called before the file is reopened, and fileNotFound may * be called if the new file has not yet been created. *

* Note: this is called from the tailer thread. */ void fileRotated(); /** * Handles a line from a Tailer. *

* Note: this is called from the tailer thread. * @param line the line. */ void handle(String line); /** * Handles an Exception . *

* Note: this is called from the tailer thread. * @param ex the exception. */ void handle(Exception ex); } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/input/TeeInputStream.java0000644000175000017500000001211712125050425030773 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * InputStream proxy that transparently writes a copy of all bytes read * from the proxied stream to a given OutputStream. Using {@link #skip(long)} * or {@link #mark(int)}/{@link #reset()} on the stream will result on some * bytes from the input stream being skipped or duplicated in the output * stream. *

* The proxied input stream is closed when the {@link #close()} method is * called on this proxy. It is configurable whether the associated output * stream will also closed. * * @version $Id: TeeInputStream.java 1307461 2012-03-30 15:12:29Z ggregory $ * @since 1.4 */ public class TeeInputStream extends ProxyInputStream { /** * The output stream that will receive a copy of all bytes read from the * proxied input stream. */ private final OutputStream branch; /** * Flag for closing also the associated output stream when this * stream is closed. */ private final boolean closeBranch; /** * Creates a TeeInputStream that proxies the given {@link InputStream} * and copies all read bytes to the given {@link OutputStream}. The given * output stream will not be closed when this stream gets closed. * * @param input input stream to be proxied * @param branch output stream that will receive a copy of all bytes read */ public TeeInputStream(InputStream input, OutputStream branch) { this(input, branch, false); } /** * Creates a TeeInputStream that proxies the given {@link InputStream} * and copies all read bytes to the given {@link OutputStream}. The given * output stream will be closed when this stream gets closed if the * closeBranch parameter is {@code true}. * * @param input input stream to be proxied * @param branch output stream that will receive a copy of all bytes read * @param closeBranch flag for closing also the output stream when this * stream is closed */ public TeeInputStream( InputStream input, OutputStream branch, boolean closeBranch) { super(input); this.branch = branch; this.closeBranch = closeBranch; } /** * Closes the proxied input stream and, if so configured, the associated * output stream. An exception thrown from one stream will not prevent * closing of the other stream. * * @throws IOException if either of the streams could not be closed */ @Override public void close() throws IOException { try { super.close(); } finally { if (closeBranch) { branch.close(); } } } /** * Reads a single byte from the proxied input stream and writes it to * the associated output stream. * * @return next byte from the stream, or -1 if the stream has ended * @throws IOException if the stream could not be read (or written) */ @Override public int read() throws IOException { int ch = super.read(); if (ch != -1) { branch.write(ch); } return ch; } /** * Reads bytes from the proxied input stream and writes the read bytes * to the associated output stream. * * @param bts byte buffer * @param st start offset within the buffer * @param end maximum number of bytes to read * @return number of bytes read, or -1 if the stream has ended * @throws IOException if the stream could not be read (or written) */ @Override public int read(byte[] bts, int st, int end) throws IOException { int n = super.read(bts, st, end); if (n != -1) { branch.write(bts, st, n); } return n; } /** * Reads bytes from the proxied input stream and writes the read bytes * to the associated output stream. * * @param bts byte buffer * @return number of bytes read, or -1 if the stream has ended * @throws IOException if the stream could not be read (or written) */ @Override public int read(byte[] bts) throws IOException { int n = super.read(bts); if (n != -1) { branch.write(bts, 0, n); } return n; } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/input/CharSequenceInputStream.java0000644000175000017500000001434512125050425032631 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import java.nio.charset.CoderResult; import java.nio.charset.CodingErrorAction; /** * {@link InputStream} implementation that can read from String, StringBuffer, * StringBuilder or CharBuffer. *

* Note: Supports {@link #mark(int)} and {@link #reset()}. * * @since 2.2 */ public class CharSequenceInputStream extends InputStream { private final CharsetEncoder encoder; private final CharBuffer cbuf; private final ByteBuffer bbuf; private int mark; /** * Constructor. * * @param s the input character sequence * @param charset the character set name to use * @param bufferSize the buffer size to use. */ public CharSequenceInputStream(final CharSequence s, final Charset charset, int bufferSize) { super(); this.encoder = charset.newEncoder() .onMalformedInput(CodingErrorAction.REPLACE) .onUnmappableCharacter(CodingErrorAction.REPLACE); this.bbuf = ByteBuffer.allocate(bufferSize); this.bbuf.flip(); this.cbuf = CharBuffer.wrap(s); this.mark = -1; } /** * Constructor, calls {@link #CharSequenceInputStream(CharSequence, Charset, int)}. * * @param s the input character sequence * @param charset the character set name to use * @param bufferSize the buffer size to use. */ public CharSequenceInputStream(final CharSequence s, final String charset, int bufferSize) { this(s, Charset.forName(charset), bufferSize); } /** * Constructor, calls {@link #CharSequenceInputStream(CharSequence, Charset, int)} * with a buffer size of 2048. * * @param s the input character sequence * @param charset the character set name to use */ public CharSequenceInputStream(final CharSequence s, final Charset charset) { this(s, charset, 2048); } /** * Constructor, calls {@link #CharSequenceInputStream(CharSequence, String, int)} * with a buffer size of 2048. * * @param s the input character sequence * @param charset the character set name to use */ public CharSequenceInputStream(final CharSequence s, final String charset) { this(s, charset, 2048); } /** * Fills the byte output buffer from the input char buffer. * * @throws CharacterCodingException * an error encoding data */ private void fillBuffer() throws CharacterCodingException { this.bbuf.compact(); CoderResult result = this.encoder.encode(this.cbuf, this.bbuf, true); if (result.isError()) { result.throwException(); } this.bbuf.flip(); } @Override public int read(byte[] b, int off, int len) throws IOException { if (b == null) { throw new NullPointerException("Byte array is null"); } if (len < 0 || (off + len) > b.length) { throw new IndexOutOfBoundsException("Array Size=" + b.length + ", offset=" + off + ", length=" + len); } if (len == 0) { return 0; // must return 0 for zero length read } if (!this.bbuf.hasRemaining() && !this.cbuf.hasRemaining()) { return -1; } int bytesRead = 0; while (len > 0) { if (this.bbuf.hasRemaining()) { int chunk = Math.min(this.bbuf.remaining(), len); this.bbuf.get(b, off, chunk); off += chunk; len -= chunk; bytesRead += chunk; } else { fillBuffer(); if (!this.bbuf.hasRemaining() && !this.cbuf.hasRemaining()) { break; } } } return bytesRead == 0 && !this.cbuf.hasRemaining() ? -1 : bytesRead; } @Override public int read() throws IOException { for (;;) { if (this.bbuf.hasRemaining()) { return this.bbuf.get() & 0xFF; } else { fillBuffer(); if (!this.bbuf.hasRemaining() && !this.cbuf.hasRemaining()) { return -1; } } } } @Override public int read(byte[] b) throws IOException { return read(b, 0, b.length); } @Override public long skip(long n) throws IOException { int skipped = 0; while (n > 0 && this.cbuf.hasRemaining()) { this.cbuf.get(); n--; skipped++; } return skipped; } @Override public int available() throws IOException { return this.cbuf.remaining(); } @Override public void close() throws IOException { } /** * {@inheritDoc} * @param readlimit max read limit (ignored) */ @Override public synchronized void mark(@SuppressWarnings("unused") int readlimit) { this.mark = this.cbuf.position(); } @Override public synchronized void reset() throws IOException { if (this.mark != -1) { this.cbuf.position(this.mark); this.mark = -1; } } @Override public boolean markSupported() { return true; } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/input/TaggedInputStream.java0000644000175000017500000000773212125050425031460 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.util.UUID; import org.apache.commons.io.TaggedIOException; /** * An input stream decorator that tags potential exceptions so that the * stream that caused the exception can easily be identified. This is * done by using the {@link TaggedIOException} class to wrap all thrown * {@link IOException}s. See below for an example of using this class. *

 * TaggedInputStream stream = new TaggedInputStream(...);
 * try {
 *     // Processing that may throw an IOException either from this stream
 *     // or from some other IO activity like temporary files, etc.
 *     processStream(stream);
 * } catch (IOException e) {
 *     if (stream.isCauseOf(e)) {
 *         // The exception was caused by this stream.
 *         // Use e.getCause() to get the original exception.
 *     } else {
 *         // The exception was caused by something else.
 *     }
 * }
 * 
*

* Alternatively, the {@link #throwIfCauseOf(Throwable)} method can be * used to let higher levels of code handle the exception caused by this * stream while other processing errors are being taken care of at this * lower level. *

 * TaggedInputStream stream = new TaggedInputStream(...);
 * try {
 *     processStream(stream);
 * } catch (IOException e) {
 *     stream.throwIfCauseOf(e);
 *     // ... or process the exception that was caused by something else
 * }
 * 
* * @see TaggedIOException * @since 2.0 */ public class TaggedInputStream extends ProxyInputStream { /** * The unique tag associated with exceptions from stream. */ private final Serializable tag = UUID.randomUUID(); /** * Creates a tagging decorator for the given input stream. * * @param proxy input stream to be decorated */ public TaggedInputStream(InputStream proxy) { super(proxy); } /** * Tests if the given exception was caused by this stream. * * @param exception an exception * @return {@code true} if the exception was thrown by this stream, * {@code false} otherwise */ public boolean isCauseOf(Throwable exception) { return TaggedIOException.isTaggedWith(exception, tag); } /** * Re-throws the original exception thrown by this stream. This method * first checks whether the given exception is a {@link TaggedIOException} * wrapper created by this decorator, and then unwraps and throws the * original wrapped exception. Returns normally if the exception was * not thrown by this stream. * * @param throwable an exception * @throws IOException original exception, if any, thrown by this stream */ public void throwIfCauseOf(Throwable throwable) throws IOException { TaggedIOException.throwCauseIfTaggedWith(throwable, tag); } /** * Tags any IOExceptions thrown, wrapping and re-throwing. * * @param e The IOException thrown * @throws IOException if an I/O error occurs */ @Override protected void handleIOException(IOException e) throws IOException { throw new TaggedIOException(e, tag); } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/input/XmlStreamReader.java0000644000175000017500000007623112125050425031130 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.text.MessageFormat; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.io.ByteOrderMark; /** * Character stream that handles all the necessary Voodo to figure out the * charset encoding of the XML document within the stream. *

* IMPORTANT: This class is not related in any way to the org.xml.sax.XMLReader. * This one IS a character stream. *

* All this has to be done without consuming characters from the stream, if not * the XML parser will not recognized the document as a valid XML. This is not * 100% true, but it's close enough (UTF-8 BOM is not handled by all parsers * right now, XmlStreamReader handles it and things work in all parsers). *

* The XmlStreamReader class handles the charset encoding of XML documents in * Files, raw streams and HTTP streams by offering a wide set of constructors. *

* By default the charset encoding detection is lenient, the constructor with * the lenient flag can be used for an script (following HTTP MIME and XML * specifications). All this is nicely explained by Mark Pilgrim in his blog, * Determining the character encoding of a feed. *

* Originally developed for ROME under * Apache License 2.0. * * @version $Id: XmlStreamReader.java 1346400 2012-06-05 14:48:01Z ggregory $ * @see org.apache.commons.io.output.XmlStreamWriter * @since 2.0 */ public class XmlStreamReader extends Reader { private static final int BUFFER_SIZE = 4096; private static final String UTF_8 = "UTF-8"; private static final String US_ASCII = "US-ASCII"; private static final String UTF_16BE = "UTF-16BE"; private static final String UTF_16LE = "UTF-16LE"; private static final String UTF_32BE = "UTF-32BE"; private static final String UTF_32LE = "UTF-32LE"; private static final String UTF_16 = "UTF-16"; private static final String UTF_32 = "UTF-32"; private static final String EBCDIC = "CP1047"; private static final ByteOrderMark[] BOMS = new ByteOrderMark[] { ByteOrderMark.UTF_8, ByteOrderMark.UTF_16BE, ByteOrderMark.UTF_16LE, ByteOrderMark.UTF_32BE, ByteOrderMark.UTF_32LE }; // UTF_16LE and UTF_32LE have the same two starting BOM bytes. private static final ByteOrderMark[] XML_GUESS_BYTES = new ByteOrderMark[] { new ByteOrderMark(UTF_8, 0x3C, 0x3F, 0x78, 0x6D), new ByteOrderMark(UTF_16BE, 0x00, 0x3C, 0x00, 0x3F), new ByteOrderMark(UTF_16LE, 0x3C, 0x00, 0x3F, 0x00), new ByteOrderMark(UTF_32BE, 0x00, 0x00, 0x00, 0x3C, 0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, 0x78, 0x00, 0x00, 0x00, 0x6D), new ByteOrderMark(UTF_32LE, 0x3C, 0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, 0x78, 0x00, 0x00, 0x00, 0x6D, 0x00, 0x00, 0x00), new ByteOrderMark(EBCDIC, 0x4C, 0x6F, 0xA7, 0x94) }; private final Reader reader; private final String encoding; private final String defaultEncoding; /** * Returns the default encoding to use if none is set in HTTP content-type, * XML prolog and the rules based on content-type are not adequate. *

* If it is NULL the content-type based rules are used. * * @return the default encoding to use. */ public String getDefaultEncoding() { return defaultEncoding; } /** * Creates a Reader for a File. *

* It looks for the UTF-8 BOM first, if none sniffs the XML prolog charset, * if this is also missing defaults to UTF-8. *

* It does a lenient charset encoding detection, check the constructor with * the lenient parameter for details. * * @param file File to create a Reader from. * @throws IOException thrown if there is a problem reading the file. */ public XmlStreamReader(File file) throws IOException { this(new FileInputStream(file)); } /** * Creates a Reader for a raw InputStream. *

* It follows the same logic used for files. *

* It does a lenient charset encoding detection, check the constructor with * the lenient parameter for details. * * @param is InputStream to create a Reader from. * @throws IOException thrown if there is a problem reading the stream. */ public XmlStreamReader(InputStream is) throws IOException { this(is, true); } /** * Creates a Reader for a raw InputStream. *

* It follows the same logic used for files. *

* If lenient detection is indicated and the detection above fails as per * specifications it then attempts the following: *

* If the content type was 'text/html' it replaces it with 'text/xml' and * tries the detection again. *

* Else if the XML prolog had a charset encoding that encoding is used. *

* Else if the content type had a charset encoding that encoding is used. *

* Else 'UTF-8' is used. *

* If lenient detection is indicated an XmlStreamReaderException is never * thrown. * * @param is InputStream to create a Reader from. * @param lenient indicates if the charset encoding detection should be * relaxed. * @throws IOException thrown if there is a problem reading the stream. * @throws XmlStreamReaderException thrown if the charset encoding could not * be determined according to the specs. */ public XmlStreamReader(InputStream is, boolean lenient) throws IOException { this(is, lenient, null); } /** * Creates a Reader for a raw InputStream. *

* It follows the same logic used for files. *

* If lenient detection is indicated and the detection above fails as per * specifications it then attempts the following: *

* If the content type was 'text/html' it replaces it with 'text/xml' and * tries the detection again. *

* Else if the XML prolog had a charset encoding that encoding is used. *

* Else if the content type had a charset encoding that encoding is used. *

* Else 'UTF-8' is used. *

* If lenient detection is indicated an XmlStreamReaderException is never * thrown. * * @param is InputStream to create a Reader from. * @param lenient indicates if the charset encoding detection should be * relaxed. * @param defaultEncoding The default encoding * @throws IOException thrown if there is a problem reading the stream. * @throws XmlStreamReaderException thrown if the charset encoding could not * be determined according to the specs. */ public XmlStreamReader(InputStream is, boolean lenient, String defaultEncoding) throws IOException { this.defaultEncoding = defaultEncoding; BOMInputStream bom = new BOMInputStream(new BufferedInputStream(is, BUFFER_SIZE), false, BOMS); BOMInputStream pis = new BOMInputStream(bom, true, XML_GUESS_BYTES); this.encoding = doRawStream(bom, pis, lenient); this.reader = new InputStreamReader(pis, encoding); } /** * Creates a Reader using the InputStream of a URL. *

* If the URL is not of type HTTP and there is not 'content-type' header in * the fetched data it uses the same logic used for Files. *

* If the URL is a HTTP Url or there is a 'content-type' header in the * fetched data it uses the same logic used for an InputStream with * content-type. *

* It does a lenient charset encoding detection, check the constructor with * the lenient parameter for details. * * @param url URL to create a Reader from. * @throws IOException thrown if there is a problem reading the stream of * the URL. */ public XmlStreamReader(URL url) throws IOException { this(url.openConnection(), null); } /** * Creates a Reader using the InputStream of a URLConnection. *

* If the URLConnection is not of type HttpURLConnection and there is not * 'content-type' header in the fetched data it uses the same logic used for * files. *

* If the URLConnection is a HTTP Url or there is a 'content-type' header in * the fetched data it uses the same logic used for an InputStream with * content-type. *

* It does a lenient charset encoding detection, check the constructor with * the lenient parameter for details. * * @param conn URLConnection to create a Reader from. * @param defaultEncoding The default encoding * @throws IOException thrown if there is a problem reading the stream of * the URLConnection. */ public XmlStreamReader(URLConnection conn, String defaultEncoding) throws IOException { this.defaultEncoding = defaultEncoding; boolean lenient = true; String contentType = conn.getContentType(); InputStream is = conn.getInputStream(); BOMInputStream bom = new BOMInputStream(new BufferedInputStream(is, BUFFER_SIZE), false, BOMS); BOMInputStream pis = new BOMInputStream(bom, true, XML_GUESS_BYTES); if (conn instanceof HttpURLConnection || contentType != null) { this.encoding = doHttpStream(bom, pis, contentType, lenient); } else { this.encoding = doRawStream(bom, pis, lenient); } this.reader = new InputStreamReader(pis, encoding); } /** * Creates a Reader using an InputStream an the associated content-type * header. *

* First it checks if the stream has BOM. If there is not BOM checks the * content-type encoding. If there is not content-type encoding checks the * XML prolog encoding. If there is not XML prolog encoding uses the default * encoding mandated by the content-type MIME type. *

* It does a lenient charset encoding detection, check the constructor with * the lenient parameter for details. * * @param is InputStream to create the reader from. * @param httpContentType content-type header to use for the resolution of * the charset encoding. * @throws IOException thrown if there is a problem reading the file. */ public XmlStreamReader(InputStream is, String httpContentType) throws IOException { this(is, httpContentType, true); } /** * Creates a Reader using an InputStream an the associated content-type * header. This constructor is lenient regarding the encoding detection. *

* First it checks if the stream has BOM. If there is not BOM checks the * content-type encoding. If there is not content-type encoding checks the * XML prolog encoding. If there is not XML prolog encoding uses the default * encoding mandated by the content-type MIME type. *

* If lenient detection is indicated and the detection above fails as per * specifications it then attempts the following: *

* If the content type was 'text/html' it replaces it with 'text/xml' and * tries the detection again. *

* Else if the XML prolog had a charset encoding that encoding is used. *

* Else if the content type had a charset encoding that encoding is used. *

* Else 'UTF-8' is used. *

* If lenient detection is indicated an XmlStreamReaderException is never * thrown. * * @param is InputStream to create the reader from. * @param httpContentType content-type header to use for the resolution of * the charset encoding. * @param lenient indicates if the charset encoding detection should be * relaxed. * @param defaultEncoding The default encoding * @throws IOException thrown if there is a problem reading the file. * @throws XmlStreamReaderException thrown if the charset encoding could not * be determined according to the specs. */ public XmlStreamReader(InputStream is, String httpContentType, boolean lenient, String defaultEncoding) throws IOException { this.defaultEncoding = defaultEncoding; BOMInputStream bom = new BOMInputStream(new BufferedInputStream(is, BUFFER_SIZE), false, BOMS); BOMInputStream pis = new BOMInputStream(bom, true, XML_GUESS_BYTES); this.encoding = doHttpStream(bom, pis, httpContentType, lenient); this.reader = new InputStreamReader(pis, encoding); } /** * Creates a Reader using an InputStream an the associated content-type * header. This constructor is lenient regarding the encoding detection. *

* First it checks if the stream has BOM. If there is not BOM checks the * content-type encoding. If there is not content-type encoding checks the * XML prolog encoding. If there is not XML prolog encoding uses the default * encoding mandated by the content-type MIME type. *

* If lenient detection is indicated and the detection above fails as per * specifications it then attempts the following: *

* If the content type was 'text/html' it replaces it with 'text/xml' and * tries the detection again. *

* Else if the XML prolog had a charset encoding that encoding is used. *

* Else if the content type had a charset encoding that encoding is used. *

* Else 'UTF-8' is used. *

* If lenient detection is indicated an XmlStreamReaderException is never * thrown. * * @param is InputStream to create the reader from. * @param httpContentType content-type header to use for the resolution of * the charset encoding. * @param lenient indicates if the charset encoding detection should be * relaxed. * @throws IOException thrown if there is a problem reading the file. * @throws XmlStreamReaderException thrown if the charset encoding could not * be determined according to the specs. */ public XmlStreamReader(InputStream is, String httpContentType, boolean lenient) throws IOException { this(is, httpContentType, lenient, null); } /** * Returns the charset encoding of the XmlStreamReader. * * @return charset encoding. */ public String getEncoding() { return encoding; } /** * Invokes the underlying reader's read(char[], int, int) method. * @param buf the buffer to read the characters into * @param offset The start offset * @param len The number of bytes to read * @return the number of characters read or -1 if the end of stream * @throws IOException if an I/O error occurs */ @Override public int read(char[] buf, int offset, int len) throws IOException { return reader.read(buf, offset, len); } /** * Closes the XmlStreamReader stream. * * @throws IOException thrown if there was a problem closing the stream. */ @Override public void close() throws IOException { reader.close(); } /** * Process the raw stream. * * @param bom BOMInputStream to detect byte order marks * @param pis BOMInputStream to guess XML encoding * @param lenient indicates if the charset encoding detection should be * relaxed. * @return the encoding to be used * @throws IOException thrown if there is a problem reading the stream. */ private String doRawStream(BOMInputStream bom, BOMInputStream pis, boolean lenient) throws IOException { String bomEnc = bom.getBOMCharsetName(); String xmlGuessEnc = pis.getBOMCharsetName(); String xmlEnc = getXmlProlog(pis, xmlGuessEnc); try { return calculateRawEncoding(bomEnc, xmlGuessEnc, xmlEnc); } catch (XmlStreamReaderException ex) { if (lenient) { return doLenientDetection(null, ex); } else { throw ex; } } } /** * Process a HTTP stream. * * @param bom BOMInputStream to detect byte order marks * @param pis BOMInputStream to guess XML encoding * @param httpContentType The HTTP content type * @param lenient indicates if the charset encoding detection should be * relaxed. * @return the encoding to be used * @throws IOException thrown if there is a problem reading the stream. */ private String doHttpStream(BOMInputStream bom, BOMInputStream pis, String httpContentType, boolean lenient) throws IOException { String bomEnc = bom.getBOMCharsetName(); String xmlGuessEnc = pis.getBOMCharsetName(); String xmlEnc = getXmlProlog(pis, xmlGuessEnc); try { return calculateHttpEncoding(httpContentType, bomEnc, xmlGuessEnc, xmlEnc, lenient); } catch (XmlStreamReaderException ex) { if (lenient) { return doLenientDetection(httpContentType, ex); } else { throw ex; } } } /** * Do lenient detection. * * @param httpContentType content-type header to use for the resolution of * the charset encoding. * @param ex The thrown exception * @return the encoding * @throws IOException thrown if there is a problem reading the stream. */ private String doLenientDetection(String httpContentType, XmlStreamReaderException ex) throws IOException { if (httpContentType != null && httpContentType.startsWith("text/html")) { httpContentType = httpContentType.substring("text/html".length()); httpContentType = "text/xml" + httpContentType; try { return calculateHttpEncoding(httpContentType, ex.getBomEncoding(), ex.getXmlGuessEncoding(), ex.getXmlEncoding(), true); } catch (XmlStreamReaderException ex2) { ex = ex2; } } String encoding = ex.getXmlEncoding(); if (encoding == null) { encoding = ex.getContentTypeEncoding(); } if (encoding == null) { encoding = defaultEncoding == null ? UTF_8 : defaultEncoding; } return encoding; } /** * Calculate the raw encoding. * * @param bomEnc BOM encoding * @param xmlGuessEnc XML Guess encoding * @param xmlEnc XML encoding * @return the raw encoding * @throws IOException thrown if there is a problem reading the stream. */ String calculateRawEncoding(String bomEnc, String xmlGuessEnc, String xmlEnc) throws IOException { // BOM is Null if (bomEnc == null) { if (xmlGuessEnc == null || xmlEnc == null) { return defaultEncoding == null ? UTF_8 : defaultEncoding; } if (xmlEnc.equals(UTF_16) && (xmlGuessEnc.equals(UTF_16BE) || xmlGuessEnc.equals(UTF_16LE))) { return xmlGuessEnc; } return xmlEnc; } // BOM is UTF-8 if (bomEnc.equals(UTF_8)) { if (xmlGuessEnc != null && !xmlGuessEnc.equals(UTF_8)) { String msg = MessageFormat.format(RAW_EX_1, new Object[] { bomEnc, xmlGuessEnc, xmlEnc }); throw new XmlStreamReaderException(msg, bomEnc, xmlGuessEnc, xmlEnc); } if (xmlEnc != null && !xmlEnc.equals(UTF_8)) { String msg = MessageFormat.format(RAW_EX_1, new Object[] { bomEnc, xmlGuessEnc, xmlEnc }); throw new XmlStreamReaderException(msg, bomEnc, xmlGuessEnc, xmlEnc); } return bomEnc; } // BOM is UTF-16BE or UTF-16LE if (bomEnc.equals(UTF_16BE) || bomEnc.equals(UTF_16LE)) { if (xmlGuessEnc != null && !xmlGuessEnc.equals(bomEnc)) { String msg = MessageFormat.format(RAW_EX_1, new Object[] { bomEnc, xmlGuessEnc, xmlEnc }); throw new XmlStreamReaderException(msg, bomEnc, xmlGuessEnc, xmlEnc); } if (xmlEnc != null && !xmlEnc.equals(UTF_16) && !xmlEnc.equals(bomEnc)) { String msg = MessageFormat.format(RAW_EX_1, new Object[] { bomEnc, xmlGuessEnc, xmlEnc }); throw new XmlStreamReaderException(msg, bomEnc, xmlGuessEnc, xmlEnc); } return bomEnc; } // BOM is UTF-32BE or UTF-32LE if (bomEnc.equals(UTF_32BE) || bomEnc.equals(UTF_32LE)) { if (xmlGuessEnc != null && !xmlGuessEnc.equals(bomEnc)) { String msg = MessageFormat.format(RAW_EX_1, new Object[] { bomEnc, xmlGuessEnc, xmlEnc }); throw new XmlStreamReaderException(msg, bomEnc, xmlGuessEnc, xmlEnc); } if (xmlEnc != null && !xmlEnc.equals(UTF_32) && !xmlEnc.equals(bomEnc)) { String msg = MessageFormat.format(RAW_EX_1, new Object[] { bomEnc, xmlGuessEnc, xmlEnc }); throw new XmlStreamReaderException(msg, bomEnc, xmlGuessEnc, xmlEnc); } return bomEnc; } // BOM is something else String msg = MessageFormat.format(RAW_EX_2, new Object[] { bomEnc, xmlGuessEnc, xmlEnc }); throw new XmlStreamReaderException(msg, bomEnc, xmlGuessEnc, xmlEnc); } /** * Calculate the HTTP encoding. * * @param httpContentType The HTTP content type * @param bomEnc BOM encoding * @param xmlGuessEnc XML Guess encoding * @param xmlEnc XML encoding * @param lenient indicates if the charset encoding detection should be * relaxed. * @return the HTTP encoding * @throws IOException thrown if there is a problem reading the stream. */ String calculateHttpEncoding(String httpContentType, String bomEnc, String xmlGuessEnc, String xmlEnc, boolean lenient) throws IOException { // Lenient and has XML encoding if (lenient && xmlEnc != null) { return xmlEnc; } // Determine mime/encoding content types from HTTP Content Type String cTMime = getContentTypeMime(httpContentType); String cTEnc = getContentTypeEncoding(httpContentType); boolean appXml = isAppXml(cTMime); boolean textXml = isTextXml(cTMime); // Mime type NOT "application/xml" or "text/xml" if (!appXml && !textXml) { String msg = MessageFormat.format(HTTP_EX_3, cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc); throw new XmlStreamReaderException(msg, cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc); } // No content type encoding if (cTEnc == null) { if (appXml) { return calculateRawEncoding(bomEnc, xmlGuessEnc, xmlEnc); } else { return defaultEncoding == null ? US_ASCII : defaultEncoding; } } // UTF-16BE or UTF-16LE content type encoding if (cTEnc.equals(UTF_16BE) || cTEnc.equals(UTF_16LE)) { if (bomEnc != null) { String msg = MessageFormat.format(HTTP_EX_1, cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc); throw new XmlStreamReaderException(msg, cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc); } return cTEnc; } // UTF-16 content type encoding if (cTEnc.equals(UTF_16)) { if (bomEnc != null && bomEnc.startsWith(UTF_16)) { return bomEnc; } String msg = MessageFormat.format(HTTP_EX_2, cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc); throw new XmlStreamReaderException(msg, cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc); } // UTF-32BE or UTF-132E content type encoding if (cTEnc.equals(UTF_32BE) || cTEnc.equals(UTF_32LE)) { if (bomEnc != null) { String msg = MessageFormat.format(HTTP_EX_1, cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc); throw new XmlStreamReaderException(msg, cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc); } return cTEnc; } // UTF-32 content type encoding if (cTEnc.equals(UTF_32)) { if (bomEnc != null && bomEnc.startsWith(UTF_32)) { return bomEnc; } String msg = MessageFormat.format(HTTP_EX_2, cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc); throw new XmlStreamReaderException(msg, cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc); } return cTEnc; } /** * Returns MIME type or NULL if httpContentType is NULL. * * @param httpContentType the HTTP content type * @return The mime content type */ static String getContentTypeMime(String httpContentType) { String mime = null; if (httpContentType != null) { int i = httpContentType.indexOf(";"); if (i >= 0) { mime = httpContentType.substring(0, i); } else { mime = httpContentType; } mime = mime.trim(); } return mime; } private static final Pattern CHARSET_PATTERN = Pattern .compile("charset=[\"']?([.[^; \"']]*)[\"']?"); /** * Returns charset parameter value, NULL if not present, NULL if * httpContentType is NULL. * * @param httpContentType the HTTP content type * @return The content type encoding (upcased) */ static String getContentTypeEncoding(String httpContentType) { String encoding = null; if (httpContentType != null) { int i = httpContentType.indexOf(";"); if (i > -1) { String postMime = httpContentType.substring(i + 1); Matcher m = CHARSET_PATTERN.matcher(postMime); encoding = m.find() ? m.group(1) : null; encoding = encoding != null ? encoding.toUpperCase(Locale.US) : null; } } return encoding; } public static final Pattern ENCODING_PATTERN = Pattern.compile( "<\\?xml.*encoding[\\s]*=[\\s]*((?:\".[^\"]*\")|(?:'.[^']*'))", Pattern.MULTILINE); /** * Returns the encoding declared in the , NULL if none. * * @param is InputStream to create the reader from. * @param guessedEnc guessed encoding * @return the encoding declared in the * @throws IOException thrown if there is a problem reading the stream. */ private static String getXmlProlog(InputStream is, String guessedEnc) throws IOException { String encoding = null; if (guessedEnc != null) { byte[] bytes = new byte[BUFFER_SIZE]; is.mark(BUFFER_SIZE); int offset = 0; int max = BUFFER_SIZE; int c = is.read(bytes, offset, max); int firstGT = -1; String xmlProlog = null; while (c != -1 && firstGT == -1 && offset < BUFFER_SIZE) { offset += c; max -= c; c = is.read(bytes, offset, max); xmlProlog = new String(bytes, 0, offset, guessedEnc); firstGT = xmlProlog.indexOf('>'); } if (firstGT == -1) { if (c == -1) { throw new IOException("Unexpected end of XML stream"); } else { throw new IOException( "XML prolog or ROOT element not found on first " + offset + " bytes"); } } int bytesRead = offset; if (bytesRead > 0) { is.reset(); BufferedReader bReader = new BufferedReader(new StringReader( xmlProlog.substring(0, firstGT + 1))); StringBuffer prolog = new StringBuffer(); String line = bReader.readLine(); while (line != null) { prolog.append(line); line = bReader.readLine(); } Matcher m = ENCODING_PATTERN.matcher(prolog); if (m.find()) { encoding = m.group(1).toUpperCase(); encoding = encoding.substring(1, encoding.length() - 1); } } } return encoding; } /** * Indicates if the MIME type belongs to the APPLICATION XML family. * * @param mime The mime type * @return true if the mime type belongs to the APPLICATION XML family, * otherwise false */ static boolean isAppXml(String mime) { return mime != null && (mime.equals("application/xml") || mime.equals("application/xml-dtd") || mime.equals("application/xml-external-parsed-entity") || mime.startsWith("application/") && mime.endsWith("+xml")); } /** * Indicates if the MIME type belongs to the TEXT XML family. * * @param mime The mime type * @return true if the mime type belongs to the TEXT XML family, * otherwise false */ static boolean isTextXml(String mime) { return mime != null && (mime.equals("text/xml") || mime.equals("text/xml-external-parsed-entity") || mime.startsWith("text/") && mime.endsWith("+xml")); } private static final String RAW_EX_1 = "Invalid encoding, BOM [{0}] XML guess [{1}] XML prolog [{2}] encoding mismatch"; private static final String RAW_EX_2 = "Invalid encoding, BOM [{0}] XML guess [{1}] XML prolog [{2}] unknown BOM"; private static final String HTTP_EX_1 = "Invalid encoding, CT-MIME [{0}] CT-Enc [{1}] BOM [{2}] XML guess [{3}] XML prolog [{4}], BOM must be NULL"; private static final String HTTP_EX_2 = "Invalid encoding, CT-MIME [{0}] CT-Enc [{1}] BOM [{2}] XML guess [{3}] XML prolog [{4}], encoding mismatch"; private static final String HTTP_EX_3 = "Invalid encoding, CT-MIME [{0}] CT-Enc [{1}] BOM [{2}] XML guess [{3}] XML prolog [{4}], Invalid MIME"; } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/input/SwappedDataInputStream.java0000644000175000017500000001721512125050425032457 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import java.io.DataInput; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import org.apache.commons.io.EndianUtils; /** * DataInput for systems relying on little endian data formats. * When read, values will be changed from little endian to big * endian formats for internal usage. *

* Origin of code: Avalon Excalibur (IO) * * @version CVS $Revision: 1302050 $ */ public class SwappedDataInputStream extends ProxyInputStream implements DataInput { /** * Constructs a SwappedDataInputStream. * * @param input InputStream to read from */ public SwappedDataInputStream( InputStream input ) { super( input ); } /** * Return {@link #readByte()} != 0 * @return false if the byte read is zero, otherwise true * @throws IOException if an I/O error occurs * @throws EOFException if an end of file is reached unexpectedly */ public boolean readBoolean() throws IOException, EOFException { return 0 != readByte(); } /** * Invokes the delegate's read() method. * @return the byte read or -1 if the end of stream * @throws IOException if an I/O error occurs * @throws EOFException if an end of file is reached unexpectedly */ public byte readByte() throws IOException, EOFException { return (byte)in.read(); } /** * Reads a character delegating to {@link #readShort()}. * @return the byte read or -1 if the end of stream * @throws IOException if an I/O error occurs * @throws EOFException if an end of file is reached unexpectedly */ public char readChar() throws IOException, EOFException { return (char)readShort(); } /** * Delegates to {@link EndianUtils#readSwappedDouble(InputStream)}. * @return the read long * @throws IOException if an I/O error occurs * @throws EOFException if an end of file is reached unexpectedly */ public double readDouble() throws IOException, EOFException { return EndianUtils.readSwappedDouble( in ); } /** * Delegates to {@link EndianUtils#readSwappedFloat(InputStream)}. * @return the read long * @throws IOException if an I/O error occurs * @throws EOFException if an end of file is reached unexpectedly */ public float readFloat() throws IOException, EOFException { return EndianUtils.readSwappedFloat( in ); } /** * Invokes the delegate's read(byte[] data, int, int) method. * * @param data the buffer to read the bytes into * @throws EOFException if an end of file is reached unexpectedly * @throws IOException if an I/O error occurs */ public void readFully( byte[] data ) throws IOException, EOFException { readFully( data, 0, data.length ); } /** * Invokes the delegate's read(byte[] data, int, int) method. * * @param data the buffer to read the bytes into * @param offset The start offset * @param length The number of bytes to read * @throws EOFException if an end of file is reached unexpectedly * @throws IOException if an I/O error occurs */ public void readFully( byte[] data, int offset, int length ) throws IOException, EOFException { int remaining = length; while( remaining > 0 ) { int location = offset + length - remaining; int count = read( data, location, remaining ); if( -1 == count ) { throw new EOFException(); } remaining -= count; } } /** * Delegates to {@link EndianUtils#readSwappedInteger(InputStream)}. * @return the read long * @throws EOFException if an end of file is reached unexpectedly * @throws IOException if an I/O error occurs */ public int readInt() throws IOException, EOFException { return EndianUtils.readSwappedInteger( in ); } /** * Not currently supported - throws {@link UnsupportedOperationException}. * @return the line read * @throws EOFException if an end of file is reached unexpectedly * @throws IOException if an I/O error occurs */ public String readLine() throws IOException, EOFException { throw new UnsupportedOperationException( "Operation not supported: readLine()" ); } /** * Delegates to {@link EndianUtils#readSwappedLong(InputStream)}. * @return the read long * @throws EOFException if an end of file is reached unexpectedly * @throws IOException if an I/O error occurs */ public long readLong() throws IOException, EOFException { return EndianUtils.readSwappedLong( in ); } /** * Delegates to {@link EndianUtils#readSwappedShort(InputStream)}. * @return the read long * @throws EOFException if an end of file is reached unexpectedly * @throws IOException if an I/O error occurs */ public short readShort() throws IOException, EOFException { return EndianUtils.readSwappedShort( in ); } /** * Invokes the delegate's read() method. * @return the byte read or -1 if the end of stream * @throws EOFException if an end of file is reached unexpectedly * @throws IOException if an I/O error occurs */ public int readUnsignedByte() throws IOException, EOFException { return in.read(); } /** * Delegates to {@link EndianUtils#readSwappedUnsignedShort(InputStream)}. * @return the read long * @throws EOFException if an end of file is reached unexpectedly * @throws IOException if an I/O error occurs */ public int readUnsignedShort() throws IOException, EOFException { return EndianUtils.readSwappedUnsignedShort( in ); } /** * Not currently supported - throws {@link UnsupportedOperationException}. * @return UTF String read * @throws EOFException if an end of file is reached unexpectedly * @throws IOException if an I/O error occurs */ public String readUTF() throws IOException, EOFException { throw new UnsupportedOperationException( "Operation not supported: readUTF()" ); } /** * Invokes the delegate's skip(int) method. * @param count the number of bytes to skip * @return the number of bytes to skipped or -1 if the end of stream * @throws EOFException if an end of file is reached unexpectedly * @throws IOException if an I/O error occurs */ public int skipBytes( int count ) throws IOException, EOFException { return (int)in.skip( count ); } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/input/ReversedLinesFileReader.java0000644000175000017500000003145412125050425032564 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import java.nio.charset.UnsupportedCharsetException; import org.apache.commons.io.Charsets; /** * Reads lines in a file reversely (similar to a BufferedReader, but starting at * the last line). Useful for e.g. searching in log files. * * @since 2.2 */ public class ReversedLinesFileReader implements Closeable { private final int blockSize; private final Charset encoding; private final RandomAccessFile randomAccessFile; private final long totalByteLength; private final long totalBlockCount; private final byte[][] newLineSequences; private final int avoidNewlineSplitBufferSize; private final int byteDecrement; private FilePart currentFilePart; private boolean trailingNewlineOfFileSkipped = false; /** * Creates a ReversedLinesFileReader with default block size of 4KB and the * platform's default encoding. * * @param file * the file to be read * @throws IOException if an I/O error occurs */ public ReversedLinesFileReader(final File file) throws IOException { this(file, 4096, Charset.defaultCharset().toString()); } /** * Creates a ReversedLinesFileReader with the given block size and encoding. * * @param file * the file to be read * @param blockSize * size of the internal buffer (for ideal performance this should * match with the block size of the underlying file system). * @param encoding * the encoding of the file * @throws IOException if an I/O error occurs * @since 2.3 */ public ReversedLinesFileReader(final File file, final int blockSize, final Charset encoding) throws IOException { this.blockSize = blockSize; this.encoding = encoding; randomAccessFile = new RandomAccessFile(file, "r"); totalByteLength = randomAccessFile.length(); int lastBlockLength = (int) (totalByteLength % blockSize); if (lastBlockLength > 0) { totalBlockCount = totalByteLength / blockSize + 1; } else { totalBlockCount = totalByteLength / blockSize; if (totalByteLength > 0) { lastBlockLength = blockSize; } } currentFilePart = new FilePart(totalBlockCount, lastBlockLength, null); // --- check & prepare encoding --- Charset charset = Charsets.toCharset(encoding); CharsetEncoder charsetEncoder = charset.newEncoder(); float maxBytesPerChar = charsetEncoder.maxBytesPerChar(); if(maxBytesPerChar==1f) { // all one byte encodings are no problem byteDecrement = 1; } else if(charset == Charset.forName("UTF-8")) { // UTF-8 works fine out of the box, for multibyte sequences a second UTF-8 byte can never be a newline byte // http://en.wikipedia.org/wiki/UTF-8 byteDecrement = 1; } else if(charset == Charset.forName("Shift_JIS")) { // Same as for UTF-8 // http://www.herongyang.com/Unicode/JIS-Shift-JIS-Encoding.html byteDecrement = 1; } else if(charset == Charset.forName("UTF-16BE") || charset == Charset.forName("UTF-16LE")) { // UTF-16 new line sequences are not allowed as second tuple of four byte sequences, // however byte order has to be specified byteDecrement = 2; } else if(charset == Charset.forName("UTF-16")) { throw new UnsupportedEncodingException( "For UTF-16, you need to specify the byte order (use UTF-16BE or UTF-16LE)"); } else { throw new UnsupportedEncodingException( "Encoding "+encoding+" is not supported yet (feel free to submit a patch)"); } // NOTE: The new line sequences are matched in the order given, so it is important that \r\n is BEFORE \n newLineSequences = new byte[][] { "\r\n".getBytes(encoding), "\n".getBytes(encoding), "\r".getBytes(encoding) }; avoidNewlineSplitBufferSize = newLineSequences[0].length; } /** * Creates a ReversedLinesFileReader with the given block size and encoding. * * @param file * the file to be read * @param blockSize * size of the internal buffer (for ideal performance this should * match with the block size of the underlying file system). * @param encoding * the encoding of the file * @throws IOException if an I/O error occurs * @throws UnsupportedCharsetException * thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not * supported. */ public ReversedLinesFileReader(final File file, final int blockSize, final String encoding) throws IOException { this(file, blockSize, Charsets.toCharset(encoding)); } /** * Returns the lines of the file from bottom to top. * * @return the next line or null if the start of the file is reached * @throws IOException if an I/O error occurs */ public String readLine() throws IOException { String line = currentFilePart.readLine(); while (line == null) { currentFilePart = currentFilePart.rollOver(); if (currentFilePart != null) { line = currentFilePart.readLine(); } else { // no more fileparts: we're done, leave line set to null break; } } // aligned behaviour wiht BufferedReader that doesn't return a last, emtpy line if("".equals(line) && !trailingNewlineOfFileSkipped) { trailingNewlineOfFileSkipped = true; line = readLine(); } return line; } /** * Closes underlying resources. * * @throws IOException if an I/O error occurs */ public void close() throws IOException { randomAccessFile.close(); } private class FilePart { private final long no; private final byte[] data; private byte[] leftOver; private int currentLastBytePos; /** * ctor * @param no the part number * @param length its length * @param leftOverOfLastFilePart remainder * @throws IOException if there is a problem reading the file */ private FilePart(final long no, final int length, final byte[] leftOverOfLastFilePart) throws IOException { this.no = no; int dataLength = length + (leftOverOfLastFilePart != null ? leftOverOfLastFilePart.length : 0); this.data = new byte[dataLength]; final long off = (no - 1) * blockSize; // read data if (no > 0 /* file not empty */) { randomAccessFile.seek(off); final int countRead = randomAccessFile.read(data, 0, length); if (countRead != length) { throw new IllegalStateException("Count of requested bytes and actually read bytes don't match"); } } // copy left over part into data arr if (leftOverOfLastFilePart != null) { System.arraycopy(leftOverOfLastFilePart, 0, data, length, leftOverOfLastFilePart.length); } this.currentLastBytePos = data.length - 1; this.leftOver = null; } /** * Handles block rollover * * @return the new FilePart or null * @throws IOException if there was a problem reading the file */ private FilePart rollOver() throws IOException { if (currentLastBytePos > -1) { throw new IllegalStateException("Current currentLastCharPos unexpectedly positive... " + "last readLine() should have returned something! currentLastCharPos=" + currentLastBytePos); } if (no > 1) { return new FilePart(no - 1, blockSize, leftOver); } else { // NO 1 was the last FilePart, we're finished if (leftOver != null) { throw new IllegalStateException("Unexpected leftover of the last block: leftOverOfThisFilePart=" + new String(leftOver, encoding)); } return null; } } /** * Reads a line. * * @return the line or null * @throws IOException if there is an error reading from the file */ private String readLine() throws IOException { String line = null; int newLineMatchByteCount; boolean isLastFilePart = no == 1; int i = currentLastBytePos; while (i > -1) { if (!isLastFilePart && i < avoidNewlineSplitBufferSize) { // avoidNewlineSplitBuffer: for all except the last file part we // take a few bytes to the next file part to avoid splitting of newlines createLeftOver(); break; // skip last few bytes and leave it to the next file part } // --- check for newline --- if ((newLineMatchByteCount = getNewLineMatchByteCount(data, i)) > 0 /* found newline */) { final int lineStart = i + 1; int lineLengthBytes = currentLastBytePos - lineStart + 1; if (lineLengthBytes < 0) { throw new IllegalStateException("Unexpected negative line length="+lineLengthBytes); } byte[] lineData = new byte[lineLengthBytes]; System.arraycopy(data, lineStart, lineData, 0, lineLengthBytes); line = new String(lineData, encoding); currentLastBytePos = i - newLineMatchByteCount; break; // found line } // --- move cursor --- i -= byteDecrement; // --- end of file part handling --- if (i < 0) { createLeftOver(); break; // end of file part } } // --- last file part handling --- if (isLastFilePart && leftOver != null) { // there will be no line break anymore, this is the first line of the file line = new String(leftOver, encoding); leftOver = null; } return line; } /** * Creates the buffer containing any left over bytes. */ private void createLeftOver() { int lineLengthBytes = currentLastBytePos + 1; if (lineLengthBytes > 0) { // create left over for next block leftOver = new byte[lineLengthBytes]; System.arraycopy(data, 0, leftOver, 0, lineLengthBytes); } else { leftOver = null; } currentLastBytePos = -1; } /** * Finds the new-line sequence and return its length. * * @param data buffer to scan * @param i start offset in buffer * @return length of newline sequence or 0 if none found */ private int getNewLineMatchByteCount(byte[] data, int i) { for (byte[] newLineSequence : newLineSequences) { boolean match = true; for (int j = newLineSequence.length - 1; j >= 0; j--) { int k = i + j - (newLineSequence.length - 1); match &= k >= 0 && data[k] == newLineSequence[j]; } if (match) { return newLineSequence.length; } } return 0; } } }libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/input/ProxyReader.java0000644000175000017500000002021012125050425030317 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import java.io.FilterReader; import java.io.IOException; import java.io.Reader; import java.nio.CharBuffer; /** * A Proxy stream which acts as expected, that is it passes the method * calls on to the proxied stream and doesn't change which methods are * being called. *

* It is an alternative base class to FilterReader * to increase reusability, because FilterReader changes the * methods being called, such as read(char[]) to read(char[], int, int). * * @version $Id: ProxyReader.java 1304052 2012-03-22 20:55:29Z ggregory $ */ public abstract class ProxyReader extends FilterReader { /** * Constructs a new ProxyReader. * * @param proxy the Reader to delegate to */ public ProxyReader(Reader proxy) { super(proxy); // the proxy is stored in a protected superclass variable named 'in' } /** * Invokes the delegate's read() method. * @return the character read or -1 if the end of stream * @throws IOException if an I/O error occurs */ @Override public int read() throws IOException { try { beforeRead(1); int c = in.read(); afterRead(c != -1 ? 1 : -1); return c; } catch (IOException e) { handleIOException(e); return -1; } } /** * Invokes the delegate's read(char[]) method. * @param chr the buffer to read the characters into * @return the number of characters read or -1 if the end of stream * @throws IOException if an I/O error occurs */ @Override public int read(char[] chr) throws IOException { try { beforeRead(chr != null ? chr.length : 0); int n = in.read(chr); afterRead(n); return n; } catch (IOException e) { handleIOException(e); return -1; } } /** * Invokes the delegate's read(char[], int, int) method. * @param chr the buffer to read the characters into * @param st The start offset * @param len The number of bytes to read * @return the number of characters read or -1 if the end of stream * @throws IOException if an I/O error occurs */ @Override public int read(char[] chr, int st, int len) throws IOException { try { beforeRead(len); int n = in.read(chr, st, len); afterRead(n); return n; } catch (IOException e) { handleIOException(e); return -1; } } /** * Invokes the delegate's read(CharBuffer) method. * @param target the char buffer to read the characters into * @return the number of characters read or -1 if the end of stream * @throws IOException if an I/O error occurs * @since 2.0 */ @Override public int read(CharBuffer target) throws IOException { try { beforeRead(target != null ? target.length() : 0); int n = in.read(target); afterRead(n); return n; } catch (IOException e) { handleIOException(e); return -1; } } /** * Invokes the delegate's skip(long) method. * @param ln the number of bytes to skip * @return the number of bytes to skipped or -1 if the end of stream * @throws IOException if an I/O error occurs */ @Override public long skip(long ln) throws IOException { try { return in.skip(ln); } catch (IOException e) { handleIOException(e); return 0; } } /** * Invokes the delegate's ready() method. * @return true if the stream is ready to be read * @throws IOException if an I/O error occurs */ @Override public boolean ready() throws IOException { try { return in.ready(); } catch (IOException e) { handleIOException(e); return false; } } /** * Invokes the delegate's close() method. * @throws IOException if an I/O error occurs */ @Override public void close() throws IOException { try { in.close(); } catch (IOException e) { handleIOException(e); } } /** * Invokes the delegate's mark(int) method. * @param idx read ahead limit * @throws IOException if an I/O error occurs */ @Override public synchronized void mark(int idx) throws IOException { try { in.mark(idx); } catch (IOException e) { handleIOException(e); } } /** * Invokes the delegate's reset() method. * @throws IOException if an I/O error occurs */ @Override public synchronized void reset() throws IOException { try { in.reset(); } catch (IOException e) { handleIOException(e); } } /** * Invokes the delegate's markSupported() method. * @return true if mark is supported, otherwise false */ @Override public boolean markSupported() { return in.markSupported(); } /** * Invoked by the read methods before the call is proxied. The number * of chars that the caller wanted to read (1 for the {@link #read()} * method, buffer length for {@link #read(char[])}, etc.) is given as * an argument. *

* Subclasses can override this method to add common pre-processing * functionality without having to override all the read methods. * The default implementation does nothing. *

* Note this method is not called from {@link #skip(long)} or * {@link #reset()}. You need to explicitly override those methods if * you want to add pre-processing steps also to them. * * @since 2.0 * @param n number of chars that the caller asked to be read * @throws IOException if the pre-processing fails */ protected void beforeRead(int n) throws IOException { } /** * Invoked by the read methods after the proxied call has returned * successfully. The number of chars returned to the caller (or -1 if * the end of stream was reached) is given as an argument. *

* Subclasses can override this method to add common post-processing * functionality without having to override all the read methods. * The default implementation does nothing. *

* Note this method is not called from {@link #skip(long)} or * {@link #reset()}. You need to explicitly override those methods if * you want to add post-processing steps also to them. * * @since 2.0 * @param n number of chars read, or -1 if the end of stream was reached * @throws IOException if the post-processing fails */ protected void afterRead(int n) throws IOException { } /** * Handle any IOExceptions thrown. *

* This method provides a point to implement custom exception * handling. The default behaviour is to re-throw the exception. * @param e The IOException thrown * @throws IOException if an I/O error occurs * @since 2.0 */ protected void handleIOException(IOException e) throws IOException { throw e; } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/input/ProxyInputStream.java0000644000175000017500000001677512125050425031415 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; /** * A Proxy stream which acts as expected, that is it passes the method * calls on to the proxied stream and doesn't change which methods are * being called. *

* It is an alternative base class to FilterInputStream * to increase reusability, because FilterInputStream changes the * methods being called, such as read(byte[]) to read(byte[], int, int). *

* See the protected methods for ways in which a subclass can easily decorate * a stream with custom pre-, post- or error processing functionality. * * @version $Id: ProxyInputStream.java 1304052 2012-03-22 20:55:29Z ggregory $ */ public abstract class ProxyInputStream extends FilterInputStream { /** * Constructs a new ProxyInputStream. * * @param proxy the InputStream to delegate to */ public ProxyInputStream(InputStream proxy) { super(proxy); // the proxy is stored in a protected superclass variable named 'in' } /** * Invokes the delegate's read() method. * @return the byte read or -1 if the end of stream * @throws IOException if an I/O error occurs */ @Override public int read() throws IOException { try { beforeRead(1); int b = in.read(); afterRead(b != -1 ? 1 : -1); return b; } catch (IOException e) { handleIOException(e); return -1; } } /** * Invokes the delegate's read(byte[]) method. * @param bts the buffer to read the bytes into * @return the number of bytes read or -1 if the end of stream * @throws IOException if an I/O error occurs */ @Override public int read(byte[] bts) throws IOException { try { beforeRead(bts != null ? bts.length : 0); int n = in.read(bts); afterRead(n); return n; } catch (IOException e) { handleIOException(e); return -1; } } /** * Invokes the delegate's read(byte[], int, int) method. * @param bts the buffer to read the bytes into * @param off The start offset * @param len The number of bytes to read * @return the number of bytes read or -1 if the end of stream * @throws IOException if an I/O error occurs */ @Override public int read(byte[] bts, int off, int len) throws IOException { try { beforeRead(len); int n = in.read(bts, off, len); afterRead(n); return n; } catch (IOException e) { handleIOException(e); return -1; } } /** * Invokes the delegate's skip(long) method. * @param ln the number of bytes to skip * @return the actual number of bytes skipped * @throws IOException if an I/O error occurs */ @Override public long skip(long ln) throws IOException { try { return in.skip(ln); } catch (IOException e) { handleIOException(e); return 0; } } /** * Invokes the delegate's available() method. * @return the number of available bytes * @throws IOException if an I/O error occurs */ @Override public int available() throws IOException { try { return super.available(); } catch (IOException e) { handleIOException(e); return 0; } } /** * Invokes the delegate's close() method. * @throws IOException if an I/O error occurs */ @Override public void close() throws IOException { try { in.close(); } catch (IOException e) { handleIOException(e); } } /** * Invokes the delegate's mark(int) method. * @param readlimit read ahead limit */ @Override public synchronized void mark(int readlimit) { in.mark(readlimit); } /** * Invokes the delegate's reset() method. * @throws IOException if an I/O error occurs */ @Override public synchronized void reset() throws IOException { try { in.reset(); } catch (IOException e) { handleIOException(e); } } /** * Invokes the delegate's markSupported() method. * @return true if mark is supported, otherwise false */ @Override public boolean markSupported() { return in.markSupported(); } /** * Invoked by the read methods before the call is proxied. The number * of bytes that the caller wanted to read (1 for the {@link #read()} * method, buffer length for {@link #read(byte[])}, etc.) is given as * an argument. *

* Subclasses can override this method to add common pre-processing * functionality without having to override all the read methods. * The default implementation does nothing. *

* Note this method is not called from {@link #skip(long)} or * {@link #reset()}. You need to explicitly override those methods if * you want to add pre-processing steps also to them. * * @since 2.0 * @param n number of bytes that the caller asked to be read * @throws IOException if the pre-processing fails */ protected void beforeRead(int n) throws IOException { } /** * Invoked by the read methods after the proxied call has returned * successfully. The number of bytes returned to the caller (or -1 if * the end of stream was reached) is given as an argument. *

* Subclasses can override this method to add common post-processing * functionality without having to override all the read methods. * The default implementation does nothing. *

* Note this method is not called from {@link #skip(long)} or * {@link #reset()}. You need to explicitly override those methods if * you want to add post-processing steps also to them. * * @since 2.0 * @param n number of bytes read, or -1 if the end of stream was reached * @throws IOException if the post-processing fails */ protected void afterRead(int n) throws IOException { } /** * Handle any IOExceptions thrown. *

* This method provides a point to implement custom exception * handling. The default behaviour is to re-throw the exception. * @param e The IOException thrown * @throws IOException if an I/O error occurs * @since 2.0 */ protected void handleIOException(IOException e) throws IOException { throw e; } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/input/Tailer.java0000644000175000017500000004172712125050425027313 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; /** * Simple implementation of the unix "tail -f" functionality. *

*

1. Create a TailerListener implementation

*

* First you need to create a {@link TailerListener} implementation * ({@link TailerListenerAdapter} is provided for convenience so that you don't have to * implement every method). *

* *

For example:

*
 *  public class MyTailerListener extends TailerListenerAdapter {
 *      public void handle(String line) {
 *          System.out.println(line);
 *      }
 *  }
 * 
* *

2. Using a Tailer

* * You can create and use a Tailer in one of three ways: *
    *
  • Using one of the static helper methods: *
      *
    • {@link Tailer#create(File, TailerListener)}
    • *
    • {@link Tailer#create(File, TailerListener, long)}
    • *
    • {@link Tailer#create(File, TailerListener, long, boolean)}
    • *
    *
  • *
  • Using an {@link java.util.concurrent.Executor}
  • *
  • Using an {@link Thread}
  • *
* * An example of each of these is shown below. * *

2.1 Using the static helper method

* *
 *      TailerListener listener = new MyTailerListener();
 *      Tailer tailer = Tailer.create(file, listener, delay);
 * 
* *

2.2 Use an Executor

* *
 *      TailerListener listener = new MyTailerListener();
 *      Tailer tailer = new Tailer(file, listener, delay);
 *
 *      // stupid executor impl. for demo purposes
 *      Executor executor = new Executor() {
 *          public void execute(Runnable command) {
 *              command.run();
 *           }
 *      };
 *
 *      executor.execute(tailer);
 * 
* * *

2.3 Use a Thread

*
 *      TailerListener listener = new MyTailerListener();
 *      Tailer tailer = new Tailer(file, listener, delay);
 *      Thread thread = new Thread(tailer);
 *      thread.setDaemon(true); // optional
 *      thread.start();
 * 
* *

3. Stop Tailing

*

Remember to stop the tailer when you have done with it:

*
 *      tailer.stop();
 * 
* * @see TailerListener * @see TailerListenerAdapter * @version $Id: Tailer.java 1348698 2012-06-11 01:09:58Z ggregory $ * @since 2.0 */ public class Tailer implements Runnable { private static final int DEFAULT_DELAY_MILLIS = 1000; private static final String RAF_MODE = "r"; private static final int DEFAULT_BUFSIZE = 4096; /** * Buffer on top of RandomAccessFile. */ private final byte inbuf[]; /** * The file which will be tailed. */ private final File file; /** * The amount of time to wait for the file to be updated. */ private final long delayMillis; /** * Whether to tail from the end or start of file */ private final boolean end; /** * The listener to notify of events when tailing. */ private final TailerListener listener; /** * Whether to close and reopen the file whilst waiting for more input. */ private final boolean reOpen; /** * The tailer will run as long as this value is true. */ private volatile boolean run = true; /** * Creates a Tailer for the given file, starting from the beginning, with the default delay of 1.0s. * @param file The file to follow. * @param listener the TailerListener to use. */ public Tailer(File file, TailerListener listener) { this(file, listener, DEFAULT_DELAY_MILLIS); } /** * Creates a Tailer for the given file, starting from the beginning. * @param file the file to follow. * @param listener the TailerListener to use. * @param delayMillis the delay between checks of the file for new content in milliseconds. */ public Tailer(File file, TailerListener listener, long delayMillis) { this(file, listener, delayMillis, false); } /** * Creates a Tailer for the given file, with a delay other than the default 1.0s. * @param file the file to follow. * @param listener the TailerListener to use. * @param delayMillis the delay between checks of the file for new content in milliseconds. * @param end Set to true to tail from the end of the file, false to tail from the beginning of the file. */ public Tailer(File file, TailerListener listener, long delayMillis, boolean end) { this(file, listener, delayMillis, end, DEFAULT_BUFSIZE); } /** * Creates a Tailer for the given file, with a delay other than the default 1.0s. * @param file the file to follow. * @param listener the TailerListener to use. * @param delayMillis the delay between checks of the file for new content in milliseconds. * @param end Set to true to tail from the end of the file, false to tail from the beginning of the file. * @param reOpen if true, close and reopen the file between reading chunks */ public Tailer(File file, TailerListener listener, long delayMillis, boolean end, boolean reOpen) { this(file, listener, delayMillis, end, reOpen, DEFAULT_BUFSIZE); } /** * Creates a Tailer for the given file, with a specified buffer size. * @param file the file to follow. * @param listener the TailerListener to use. * @param delayMillis the delay between checks of the file for new content in milliseconds. * @param end Set to true to tail from the end of the file, false to tail from the beginning of the file. * @param bufSize Buffer size */ public Tailer(File file, TailerListener listener, long delayMillis, boolean end, int bufSize) { this(file, listener, delayMillis, end, false, bufSize); } /** * Creates a Tailer for the given file, with a specified buffer size. * @param file the file to follow. * @param listener the TailerListener to use. * @param delayMillis the delay between checks of the file for new content in milliseconds. * @param end Set to true to tail from the end of the file, false to tail from the beginning of the file. * @param reOpen if true, close and reopen the file between reading chunks * @param bufSize Buffer size */ public Tailer(File file, TailerListener listener, long delayMillis, boolean end, boolean reOpen, int bufSize) { this.file = file; this.delayMillis = delayMillis; this.end = end; this.inbuf = new byte[bufSize]; // Save and prepare the listener this.listener = listener; listener.init(this); this.reOpen = reOpen; } /** * Creates and starts a Tailer for the given file. * * @param file the file to follow. * @param listener the TailerListener to use. * @param delayMillis the delay between checks of the file for new content in milliseconds. * @param end Set to true to tail from the end of the file, false to tail from the beginning of the file. * @param bufSize buffer size. * @return The new tailer */ public static Tailer create(File file, TailerListener listener, long delayMillis, boolean end, int bufSize) { Tailer tailer = new Tailer(file, listener, delayMillis, end, bufSize); Thread thread = new Thread(tailer); thread.setDaemon(true); thread.start(); return tailer; } /** * Creates and starts a Tailer for the given file. * * @param file the file to follow. * @param listener the TailerListener to use. * @param delayMillis the delay between checks of the file for new content in milliseconds. * @param end Set to true to tail from the end of the file, false to tail from the beginning of the file. * @param reOpen whether to close/reopen the file between chunks * @param bufSize buffer size. * @return The new tailer */ public static Tailer create(File file, TailerListener listener, long delayMillis, boolean end, boolean reOpen, int bufSize) { Tailer tailer = new Tailer(file, listener, delayMillis, end, reOpen, bufSize); Thread thread = new Thread(tailer); thread.setDaemon(true); thread.start(); return tailer; } /** * Creates and starts a Tailer for the given file with default buffer size. * * @param file the file to follow. * @param listener the TailerListener to use. * @param delayMillis the delay between checks of the file for new content in milliseconds. * @param end Set to true to tail from the end of the file, false to tail from the beginning of the file. * @return The new tailer */ public static Tailer create(File file, TailerListener listener, long delayMillis, boolean end) { return create(file, listener, delayMillis, end, DEFAULT_BUFSIZE); } /** * Creates and starts a Tailer for the given file with default buffer size. * * @param file the file to follow. * @param listener the TailerListener to use. * @param delayMillis the delay between checks of the file for new content in milliseconds. * @param end Set to true to tail from the end of the file, false to tail from the beginning of the file. * @param reOpen whether to close/reopen the file between chunks * @return The new tailer */ public static Tailer create(File file, TailerListener listener, long delayMillis, boolean end, boolean reOpen) { return create(file, listener, delayMillis, end, reOpen, DEFAULT_BUFSIZE); } /** * Creates and starts a Tailer for the given file, starting at the beginning of the file * * @param file the file to follow. * @param listener the TailerListener to use. * @param delayMillis the delay between checks of the file for new content in milliseconds. * @return The new tailer */ public static Tailer create(File file, TailerListener listener, long delayMillis) { return create(file, listener, delayMillis, false); } /** * Creates and starts a Tailer for the given file, starting at the beginning of the file * with the default delay of 1.0s * * @param file the file to follow. * @param listener the TailerListener to use. * @return The new tailer */ public static Tailer create(File file, TailerListener listener) { return create(file, listener, DEFAULT_DELAY_MILLIS, false); } /** * Return the file. * * @return the file */ public File getFile() { return file; } /** * Return the delay in milliseconds. * * @return the delay in milliseconds. */ public long getDelay() { return delayMillis; } /** * Follows changes in the file, calling the TailerListener's handle method for each new line. */ public void run() { RandomAccessFile reader = null; try { long last = 0; // The last time the file was checked for changes long position = 0; // position within the file // Open the file while (run && reader == null) { try { reader = new RandomAccessFile(file, RAF_MODE); } catch (FileNotFoundException e) { listener.fileNotFound(); } if (reader == null) { try { Thread.sleep(delayMillis); } catch (InterruptedException e) { } } else { // The current position in the file position = end ? file.length() : 0; last = System.currentTimeMillis(); reader.seek(position); } } while (run) { boolean newer = FileUtils.isFileNewer(file, last); // IO-279, must be done first // Check the file length to see if it was rotated long length = file.length(); if (length < position) { // File was rotated listener.fileRotated(); // Reopen the reader after rotation try { // Ensure that the old file is closed iff we re-open it successfully RandomAccessFile save = reader; reader = new RandomAccessFile(file, RAF_MODE); position = 0; // close old file explicitly rather than relying on GC picking up previous RAF IOUtils.closeQuietly(save); } catch (FileNotFoundException e) { // in this case we continue to use the previous reader and position values listener.fileNotFound(); } continue; } else { // File was not rotated // See if the file needs to be read again if (length > position) { // The file has more content than it did last time position = readLines(reader); last = System.currentTimeMillis(); } else if (newer) { /* * This can happen if the file is truncated or overwritten with the exact same length of * information. In cases like this, the file position needs to be reset */ position = 0; reader.seek(position); // cannot be null here // Now we can read new lines position = readLines(reader); last = System.currentTimeMillis(); } } if (reOpen) { IOUtils.closeQuietly(reader); } try { Thread.sleep(delayMillis); } catch (InterruptedException e) { } if (run && reOpen) { reader = new RandomAccessFile(file, RAF_MODE); reader.seek(position); } } } catch (Exception e) { listener.handle(e); } finally { IOUtils.closeQuietly(reader); } } /** * Allows the tailer to complete its current loop and return. */ public void stop() { this.run = false; } /** * Read new lines. * * @param reader The file to read * @return The new position after the lines have been read * @throws java.io.IOException if an I/O error occurs. */ private long readLines(RandomAccessFile reader) throws IOException { StringBuilder sb = new StringBuilder(); long pos = reader.getFilePointer(); long rePos = pos; // position to re-read int num; boolean seenCR = false; while (run && ((num = reader.read(inbuf)) != -1)) { for (int i = 0; i < num; i++) { byte ch = inbuf[i]; switch (ch) { case '\n': seenCR = false; // swallow CR before LF listener.handle(sb.toString()); sb.setLength(0); rePos = pos + i + 1; break; case '\r': if (seenCR) { sb.append('\r'); } seenCR = true; break; default: if (seenCR) { seenCR = false; // swallow final CR listener.handle(sb.toString()); sb.setLength(0); rePos = pos + i + 1; } sb.append((char) ch); // add character, not its ascii value } } pos = reader.getFilePointer(); } reader.seek(rePos); // Ensure we can re-read if necessary return rePos; } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/input/AutoCloseInputStream.java0000644000175000017500000000644612125050425032164 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import java.io.IOException; import java.io.InputStream; /** * Proxy stream that closes and discards the underlying stream as soon as the * end of input has been reached or when the stream is explicitly closed. * Not even a reference to the underlying stream is kept after it has been * closed, so any allocated in-memory buffers can be freed even if the * client application still keeps a reference to the proxy stream. *

* This class is typically used to release any resources related to an open * stream as soon as possible even if the client application (by not explicitly * closing the stream when no longer needed) or the underlying stream (by not * releasing resources once the last byte has been read) do not do that. * * @version $Id: AutoCloseInputStream.java 1304052 2012-03-22 20:55:29Z ggregory $ * @since 1.4 */ public class AutoCloseInputStream extends ProxyInputStream { /** * Creates an automatically closing proxy for the given input stream. * * @param in underlying input stream */ public AutoCloseInputStream(InputStream in) { super(in); } /** * Closes the underlying input stream and replaces the reference to it * with a {@link ClosedInputStream} instance. *

* This method is automatically called by the read methods when the end * of input has been reached. *

* Note that it is safe to call this method any number of times. The original * underlying input stream is closed and discarded only once when this * method is first called. * * @throws IOException if the underlying input stream can not be closed */ @Override public void close() throws IOException { in.close(); in = new ClosedInputStream(); } /** * Automatically closes the stream if the end of stream was reached. * * @param n number of bytes read, or -1 if no more bytes are available * @throws IOException if the stream could not be closed * @since 2.0 */ @Override protected void afterRead(int n) throws IOException { if (n == -1) { close(); } } /** * Ensures that the stream is closed before it gets garbage-collected. * As mentioned in {@link #close()}, this is a no-op if the stream has * already been closed. * @throws Throwable if an error occurs */ @Override protected void finalize() throws Throwable { close(); super.finalize(); } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/input/CloseShieldInputStream.java0000644000175000017500000000347212125050425032460 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import java.io.InputStream; /** * Proxy stream that prevents the underlying input stream from being closed. *

* This class is typically used in cases where an input stream needs to be * passed to a component that wants to explicitly close the stream even if * more input would still be available to other components. * * @version $Id: CloseShieldInputStream.java 1304052 2012-03-22 20:55:29Z ggregory $ * @since 1.4 */ public class CloseShieldInputStream extends ProxyInputStream { /** * Creates a proxy that shields the given input stream from being * closed. * * @param in underlying input stream */ public CloseShieldInputStream(InputStream in) { super(in); } /** * Replaces the underlying input stream with a {@link ClosedInputStream} * sentinel. The original input stream will remain open, but this proxy * will appear closed. */ @Override public void close() { in = new ClosedInputStream(); } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/input/XmlStreamReaderException.java0000644000175000017500000001071612125050425033003 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import java.io.IOException; /** * The XmlStreamReaderException is thrown by the XmlStreamReader constructors if * the charset encoding can not be determined according to the XML 1.0 * specification and RFC 3023. *

* The exception returns the unconsumed InputStream to allow the application to * do an alternate processing with the stream. Note that the original * InputStream given to the XmlStreamReader cannot be used as that one has been * already read. * * @version $Id: XmlStreamReaderException.java 1304052 2012-03-22 20:55:29Z ggregory $ * @since 2.0 */ public class XmlStreamReaderException extends IOException { private static final long serialVersionUID = 1L; private final String bomEncoding; private final String xmlGuessEncoding; private final String xmlEncoding; private final String contentTypeMime; private final String contentTypeEncoding; /** * Creates an exception instance if the charset encoding could not be * determined. *

* Instances of this exception are thrown by the XmlStreamReader. * * @param msg message describing the reason for the exception. * @param bomEnc BOM encoding. * @param xmlGuessEnc XML guess encoding. * @param xmlEnc XML prolog encoding. */ public XmlStreamReaderException(String msg, String bomEnc, String xmlGuessEnc, String xmlEnc) { this(msg, null, null, bomEnc, xmlGuessEnc, xmlEnc); } /** * Creates an exception instance if the charset encoding could not be * determined. *

* Instances of this exception are thrown by the XmlStreamReader. * * @param msg message describing the reason for the exception. * @param ctMime MIME type in the content-type. * @param ctEnc encoding in the content-type. * @param bomEnc BOM encoding. * @param xmlGuessEnc XML guess encoding. * @param xmlEnc XML prolog encoding. */ public XmlStreamReaderException(String msg, String ctMime, String ctEnc, String bomEnc, String xmlGuessEnc, String xmlEnc) { super(msg); contentTypeMime = ctMime; contentTypeEncoding = ctEnc; bomEncoding = bomEnc; xmlGuessEncoding = xmlGuessEnc; xmlEncoding = xmlEnc; } /** * Returns the BOM encoding found in the InputStream. * * @return the BOM encoding, null if none. */ public String getBomEncoding() { return bomEncoding; } /** * Returns the encoding guess based on the first bytes of the InputStream. * * @return the encoding guess, null if it couldn't be guessed. */ public String getXmlGuessEncoding() { return xmlGuessEncoding; } /** * Returns the encoding found in the XML prolog of the InputStream. * * @return the encoding of the XML prolog, null if none. */ public String getXmlEncoding() { return xmlEncoding; } /** * Returns the MIME type in the content-type used to attempt determining the * encoding. * * @return the MIME type in the content-type, null if there was not * content-type or the encoding detection did not involve HTTP. */ public String getContentTypeMime() { return contentTypeMime; } /** * Returns the encoding in the content-type used to attempt determining the * encoding. * * @return the encoding in the content-type, null if there was not * content-type, no encoding in it or the encoding detection did not * involve HTTP. */ public String getContentTypeEncoding() { return contentTypeEncoding; } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/input/BOMInputStream.java0000644000175000017500000003156612125050425030704 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Comparator; import java.util.List; import org.apache.commons.io.ByteOrderMark; /** * This class is used to wrap a stream that includes an encoded {@link ByteOrderMark} as its first bytes. * * This class detects these bytes and, if required, can automatically skip them and return the subsequent byte as the * first byte in the stream. * * The {@link ByteOrderMark} implementation has the following pre-defined BOMs: *

    *
  • UTF-8 - {@link ByteOrderMark#UTF_8}
  • *
  • UTF-16BE - {@link ByteOrderMark#UTF_16LE}
  • *
  • UTF-16LE - {@link ByteOrderMark#UTF_16BE}
  • *
  • UTF-32BE - {@link ByteOrderMark#UTF_32LE}
  • *
  • UTF-32LE - {@link ByteOrderMark#UTF_32BE}
  • *
* * *

Example 1 - Detect and exclude a UTF-8 BOM

* *
 * BOMInputStream bomIn = new BOMInputStream(in);
 * if (bomIn.hasBOM()) {
 *     // has a UTF-8 BOM
 * }
 * 
* *

Example 2 - Detect a UTF-8 BOM (but don't exclude it)

* *
 * boolean include = true;
 * BOMInputStream bomIn = new BOMInputStream(in, include);
 * if (bomIn.hasBOM()) {
 *     // has a UTF-8 BOM
 * }
 * 
* *

Example 3 - Detect Multiple BOMs

* *
 * BOMInputStream bomIn = new BOMInputStream(in, 
 *   ByteOrderMark.UTF_16LE, ByteOrderMark.UTF_16BE,
 *   ByteOrderMark.UTF_32LE, ByteOrderMark.UTF_32BE
 *   );
 * if (bomIn.hasBOM() == false) {
 *     // No BOM found
 * } else if (bomIn.hasBOM(ByteOrderMark.UTF_16LE)) {
 *     // has a UTF-16LE BOM
 * } else if (bomIn.hasBOM(ByteOrderMark.UTF_16BE)) {
 *     // has a UTF-16BE BOM
 * } else if (bomIn.hasBOM(ByteOrderMark.UTF_32LE)) {
 *     // has a UTF-32LE BOM
 * } else if (bomIn.hasBOM(ByteOrderMark.UTF_32BE)) {
 *     // has a UTF-32BE BOM
 * }
 * 
* * @see org.apache.commons.io.ByteOrderMark * @see Wikipedia - Byte Order Mark * @version $Id: BOMInputStream.java 1346400 2012-06-05 14:48:01Z ggregory $ * @since 2.0 */ public class BOMInputStream extends ProxyInputStream { private final boolean include; /** * BOMs are sorted from longest to shortest. */ private final List boms; private ByteOrderMark byteOrderMark; private int[] firstBytes; private int fbLength; private int fbIndex; private int markFbIndex; private boolean markedAtStart; /** * Constructs a new BOM InputStream that excludes a {@link ByteOrderMark#UTF_8} BOM. * * @param delegate * the InputStream to delegate to */ public BOMInputStream(InputStream delegate) { this(delegate, false, ByteOrderMark.UTF_8); } /** * Constructs a new BOM InputStream that detects a a {@link ByteOrderMark#UTF_8} and optionally includes it. * * @param delegate * the InputStream to delegate to * @param include * true to include the UTF-8 BOM or false to exclude it */ public BOMInputStream(InputStream delegate, boolean include) { this(delegate, include, ByteOrderMark.UTF_8); } /** * Constructs a new BOM InputStream that excludes the specified BOMs. * * @param delegate * the InputStream to delegate to * @param boms * The BOMs to detect and exclude */ public BOMInputStream(InputStream delegate, ByteOrderMark... boms) { this(delegate, false, boms); } /** * Compares ByteOrderMark objects in descending length order. */ private static final Comparator ByteOrderMarkLengthComparator = new Comparator() { public int compare(ByteOrderMark bom1, ByteOrderMark bom2) { int len1 = bom1.length(); int len2 = bom2.length(); if (len1 > len2) { return -1; } if (len2 > len1) { return 1; } return 0; } }; /** * Constructs a new BOM InputStream that detects the specified BOMs and optionally includes them. * * @param delegate * the InputStream to delegate to * @param include * true to include the specified BOMs or false to exclude them * @param boms * The BOMs to detect and optionally exclude */ public BOMInputStream(InputStream delegate, boolean include, ByteOrderMark... boms) { super(delegate); if (boms == null || boms.length == 0) { throw new IllegalArgumentException("No BOMs specified"); } this.include = include; // Sort the BOMs to match the longest BOM first because some BOMs have the same starting two bytes. Arrays.sort(boms, ByteOrderMarkLengthComparator); this.boms = Arrays.asList(boms); } /** * Indicates whether the stream contains one of the specified BOMs. * * @return true if the stream has one of the specified BOMs, otherwise false if it does not * @throws IOException * if an error reading the first bytes of the stream occurs */ public boolean hasBOM() throws IOException { return getBOM() != null; } /** * Indicates whether the stream contains the specified BOM. * * @param bom * The BOM to check for * @return true if the stream has the specified BOM, otherwise false if it does not * @throws IllegalArgumentException * if the BOM is not one the stream is configured to detect * @throws IOException * if an error reading the first bytes of the stream occurs */ public boolean hasBOM(ByteOrderMark bom) throws IOException { if (!boms.contains(bom)) { throw new IllegalArgumentException("Stream not configure to detect " + bom); } return byteOrderMark != null && getBOM().equals(bom); } /** * Return the BOM (Byte Order Mark). * * @return The BOM or null if none * @throws IOException * if an error reading the first bytes of the stream occurs */ public ByteOrderMark getBOM() throws IOException { if (firstBytes == null) { fbLength = 0; // BOMs are sorted from longest to shortest final int maxBomSize = boms.get(0).length(); firstBytes = new int[maxBomSize]; // Read first maxBomSize bytes for (int i = 0; i < firstBytes.length; i++) { firstBytes[i] = in.read(); fbLength++; if (firstBytes[i] < 0) { break; } } // match BOM in firstBytes byteOrderMark = find(); if (byteOrderMark != null) { if (!include) { if (byteOrderMark.length() < firstBytes.length) { fbIndex = byteOrderMark.length(); } else { fbLength = 0; } } } } return byteOrderMark; } /** * Return the BOM charset Name - {@link ByteOrderMark#getCharsetName()}. * * @return The BOM charset Name or null if no BOM found * @throws IOException * if an error reading the first bytes of the stream occurs * */ public String getBOMCharsetName() throws IOException { getBOM(); return byteOrderMark == null ? null : byteOrderMark.getCharsetName(); } /** * This method reads and either preserves or skips the first bytes in the stream. It behaves like the single-byte * read() method, either returning a valid byte or -1 to indicate that the initial bytes have been * processed already. * * @return the byte read (excluding BOM) or -1 if the end of stream * @throws IOException * if an I/O error occurs */ private int readFirstBytes() throws IOException { getBOM(); return fbIndex < fbLength ? firstBytes[fbIndex++] : -1; } /** * Find a BOM with the specified bytes. * * @return The matched BOM or null if none matched */ private ByteOrderMark find() { for (ByteOrderMark bom : boms) { if (matches(bom)) { return bom; } } return null; } /** * Check if the bytes match a BOM. * * @param bom * The BOM * @return true if the bytes match the bom, otherwise false */ private boolean matches(ByteOrderMark bom) { // if (bom.length() != fbLength) { // return false; // } // firstBytes may be bigger than the BOM bytes for (int i = 0; i < bom.length(); i++) { if (bom.get(i) != firstBytes[i]) { return false; } } return true; } // ---------------------------------------------------------------------------- // Implementation of InputStream // ---------------------------------------------------------------------------- /** * Invokes the delegate's read() method, detecting and optionally skipping BOM. * * @return the byte read (excluding BOM) or -1 if the end of stream * @throws IOException * if an I/O error occurs */ @Override public int read() throws IOException { int b = readFirstBytes(); return b >= 0 ? b : in.read(); } /** * Invokes the delegate's read(byte[], int, int) method, detecting and optionally skipping BOM. * * @param buf * the buffer to read the bytes into * @param off * The start offset * @param len * The number of bytes to read (excluding BOM) * @return the number of bytes read or -1 if the end of stream * @throws IOException * if an I/O error occurs */ @Override public int read(byte[] buf, int off, int len) throws IOException { int firstCount = 0; int b = 0; while (len > 0 && b >= 0) { b = readFirstBytes(); if (b >= 0) { buf[off++] = (byte) (b & 0xFF); len--; firstCount++; } } int secondCount = in.read(buf, off, len); return secondCount < 0 ? firstCount > 0 ? firstCount : -1 : firstCount + secondCount; } /** * Invokes the delegate's read(byte[]) method, detecting and optionally skipping BOM. * * @param buf * the buffer to read the bytes into * @return the number of bytes read (excluding BOM) or -1 if the end of stream * @throws IOException * if an I/O error occurs */ @Override public int read(byte[] buf) throws IOException { return read(buf, 0, buf.length); } /** * Invokes the delegate's mark(int) method. * * @param readlimit * read ahead limit */ @Override public synchronized void mark(int readlimit) { markFbIndex = fbIndex; markedAtStart = firstBytes == null; in.mark(readlimit); } /** * Invokes the delegate's reset() method. * * @throws IOException * if an I/O error occurs */ @Override public synchronized void reset() throws IOException { fbIndex = markFbIndex; if (markedAtStart) { firstBytes = null; } in.reset(); } /** * Invokes the delegate's skip(long) method, detecting and optionallyskipping BOM. * * @param n * the number of bytes to skip * @return the number of bytes to skipped or -1 if the end of stream * @throws IOException * if an I/O error occurs */ @Override public long skip(long n) throws IOException { while (n > 0 && readFirstBytes() >= 0) { n--; } return in.skip(n); } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/input/NullInputStream.java0000644000175000017500000002474512125050425031202 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; /** * A functional, light weight {@link InputStream} that emulates * a stream of a specified size. *

* This implementation provides a light weight * object for testing with an {@link InputStream} * where the contents don't matter. *

* One use case would be for testing the handling of * large {@link InputStream} as it can emulate that * scenario without the overhead of actually processing * large numbers of bytes - significantly speeding up * test execution times. *

* This implementation returns zero from the method that * reads a byte and leaves the array unchanged in the read * methods that are passed a byte array. * If alternative data is required the processByte() and * processBytes() methods can be implemented to generate * data, for example: * *

 *  public class TestInputStream extends NullInputStream {
 *      public TestInputStream(int size) {
 *          super(size);
 *      }
 *      protected int processByte() {
 *          return ... // return required value here
 *      }
 *      protected void processBytes(byte[] bytes, int offset, int length) {
 *          for (int i = offset; i < length; i++) {
 *              bytes[i] = ... // set array value here
 *          }
 *      }
 *  }
 * 
* * @since 1.3 * @version $Id: NullInputStream.java 1307462 2012-03-30 15:13:11Z ggregory $ */ public class NullInputStream extends InputStream { private final long size; private long position; private long mark = -1; private long readlimit; private boolean eof; private final boolean throwEofException; private final boolean markSupported; /** * Create an {@link InputStream} that emulates a specified size * which supports marking and does not throw EOFException. * * @param size The size of the input stream to emulate. */ public NullInputStream(long size) { this(size, true, false); } /** * Create an {@link InputStream} that emulates a specified * size with option settings. * * @param size The size of the input stream to emulate. * @param markSupported Whether this instance will support * the mark() functionality. * @param throwEofException Whether this implementation * will throw an {@link EOFException} or return -1 when the * end of file is reached. */ public NullInputStream(long size, boolean markSupported, boolean throwEofException) { this.size = size; this.markSupported = markSupported; this.throwEofException = throwEofException; } /** * Return the current position. * * @return the current position. */ public long getPosition() { return position; } /** * Return the size this {@link InputStream} emulates. * * @return The size of the input stream to emulate. */ public long getSize() { return size; } /** * Return the number of bytes that can be read. * * @return The number of bytes that can be read. */ @Override public int available() { long avail = size - position; if (avail <= 0) { return 0; } else if (avail > Integer.MAX_VALUE) { return Integer.MAX_VALUE; } else { return (int)avail; } } /** * Close this input stream - resets the internal state to * the initial values. * * @throws IOException If an error occurs. */ @Override public void close() throws IOException { eof = false; position = 0; mark = -1; } /** * Mark the current position. * * @param readlimit The number of bytes before this marked position * is invalid. * @throws UnsupportedOperationException if mark is not supported. */ @Override public synchronized void mark(int readlimit) { if (!markSupported) { throw new UnsupportedOperationException("Mark not supported"); } mark = position; this.readlimit = readlimit; } /** * Indicates whether mark is supported. * * @return Whether mark is supported or not. */ @Override public boolean markSupported() { return markSupported; } /** * Read a byte. * * @return Either The byte value returned by processByte() * or -1 if the end of file has been reached and * throwEofException is set to {@code false}. * @throws EOFException if the end of file is reached and * throwEofException is set to {@code true}. * @throws IOException if trying to read past the end of file. */ @Override public int read() throws IOException { if (eof) { throw new IOException("Read after end of file"); } if (position == size) { return doEndOfFile(); } position++; return processByte(); } /** * Read some bytes into the specified array. * * @param bytes The byte array to read into * @return The number of bytes read or -1 * if the end of file has been reached and * throwEofException is set to {@code false}. * @throws EOFException if the end of file is reached and * throwEofException is set to {@code true}. * @throws IOException if trying to read past the end of file. */ @Override public int read(byte[] bytes) throws IOException { return read(bytes, 0, bytes.length); } /** * Read the specified number bytes into an array. * * @param bytes The byte array to read into. * @param offset The offset to start reading bytes into. * @param length The number of bytes to read. * @return The number of bytes read or -1 * if the end of file has been reached and * throwEofException is set to {@code false}. * @throws EOFException if the end of file is reached and * throwEofException is set to {@code true}. * @throws IOException if trying to read past the end of file. */ @Override public int read(byte[] bytes, int offset, int length) throws IOException { if (eof) { throw new IOException("Read after end of file"); } if (position == size) { return doEndOfFile(); } position += length; int returnLength = length; if (position > size) { returnLength = length - (int)(position - size); position = size; } processBytes(bytes, offset, returnLength); return returnLength; } /** * Reset the stream to the point when mark was last called. * * @throws UnsupportedOperationException if mark is not supported. * @throws IOException If no position has been marked * or the read limit has been exceed since the last position was * marked. */ @Override public synchronized void reset() throws IOException { if (!markSupported) { throw new UnsupportedOperationException("Mark not supported"); } if (mark < 0) { throw new IOException("No position has been marked"); } if (position > mark + readlimit) { throw new IOException("Marked position [" + mark + "] is no longer valid - passed the read limit [" + readlimit + "]"); } position = mark; eof = false; } /** * Skip a specified number of bytes. * * @param numberOfBytes The number of bytes to skip. * @return The number of bytes skipped or -1 * if the end of file has been reached and * throwEofException is set to {@code false}. * @throws EOFException if the end of file is reached and * throwEofException is set to {@code true}. * @throws IOException if trying to read past the end of file. */ @Override public long skip(long numberOfBytes) throws IOException { if (eof) { throw new IOException("Skip after end of file"); } if (position == size) { return doEndOfFile(); } position += numberOfBytes; long returnLength = numberOfBytes; if (position > size) { returnLength = numberOfBytes - (position - size); position = size; } return returnLength; } /** * Return a byte value for the read() method. *

* This implementation returns zero. * * @return This implementation always returns zero. */ protected int processByte() { // do nothing - overridable by subclass return 0; } /** * Process the bytes for the read(byte[], offset, length) * method. *

* This implementation leaves the byte array unchanged. * * @param bytes The byte array * @param offset The offset to start at. * @param length The number of bytes. */ protected void processBytes(byte[] bytes, int offset, int length) { // do nothing - overridable by subclass } /** * Handle End of File. * * @return -1 if throwEofException is * set to {@code false} * @throws EOFException if throwEofException is set * to {@code true}. */ private int doEndOfFile() throws EOFException { eof = true; if (throwEofException) { throw new EOFException(); } return -1; } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/input/ClassLoaderObjectInputStream.javalibcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/input/ClassLoaderObjectInputStream.j0000644000175000017500000000764312125050425033121 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectStreamClass; import java.io.StreamCorruptedException; import java.lang.reflect.Proxy; /** * A special ObjectInputStream that loads a class based on a specified * ClassLoader rather than the system default. *

* This is useful in dynamic container environments. * * @version $Id: ClassLoaderObjectInputStream.java 1304052 2012-03-22 20:55:29Z ggregory $ * @since 1.1 */ public class ClassLoaderObjectInputStream extends ObjectInputStream { /** The class loader to use. */ private final ClassLoader classLoader; /** * Constructs a new ClassLoaderObjectInputStream. * * @param classLoader the ClassLoader from which classes should be loaded * @param inputStream the InputStream to work on * @throws IOException in case of an I/O error * @throws StreamCorruptedException if the stream is corrupted */ public ClassLoaderObjectInputStream( ClassLoader classLoader, InputStream inputStream) throws IOException, StreamCorruptedException { super(inputStream); this.classLoader = classLoader; } /** * Resolve a class specified by the descriptor using the * specified ClassLoader or the super ClassLoader. * * @param objectStreamClass descriptor of the class * @return the Class object described by the ObjectStreamClass * @throws IOException in case of an I/O error * @throws ClassNotFoundException if the Class cannot be found */ @Override protected Class resolveClass(ObjectStreamClass objectStreamClass) throws IOException, ClassNotFoundException { Class clazz = Class.forName(objectStreamClass.getName(), false, classLoader); if (clazz != null) { // the classloader knows of the class return clazz; } else { // classloader knows not of class, let the super classloader do it return super.resolveClass(objectStreamClass); } } /** * Create a proxy class that implements the specified interfaces using * the specified ClassLoader or the super ClassLoader. * * @param interfaces the interfaces to implement * @return a proxy class implementing the interfaces * @throws IOException in case of an I/O error * @throws ClassNotFoundException if the Class cannot be found * @see java.io.ObjectInputStream#resolveProxyClass(java.lang.String[]) * @since 2.1 */ @Override protected Class resolveProxyClass(String[] interfaces) throws IOException, ClassNotFoundException { Class[] interfaceClasses = new Class[interfaces.length]; for (int i = 0; i < interfaces.length; i++) { interfaceClasses[i] = Class.forName(interfaces[i], false, classLoader); } try { return Proxy.getProxyClass(classLoader, interfaceClasses); } catch (IllegalArgumentException e) { return super.resolveProxyClass(interfaces); } } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/input/package.html0000644000175000017500000000172612125050425027504 0ustar ebourgebourg

This package provides implementations of input classes, such as InputStream and Reader.

libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/input/ReaderInputStream.java0000644000175000017500000002605512125050425031466 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.input; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import java.nio.charset.CoderResult; import java.nio.charset.CodingErrorAction; /** * {@link InputStream} implementation that reads a character stream from a {@link Reader} * and transforms it to a byte stream using a specified charset encoding. The stream * is transformed using a {@link CharsetEncoder} object, guaranteeing that all charset * encodings supported by the JRE are handled correctly. In particular for charsets such as * UTF-16, the implementation ensures that one and only one byte order marker * is produced. *

* Since in general it is not possible to predict the number of characters to be read from the * {@link Reader} to satisfy a read request on the {@link ReaderInputStream}, all reads from * the {@link Reader} are buffered. There is therefore no well defined correlation * between the current position of the {@link Reader} and that of the {@link ReaderInputStream}. * This also implies that in general there is no need to wrap the underlying {@link Reader} * in a {@link java.io.BufferedReader}. *

* {@link ReaderInputStream} implements the inverse transformation of {@link java.io.InputStreamReader}; * in the following example, reading from in2 would return the same byte * sequence as reading from in (provided that the initial byte sequence is legal * with respect to the charset encoding): *

 * InputStream in = ...
 * Charset cs = ...
 * InputStreamReader reader = new InputStreamReader(in, cs);
 * ReaderInputStream in2 = new ReaderInputStream(reader, cs);
* {@link ReaderInputStream} implements the same transformation as {@link java.io.OutputStreamWriter}, * except that the control flow is reversed: both classes transform a character stream * into a byte stream, but {@link java.io.OutputStreamWriter} pushes data to the underlying stream, * while {@link ReaderInputStream} pulls it from the underlying stream. *

* Note that while there are use cases where there is no alternative to using * this class, very often the need to use this class is an indication of a flaw * in the design of the code. This class is typically used in situations where an existing * API only accepts an {@link InputStream}, but where the most natural way to produce the data * is as a character stream, i.e. by providing a {@link Reader} instance. An example of a situation * where this problem may appear is when implementing the {@link javax.activation.DataSource} * interface from the Java Activation Framework. *

* Given the fact that the {@link Reader} class doesn't provide any way to predict whether the next * read operation will block or not, it is not possible to provide a meaningful * implementation of the {@link InputStream#available()} method. A call to this method * will always return 0. Also, this class doesn't support {@link InputStream#mark(int)}. *

* Instances of {@link ReaderInputStream} are not thread safe. * * @see org.apache.commons.io.output.WriterOutputStream * * @since 2.0 */ public class ReaderInputStream extends InputStream { private static final int DEFAULT_BUFFER_SIZE = 1024; private final Reader reader; private final CharsetEncoder encoder; /** * CharBuffer used as input for the decoder. It should be reasonably * large as we read data from the underlying Reader into this buffer. */ private final CharBuffer encoderIn; /** * ByteBuffer used as output for the decoder. This buffer can be small * as it is only used to transfer data from the decoder to the * buffer provided by the caller. */ private final ByteBuffer encoderOut; private CoderResult lastCoderResult; private boolean endOfInput; /** * Construct a new {@link ReaderInputStream}. * * @param reader the target {@link Reader} * @param encoder the charset encoder * @since 2.1 */ public ReaderInputStream(Reader reader, CharsetEncoder encoder) { this(reader, encoder, DEFAULT_BUFFER_SIZE); } /** * Construct a new {@link ReaderInputStream}. * * @param reader the target {@link Reader} * @param encoder the charset encoder * @param bufferSize the size of the input buffer in number of characters * @since 2.1 */ public ReaderInputStream(Reader reader, CharsetEncoder encoder, int bufferSize) { this.reader = reader; this.encoder = encoder; this.encoderIn = CharBuffer.allocate(bufferSize); this.encoderIn.flip(); this.encoderOut = ByteBuffer.allocate(128); this.encoderOut.flip(); } /** * Construct a new {@link ReaderInputStream}. * * @param reader the target {@link Reader} * @param charset the charset encoding * @param bufferSize the size of the input buffer in number of characters */ public ReaderInputStream(Reader reader, Charset charset, int bufferSize) { this(reader, charset.newEncoder() .onMalformedInput(CodingErrorAction.REPLACE) .onUnmappableCharacter(CodingErrorAction.REPLACE), bufferSize); } /** * Construct a new {@link ReaderInputStream} with a default input buffer size of * 1024 characters. * * @param reader the target {@link Reader} * @param charset the charset encoding */ public ReaderInputStream(Reader reader, Charset charset) { this(reader, charset, DEFAULT_BUFFER_SIZE); } /** * Construct a new {@link ReaderInputStream}. * * @param reader the target {@link Reader} * @param charsetName the name of the charset encoding * @param bufferSize the size of the input buffer in number of characters */ public ReaderInputStream(Reader reader, String charsetName, int bufferSize) { this(reader, Charset.forName(charsetName), bufferSize); } /** * Construct a new {@link ReaderInputStream} with a default input buffer size of * 1024 characters. * * @param reader the target {@link Reader} * @param charsetName the name of the charset encoding */ public ReaderInputStream(Reader reader, String charsetName) { this(reader, charsetName, DEFAULT_BUFFER_SIZE); } /** * Construct a new {@link ReaderInputStream} that uses the default character encoding * with a default input buffer size of 1024 characters. * * @param reader the target {@link Reader} */ public ReaderInputStream(Reader reader) { this(reader, Charset.defaultCharset()); } /** * Fills the internal char buffer from the reader. * * @throws IOException * If an I/O error occurs */ private void fillBuffer() throws IOException { if (!endOfInput && (lastCoderResult == null || lastCoderResult.isUnderflow())) { encoderIn.compact(); int position = encoderIn.position(); // We don't use Reader#read(CharBuffer) here because it is more efficient // to write directly to the underlying char array (the default implementation // copies data to a temporary char array). int c = reader.read(encoderIn.array(), position, encoderIn.remaining()); if (c == -1) { endOfInput = true; } else { encoderIn.position(position+c); } encoderIn.flip(); } encoderOut.compact(); lastCoderResult = encoder.encode(encoderIn, encoderOut, endOfInput); encoderOut.flip(); } /** * Read the specified number of bytes into an array. * * @param b the byte array to read into * @param off the offset to start reading bytes into * @param len the number of bytes to read * @return the number of bytes read or -1 * if the end of the stream has been reached * @throws IOException if an I/O error occurs */ @Override public int read(byte[] b, int off, int len) throws IOException { if (b == null) { throw new NullPointerException("Byte array must not be null"); } if (len < 0 || off < 0 || (off + len) > b.length) { throw new IndexOutOfBoundsException("Array Size=" + b.length + ", offset=" + off + ", length=" + len); } int read = 0; if (len == 0) { return 0; // Always return 0 if len == 0 } while (len > 0) { if (encoderOut.hasRemaining()) { int c = Math.min(encoderOut.remaining(), len); encoderOut.get(b, off, c); off += c; len -= c; read += c; } else { fillBuffer(); if (endOfInput && !encoderOut.hasRemaining()) { break; } } } return read == 0 && endOfInput ? -1 : read; } /** * Read the specified number of bytes into an array. * * @param b the byte array to read into * @return the number of bytes read or -1 * if the end of the stream has been reached * @throws IOException if an I/O error occurs */ @Override public int read(byte[] b) throws IOException { return read(b, 0, b.length); } /** * Read a single byte. * * @return either the byte read or -1 if the end of the stream * has been reached * @throws IOException if an I/O error occurs */ @Override public int read() throws IOException { for (;;) { if (encoderOut.hasRemaining()) { return encoderOut.get() & 0xFF; } else { fillBuffer(); if (endOfInput && !encoderOut.hasRemaining()) { return -1; } } } } /** * Close the stream. This method will cause the underlying {@link Reader} * to be closed. * @throws IOException if an I/O error occurs */ @Override public void close() throws IOException { reader.close(); } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/IOCase.java0000644000175000017500000002207612125050425026033 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.io.Serializable; /** * Enumeration of IO case sensitivity. *

* Different filing systems have different rules for case-sensitivity. * Windows is case-insensitive, Unix is case-sensitive. *

* This class captures that difference, providing an enumeration to * control how filename comparisons should be performed. It also provides * methods that use the enumeration to perform comparisons. *

* Wherever possible, you should use the check methods in this * class to compare filenames. * * @version $Id: IOCase.java 1307459 2012-03-30 15:11:44Z ggregory $ * @since 1.3 */ public final class IOCase implements Serializable { /** * The constant for case sensitive regardless of operating system. */ public static final IOCase SENSITIVE = new IOCase("Sensitive", true); /** * The constant for case insensitive regardless of operating system. */ public static final IOCase INSENSITIVE = new IOCase("Insensitive", false); /** * The constant for case sensitivity determined by the current operating system. * Windows is case-insensitive when comparing filenames, Unix is case-sensitive. *

* Note: This only caters for Windows and Unix. Other operating * systems (e.g. OSX and OpenVMS) are treated as case sensitive if they use the * Unix file separator and case-insensitive if they use the Windows file separator * (see {@link java.io.File#separatorChar}). *

* If you derialize this constant of Windows, and deserialize on Unix, or vice * versa, then the value of the case-sensitivity flag will change. */ public static final IOCase SYSTEM = new IOCase("System", !FilenameUtils.isSystemWindows()); /** Serialization version. */ private static final long serialVersionUID = -6343169151696340687L; /** The enumeration name. */ private final String name; /** The sensitivity flag. */ private final transient boolean sensitive; //----------------------------------------------------------------------- /** * Factory method to create an IOCase from a name. * * @param name the name to find * @return the IOCase object * @throws IllegalArgumentException if the name is invalid */ public static IOCase forName(String name) { if (IOCase.SENSITIVE.name.equals(name)){ return IOCase.SENSITIVE; } if (IOCase.INSENSITIVE.name.equals(name)){ return IOCase.INSENSITIVE; } if (IOCase.SYSTEM.name.equals(name)){ return IOCase.SYSTEM; } throw new IllegalArgumentException("Invalid IOCase name: " + name); } //----------------------------------------------------------------------- /** * Private constructor. * * @param name the name * @param sensitive the sensitivity */ private IOCase(String name, boolean sensitive) { this.name = name; this.sensitive = sensitive; } /** * Replaces the enumeration from the stream with a real one. * This ensures that the correct flag is set for SYSTEM. * * @return the resolved object */ private Object readResolve() { return forName(name); } //----------------------------------------------------------------------- /** * Gets the name of the constant. * * @return the name of the constant */ public String getName() { return name; } /** * Does the object represent case sensitive comparison. * * @return true if case sensitive */ public boolean isCaseSensitive() { return sensitive; } //----------------------------------------------------------------------- /** * Compares two strings using the case-sensitivity rule. *

* This method mimics {@link String#compareTo} but takes case-sensitivity * into account. * * @param str1 the first string to compare, not null * @param str2 the second string to compare, not null * @return true if equal using the case rules * @throws NullPointerException if either string is null */ public int checkCompareTo(String str1, String str2) { if (str1 == null || str2 == null) { throw new NullPointerException("The strings must not be null"); } return sensitive ? str1.compareTo(str2) : str1.compareToIgnoreCase(str2); } /** * Compares two strings using the case-sensitivity rule. *

* This method mimics {@link String#equals} but takes case-sensitivity * into account. * * @param str1 the first string to compare, not null * @param str2 the second string to compare, not null * @return true if equal using the case rules * @throws NullPointerException if either string is null */ public boolean checkEquals(String str1, String str2) { if (str1 == null || str2 == null) { throw new NullPointerException("The strings must not be null"); } return sensitive ? str1.equals(str2) : str1.equalsIgnoreCase(str2); } /** * Checks if one string starts with another using the case-sensitivity rule. *

* This method mimics {@link String#startsWith(String)} but takes case-sensitivity * into account. * * @param str the string to check, not null * @param start the start to compare against, not null * @return true if equal using the case rules * @throws NullPointerException if either string is null */ public boolean checkStartsWith(String str, String start) { return str.regionMatches(!sensitive, 0, start, 0, start.length()); } /** * Checks if one string ends with another using the case-sensitivity rule. *

* This method mimics {@link String#endsWith} but takes case-sensitivity * into account. * * @param str the string to check, not null * @param end the end to compare against, not null * @return true if equal using the case rules * @throws NullPointerException if either string is null */ public boolean checkEndsWith(String str, String end) { int endLen = end.length(); return str.regionMatches(!sensitive, str.length() - endLen, end, 0, endLen); } /** * Checks if one string contains another starting at a specific index using the * case-sensitivity rule. *

* This method mimics parts of {@link String#indexOf(String, int)} * but takes case-sensitivity into account. * * @param str the string to check, not null * @param strStartIndex the index to start at in str * @param search the start to search for, not null * @return the first index of the search String, * -1 if no match or {@code null} string input * @throws NullPointerException if either string is null * @since 2.0 */ public int checkIndexOf(String str, int strStartIndex, String search) { int endIndex = str.length() - search.length(); if (endIndex >= strStartIndex) { for (int i = strStartIndex; i <= endIndex; i++) { if (checkRegionMatches(str, i, search)) { return i; } } } return -1; } /** * Checks if one string contains another at a specific index using the case-sensitivity rule. *

* This method mimics parts of {@link String#regionMatches(boolean, int, String, int, int)} * but takes case-sensitivity into account. * * @param str the string to check, not null * @param strStartIndex the index to start at in str * @param search the start to search for, not null * @return true if equal using the case rules * @throws NullPointerException if either string is null */ public boolean checkRegionMatches(String str, int strStartIndex, String search) { return str.regionMatches(!sensitive, strStartIndex, search, 0, search.length()); } //----------------------------------------------------------------------- /** * Gets a string describing the sensitivity. * * @return a string describing the sensitivity */ @Override public String toString() { return name; } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/FileExistsException.java0000644000175000017500000000326512125050425030665 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.io.File; import java.io.IOException; /** * Indicates that a file already exists. * * @version $Id: FileExistsException.java 1304052 2012-03-22 20:55:29Z ggregory $ * @since 2.0 */ public class FileExistsException extends IOException { /** * Defines the serial version UID. */ private static final long serialVersionUID = 1L; /** * Default Constructor. */ public FileExistsException() { super(); } /** * Construct an instance with the specified message. * * @param message The error message */ public FileExistsException(String message) { super(message); } /** * Construct an instance with the specified file. * * @param file The file that exists */ public FileExistsException(File file) { super("File " + file + " exists"); } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/FilenameUtils.java0000644000175000017500000015034612125050425027473 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Stack; /** * General filename and filepath manipulation utilities. *

* When dealing with filenames you can hit problems when moving from a Windows * based development machine to a Unix based production machine. * This class aims to help avoid those problems. *

* NOTE: You may be able to avoid using this class entirely simply by * using JDK {@link java.io.File File} objects and the two argument constructor * {@link java.io.File#File(java.io.File, java.lang.String) File(File,String)}. *

* Most methods on this class are designed to work the same on both Unix and Windows. * Those that don't include 'System', 'Unix' or 'Windows' in their name. *

* Most methods recognise both separators (forward and back), and both * sets of prefixes. See the javadoc of each method for details. *

* This class defines six components within a filename * (example C:\dev\project\file.txt): *

    *
  • the prefix - C:\
  • *
  • the path - dev\project\
  • *
  • the full path - C:\dev\project\
  • *
  • the name - file.txt
  • *
  • the base name - file
  • *
  • the extension - txt
  • *
* Note that this class works best if directory filenames end with a separator. * If you omit the last separator, it is impossible to determine if the filename * corresponds to a file or a directory. As a result, we have chosen to say * it corresponds to a file. *

* This class only supports Unix and Windows style names. * Prefixes are matched as follows: *

 * Windows:
 * a\b\c.txt           --> ""          --> relative
 * \a\b\c.txt          --> "\"         --> current drive absolute
 * C:a\b\c.txt         --> "C:"        --> drive relative
 * C:\a\b\c.txt        --> "C:\"       --> absolute
 * \\server\a\b\c.txt  --> "\\server\" --> UNC
 *
 * Unix:
 * a/b/c.txt           --> ""          --> relative
 * /a/b/c.txt          --> "/"         --> absolute
 * ~/a/b/c.txt         --> "~/"        --> current user
 * ~                   --> "~/"        --> current user (slash added)
 * ~user/a/b/c.txt     --> "~user/"    --> named user
 * ~user               --> "~user/"    --> named user (slash added)
 * 
* Both prefix styles are matched always, irrespective of the machine that you are * currently running on. *

* Origin of code: Excalibur, Alexandria, Tomcat, Commons-Utils. * * @version $Id: FilenameUtils.java 1307462 2012-03-30 15:13:11Z ggregory $ * @since 1.1 */ public class FilenameUtils { /** * The extension separator character. * @since 1.4 */ public static final char EXTENSION_SEPARATOR = '.'; /** * The extension separator String. * @since 1.4 */ public static final String EXTENSION_SEPARATOR_STR = Character.toString(EXTENSION_SEPARATOR); /** * The Unix separator character. */ private static final char UNIX_SEPARATOR = '/'; /** * The Windows separator character. */ private static final char WINDOWS_SEPARATOR = '\\'; /** * The system separator character. */ private static final char SYSTEM_SEPARATOR = File.separatorChar; /** * The separator character that is the opposite of the system separator. */ private static final char OTHER_SEPARATOR; static { if (isSystemWindows()) { OTHER_SEPARATOR = UNIX_SEPARATOR; } else { OTHER_SEPARATOR = WINDOWS_SEPARATOR; } } /** * Instances should NOT be constructed in standard programming. */ public FilenameUtils() { super(); } //----------------------------------------------------------------------- /** * Determines if Windows file system is in use. * * @return true if the system is Windows */ static boolean isSystemWindows() { return SYSTEM_SEPARATOR == WINDOWS_SEPARATOR; } //----------------------------------------------------------------------- /** * Checks if the character is a separator. * * @param ch the character to check * @return true if it is a separator character */ private static boolean isSeparator(char ch) { return ch == UNIX_SEPARATOR || ch == WINDOWS_SEPARATOR; } //----------------------------------------------------------------------- /** * Normalizes a path, removing double and single dot path steps. *

* This method normalizes a path to a standard format. * The input may contain separators in either Unix or Windows format. * The output will contain separators in the format of the system. *

* A trailing slash will be retained. * A double slash will be merged to a single slash (but UNC names are handled). * A single dot path segment will be removed. * A double dot will cause that path segment and the one before to be removed. * If the double dot has no parent path segment to work with, {@code null} * is returned. *

* The output will be the same on both Unix and Windows except * for the separator character. *

     * /foo//               -->   /foo/
     * /foo/./              -->   /foo/
     * /foo/../bar          -->   /bar
     * /foo/../bar/         -->   /bar/
     * /foo/../bar/../baz   -->   /baz
     * //foo//./bar         -->   /foo/bar
     * /../                 -->   null
     * ../foo               -->   null
     * foo/bar/..           -->   foo/
     * foo/../../bar        -->   null
     * foo/../bar           -->   bar
     * //server/foo/../bar  -->   //server/bar
     * //server/../bar      -->   null
     * C:\foo\..\bar        -->   C:\bar
     * C:\..\bar            -->   null
     * ~/foo/../bar/        -->   ~/bar/
     * ~/../bar             -->   null
     * 
* (Note the file separator returned will be correct for Windows/Unix) * * @param filename the filename to normalize, null returns null * @return the normalized filename, or null if invalid */ public static String normalize(String filename) { return doNormalize(filename, SYSTEM_SEPARATOR, true); } /** * Normalizes a path, removing double and single dot path steps. *

* This method normalizes a path to a standard format. * The input may contain separators in either Unix or Windows format. * The output will contain separators in the format specified. *

* A trailing slash will be retained. * A double slash will be merged to a single slash (but UNC names are handled). * A single dot path segment will be removed. * A double dot will cause that path segment and the one before to be removed. * If the double dot has no parent path segment to work with, {@code null} * is returned. *

* The output will be the same on both Unix and Windows except * for the separator character. *

     * /foo//               -->   /foo/
     * /foo/./              -->   /foo/
     * /foo/../bar          -->   /bar
     * /foo/../bar/         -->   /bar/
     * /foo/../bar/../baz   -->   /baz
     * //foo//./bar         -->   /foo/bar
     * /../                 -->   null
     * ../foo               -->   null
     * foo/bar/..           -->   foo/
     * foo/../../bar        -->   null
     * foo/../bar           -->   bar
     * //server/foo/../bar  -->   //server/bar
     * //server/../bar      -->   null
     * C:\foo\..\bar        -->   C:\bar
     * C:\..\bar            -->   null
     * ~/foo/../bar/        -->   ~/bar/
     * ~/../bar             -->   null
     * 
* The output will be the same on both Unix and Windows including * the separator character. * * @param filename the filename to normalize, null returns null * @param unixSeparator {@code true} if a unix separator should * be used or {@code false} if a windows separator should be used. * @return the normalized filename, or null if invalid * @since 2.0 */ public static String normalize(String filename, boolean unixSeparator) { char separator = unixSeparator ? UNIX_SEPARATOR : WINDOWS_SEPARATOR; return doNormalize(filename, separator, true); } //----------------------------------------------------------------------- /** * Normalizes a path, removing double and single dot path steps, * and removing any final directory separator. *

* This method normalizes a path to a standard format. * The input may contain separators in either Unix or Windows format. * The output will contain separators in the format of the system. *

* A trailing slash will be removed. * A double slash will be merged to a single slash (but UNC names are handled). * A single dot path segment will be removed. * A double dot will cause that path segment and the one before to be removed. * If the double dot has no parent path segment to work with, {@code null} * is returned. *

* The output will be the same on both Unix and Windows except * for the separator character. *

     * /foo//               -->   /foo
     * /foo/./              -->   /foo
     * /foo/../bar          -->   /bar
     * /foo/../bar/         -->   /bar
     * /foo/../bar/../baz   -->   /baz
     * //foo//./bar         -->   /foo/bar
     * /../                 -->   null
     * ../foo               -->   null
     * foo/bar/..           -->   foo
     * foo/../../bar        -->   null
     * foo/../bar           -->   bar
     * //server/foo/../bar  -->   //server/bar
     * //server/../bar      -->   null
     * C:\foo\..\bar        -->   C:\bar
     * C:\..\bar            -->   null
     * ~/foo/../bar/        -->   ~/bar
     * ~/../bar             -->   null
     * 
* (Note the file separator returned will be correct for Windows/Unix) * * @param filename the filename to normalize, null returns null * @return the normalized filename, or null if invalid */ public static String normalizeNoEndSeparator(String filename) { return doNormalize(filename, SYSTEM_SEPARATOR, false); } /** * Normalizes a path, removing double and single dot path steps, * and removing any final directory separator. *

* This method normalizes a path to a standard format. * The input may contain separators in either Unix or Windows format. * The output will contain separators in the format specified. *

* A trailing slash will be removed. * A double slash will be merged to a single slash (but UNC names are handled). * A single dot path segment will be removed. * A double dot will cause that path segment and the one before to be removed. * If the double dot has no parent path segment to work with, {@code null} * is returned. *

* The output will be the same on both Unix and Windows including * the separator character. *

     * /foo//               -->   /foo
     * /foo/./              -->   /foo
     * /foo/../bar          -->   /bar
     * /foo/../bar/         -->   /bar
     * /foo/../bar/../baz   -->   /baz
     * //foo//./bar         -->   /foo/bar
     * /../                 -->   null
     * ../foo               -->   null
     * foo/bar/..           -->   foo
     * foo/../../bar        -->   null
     * foo/../bar           -->   bar
     * //server/foo/../bar  -->   //server/bar
     * //server/../bar      -->   null
     * C:\foo\..\bar        -->   C:\bar
     * C:\..\bar            -->   null
     * ~/foo/../bar/        -->   ~/bar
     * ~/../bar             -->   null
     * 
* * @param filename the filename to normalize, null returns null * @param unixSeparator {@code true} if a unix separator should * be used or {@code false} if a windows separtor should be used. * @return the normalized filename, or null if invalid * @since 2.0 */ public static String normalizeNoEndSeparator(String filename, boolean unixSeparator) { char separator = unixSeparator ? UNIX_SEPARATOR : WINDOWS_SEPARATOR; return doNormalize(filename, separator, false); } /** * Internal method to perform the normalization. * * @param filename the filename * @param separator The separator character to use * @param keepSeparator true to keep the final separator * @return the normalized filename */ private static String doNormalize(String filename, char separator, boolean keepSeparator) { if (filename == null) { return null; } int size = filename.length(); if (size == 0) { return filename; } int prefix = getPrefixLength(filename); if (prefix < 0) { return null; } char[] array = new char[size + 2]; // +1 for possible extra slash, +2 for arraycopy filename.getChars(0, filename.length(), array, 0); // fix separators throughout char otherSeparator = separator == SYSTEM_SEPARATOR ? OTHER_SEPARATOR : SYSTEM_SEPARATOR; for (int i = 0; i < array.length; i++) { if (array[i] == otherSeparator) { array[i] = separator; } } // add extra separator on the end to simplify code below boolean lastIsDirectory = true; if (array[size - 1] != separator) { array[size++] = separator; lastIsDirectory = false; } // adjoining slashes for (int i = prefix + 1; i < size; i++) { if (array[i] == separator && array[i - 1] == separator) { System.arraycopy(array, i, array, i - 1, size - i); size--; i--; } } // dot slash for (int i = prefix + 1; i < size; i++) { if (array[i] == separator && array[i - 1] == '.' && (i == prefix + 1 || array[i - 2] == separator)) { if (i == size - 1) { lastIsDirectory = true; } System.arraycopy(array, i + 1, array, i - 1, size - i); size -=2; i--; } } // double dot slash outer: for (int i = prefix + 2; i < size; i++) { if (array[i] == separator && array[i - 1] == '.' && array[i - 2] == '.' && (i == prefix + 2 || array[i - 3] == separator)) { if (i == prefix + 2) { return null; } if (i == size - 1) { lastIsDirectory = true; } int j; for (j = i - 4 ; j >= prefix; j--) { if (array[j] == separator) { // remove b/../ from a/b/../c System.arraycopy(array, i + 1, array, j + 1, size - i); size -= i - j; i = j + 1; continue outer; } } // remove a/../ from a/../c System.arraycopy(array, i + 1, array, prefix, size - i); size -= i + 1 - prefix; i = prefix + 1; } } if (size <= 0) { // should never be less than 0 return ""; } if (size <= prefix) { // should never be less than prefix return new String(array, 0, size); } if (lastIsDirectory && keepSeparator) { return new String(array, 0, size); // keep trailing separator } return new String(array, 0, size - 1); // lose trailing separator } //----------------------------------------------------------------------- /** * Concatenates a filename to a base path using normal command line style rules. *

* The effect is equivalent to resultant directory after changing * directory to the first argument, followed by changing directory to * the second argument. *

* The first argument is the base path, the second is the path to concatenate. * The returned path is always normalized via {@link #normalize(String)}, * thus .. is handled. *

* If pathToAdd is absolute (has an absolute prefix), then * it will be normalized and returned. * Otherwise, the paths will be joined, normalized and returned. *

* The output will be the same on both Unix and Windows except * for the separator character. *

     * /foo/ + bar          -->   /foo/bar
     * /foo + bar           -->   /foo/bar
     * /foo + /bar          -->   /bar
     * /foo + C:/bar        -->   C:/bar
     * /foo + C:bar         -->   C:bar (*)
     * /foo/a/ + ../bar     -->   foo/bar
     * /foo/ + ../../bar    -->   null
     * /foo/ + /bar         -->   /bar
     * /foo/.. + /bar       -->   /bar
     * /foo + bar/c.txt     -->   /foo/bar/c.txt
     * /foo/c.txt + bar     -->   /foo/c.txt/bar (!)
     * 
* (*) Note that the Windows relative drive prefix is unreliable when * used with this method. * (!) Note that the first parameter must be a path. If it ends with a name, then * the name will be built into the concatenated path. If this might be a problem, * use {@link #getFullPath(String)} on the base path argument. * * @param basePath the base path to attach to, always treated as a path * @param fullFilenameToAdd the filename (or path) to attach to the base * @return the concatenated path, or null if invalid */ public static String concat(String basePath, String fullFilenameToAdd) { int prefix = getPrefixLength(fullFilenameToAdd); if (prefix < 0) { return null; } if (prefix > 0) { return normalize(fullFilenameToAdd); } if (basePath == null) { return null; } int len = basePath.length(); if (len == 0) { return normalize(fullFilenameToAdd); } char ch = basePath.charAt(len - 1); if (isSeparator(ch)) { return normalize(basePath + fullFilenameToAdd); } else { return normalize(basePath + '/' + fullFilenameToAdd); } } /** * Determines whether the {@code parent} directory contains the {@code child} element (a file or directory). *

* The files names are expected to be normalized. *

* * Edge cases: *
    *
  • A {@code directory} must not be null: if null, throw IllegalArgumentException
  • *
  • A directory does not contain itself: return false
  • *
  • A null child file is not contained in any parent: return false
  • *
* * @param canonicalParent * the file to consider as the parent. * @param canonicalChild * the file to consider as the child. * @return true is the candidate leaf is under by the specified composite. False otherwise. * @throws IOException * if an IO error occurs while checking the files. * @since 2.2 * @see FileUtils#directoryContains(File, File) */ public static boolean directoryContains(final String canonicalParent, final String canonicalChild) throws IOException { // Fail fast against NullPointerException if (canonicalParent == null) { throw new IllegalArgumentException("Directory must not be null"); } if (canonicalChild == null) { return false; } if (IOCase.SYSTEM.checkEquals(canonicalParent, canonicalChild)) { return false; } return IOCase.SYSTEM.checkStartsWith(canonicalChild, canonicalParent); } //----------------------------------------------------------------------- /** * Converts all separators to the Unix separator of forward slash. * * @param path the path to be changed, null ignored * @return the updated path */ public static String separatorsToUnix(String path) { if (path == null || path.indexOf(WINDOWS_SEPARATOR) == -1) { return path; } return path.replace(WINDOWS_SEPARATOR, UNIX_SEPARATOR); } /** * Converts all separators to the Windows separator of backslash. * * @param path the path to be changed, null ignored * @return the updated path */ public static String separatorsToWindows(String path) { if (path == null || path.indexOf(UNIX_SEPARATOR) == -1) { return path; } return path.replace(UNIX_SEPARATOR, WINDOWS_SEPARATOR); } /** * Converts all separators to the system separator. * * @param path the path to be changed, null ignored * @return the updated path */ public static String separatorsToSystem(String path) { if (path == null) { return null; } if (isSystemWindows()) { return separatorsToWindows(path); } else { return separatorsToUnix(path); } } //----------------------------------------------------------------------- /** * Returns the length of the filename prefix, such as C:/ or ~/. *

* This method will handle a file in either Unix or Windows format. *

* The prefix length includes the first slash in the full filename * if applicable. Thus, it is possible that the length returned is greater * than the length of the input string. *

     * Windows:
     * a\b\c.txt           --> ""          --> relative
     * \a\b\c.txt          --> "\"         --> current drive absolute
     * C:a\b\c.txt         --> "C:"        --> drive relative
     * C:\a\b\c.txt        --> "C:\"       --> absolute
     * \\server\a\b\c.txt  --> "\\server\" --> UNC
     *
     * Unix:
     * a/b/c.txt           --> ""          --> relative
     * /a/b/c.txt          --> "/"         --> absolute
     * ~/a/b/c.txt         --> "~/"        --> current user
     * ~                   --> "~/"        --> current user (slash added)
     * ~user/a/b/c.txt     --> "~user/"    --> named user
     * ~user               --> "~user/"    --> named user (slash added)
     * 
*

* The output will be the same irrespective of the machine that the code is running on. * ie. both Unix and Windows prefixes are matched regardless. * * @param filename the filename to find the prefix in, null returns -1 * @return the length of the prefix, -1 if invalid or null */ public static int getPrefixLength(String filename) { if (filename == null) { return -1; } int len = filename.length(); if (len == 0) { return 0; } char ch0 = filename.charAt(0); if (ch0 == ':') { return -1; } if (len == 1) { if (ch0 == '~') { return 2; // return a length greater than the input } return isSeparator(ch0) ? 1 : 0; } else { if (ch0 == '~') { int posUnix = filename.indexOf(UNIX_SEPARATOR, 1); int posWin = filename.indexOf(WINDOWS_SEPARATOR, 1); if (posUnix == -1 && posWin == -1) { return len + 1; // return a length greater than the input } posUnix = posUnix == -1 ? posWin : posUnix; posWin = posWin == -1 ? posUnix : posWin; return Math.min(posUnix, posWin) + 1; } char ch1 = filename.charAt(1); if (ch1 == ':') { ch0 = Character.toUpperCase(ch0); if (ch0 >= 'A' && ch0 <= 'Z') { if (len == 2 || isSeparator(filename.charAt(2)) == false) { return 2; } return 3; } return -1; } else if (isSeparator(ch0) && isSeparator(ch1)) { int posUnix = filename.indexOf(UNIX_SEPARATOR, 2); int posWin = filename.indexOf(WINDOWS_SEPARATOR, 2); if (posUnix == -1 && posWin == -1 || posUnix == 2 || posWin == 2) { return -1; } posUnix = posUnix == -1 ? posWin : posUnix; posWin = posWin == -1 ? posUnix : posWin; return Math.min(posUnix, posWin) + 1; } else { return isSeparator(ch0) ? 1 : 0; } } } /** * Returns the index of the last directory separator character. *

* This method will handle a file in either Unix or Windows format. * The position of the last forward or backslash is returned. *

* The output will be the same irrespective of the machine that the code is running on. * * @param filename the filename to find the last path separator in, null returns -1 * @return the index of the last separator character, or -1 if there * is no such character */ public static int indexOfLastSeparator(String filename) { if (filename == null) { return -1; } int lastUnixPos = filename.lastIndexOf(UNIX_SEPARATOR); int lastWindowsPos = filename.lastIndexOf(WINDOWS_SEPARATOR); return Math.max(lastUnixPos, lastWindowsPos); } /** * Returns the index of the last extension separator character, which is a dot. *

* This method also checks that there is no directory separator after the last dot. * To do this it uses {@link #indexOfLastSeparator(String)} which will * handle a file in either Unix or Windows format. *

* The output will be the same irrespective of the machine that the code is running on. * * @param filename the filename to find the last path separator in, null returns -1 * @return the index of the last separator character, or -1 if there * is no such character */ public static int indexOfExtension(String filename) { if (filename == null) { return -1; } int extensionPos = filename.lastIndexOf(EXTENSION_SEPARATOR); int lastSeparator = indexOfLastSeparator(filename); return lastSeparator > extensionPos ? -1 : extensionPos; } //----------------------------------------------------------------------- /** * Gets the prefix from a full filename, such as C:/ * or ~/. *

* This method will handle a file in either Unix or Windows format. * The prefix includes the first slash in the full filename where applicable. *

     * Windows:
     * a\b\c.txt           --> ""          --> relative
     * \a\b\c.txt          --> "\"         --> current drive absolute
     * C:a\b\c.txt         --> "C:"        --> drive relative
     * C:\a\b\c.txt        --> "C:\"       --> absolute
     * \\server\a\b\c.txt  --> "\\server\" --> UNC
     *
     * Unix:
     * a/b/c.txt           --> ""          --> relative
     * /a/b/c.txt          --> "/"         --> absolute
     * ~/a/b/c.txt         --> "~/"        --> current user
     * ~                   --> "~/"        --> current user (slash added)
     * ~user/a/b/c.txt     --> "~user/"    --> named user
     * ~user               --> "~user/"    --> named user (slash added)
     * 
*

* The output will be the same irrespective of the machine that the code is running on. * ie. both Unix and Windows prefixes are matched regardless. * * @param filename the filename to query, null returns null * @return the prefix of the file, null if invalid */ public static String getPrefix(String filename) { if (filename == null) { return null; } int len = getPrefixLength(filename); if (len < 0) { return null; } if (len > filename.length()) { return filename + UNIX_SEPARATOR; // we know this only happens for unix } return filename.substring(0, len); } /** * Gets the path from a full filename, which excludes the prefix. *

* This method will handle a file in either Unix or Windows format. * The method is entirely text based, and returns the text before and * including the last forward or backslash. *

     * C:\a\b\c.txt --> a\b\
     * ~/a/b/c.txt  --> a/b/
     * a.txt        --> ""
     * a/b/c        --> a/b/
     * a/b/c/       --> a/b/c/
     * 
*

* The output will be the same irrespective of the machine that the code is running on. *

* This method drops the prefix from the result. * See {@link #getFullPath(String)} for the method that retains the prefix. * * @param filename the filename to query, null returns null * @return the path of the file, an empty string if none exists, null if invalid */ public static String getPath(String filename) { return doGetPath(filename, 1); } /** * Gets the path from a full filename, which excludes the prefix, and * also excluding the final directory separator. *

* This method will handle a file in either Unix or Windows format. * The method is entirely text based, and returns the text before the * last forward or backslash. *

     * C:\a\b\c.txt --> a\b
     * ~/a/b/c.txt  --> a/b
     * a.txt        --> ""
     * a/b/c        --> a/b
     * a/b/c/       --> a/b/c
     * 
*

* The output will be the same irrespective of the machine that the code is running on. *

* This method drops the prefix from the result. * See {@link #getFullPathNoEndSeparator(String)} for the method that retains the prefix. * * @param filename the filename to query, null returns null * @return the path of the file, an empty string if none exists, null if invalid */ public static String getPathNoEndSeparator(String filename) { return doGetPath(filename, 0); } /** * Does the work of getting the path. * * @param filename the filename * @param separatorAdd 0 to omit the end separator, 1 to return it * @return the path */ private static String doGetPath(String filename, int separatorAdd) { if (filename == null) { return null; } int prefix = getPrefixLength(filename); if (prefix < 0) { return null; } int index = indexOfLastSeparator(filename); int endIndex = index+separatorAdd; if (prefix >= filename.length() || index < 0 || prefix >= endIndex) { return ""; } return filename.substring(prefix, endIndex); } /** * Gets the full path from a full filename, which is the prefix + path. *

* This method will handle a file in either Unix or Windows format. * The method is entirely text based, and returns the text before and * including the last forward or backslash. *

     * C:\a\b\c.txt --> C:\a\b\
     * ~/a/b/c.txt  --> ~/a/b/
     * a.txt        --> ""
     * a/b/c        --> a/b/
     * a/b/c/       --> a/b/c/
     * C:           --> C:
     * C:\          --> C:\
     * ~            --> ~/
     * ~/           --> ~/
     * ~user        --> ~user/
     * ~user/       --> ~user/
     * 
*

* The output will be the same irrespective of the machine that the code is running on. * * @param filename the filename to query, null returns null * @return the path of the file, an empty string if none exists, null if invalid */ public static String getFullPath(String filename) { return doGetFullPath(filename, true); } /** * Gets the full path from a full filename, which is the prefix + path, * and also excluding the final directory separator. *

* This method will handle a file in either Unix or Windows format. * The method is entirely text based, and returns the text before the * last forward or backslash. *

     * C:\a\b\c.txt --> C:\a\b
     * ~/a/b/c.txt  --> ~/a/b
     * a.txt        --> ""
     * a/b/c        --> a/b
     * a/b/c/       --> a/b/c
     * C:           --> C:
     * C:\          --> C:\
     * ~            --> ~
     * ~/           --> ~
     * ~user        --> ~user
     * ~user/       --> ~user
     * 
*

* The output will be the same irrespective of the machine that the code is running on. * * @param filename the filename to query, null returns null * @return the path of the file, an empty string if none exists, null if invalid */ public static String getFullPathNoEndSeparator(String filename) { return doGetFullPath(filename, false); } /** * Does the work of getting the path. * * @param filename the filename * @param includeSeparator true to include the end separator * @return the path */ private static String doGetFullPath(String filename, boolean includeSeparator) { if (filename == null) { return null; } int prefix = getPrefixLength(filename); if (prefix < 0) { return null; } if (prefix >= filename.length()) { if (includeSeparator) { return getPrefix(filename); // add end slash if necessary } else { return filename; } } int index = indexOfLastSeparator(filename); if (index < 0) { return filename.substring(0, prefix); } int end = index + (includeSeparator ? 1 : 0); if (end == 0) { end++; } return filename.substring(0, end); } /** * Gets the name minus the path from a full filename. *

* This method will handle a file in either Unix or Windows format. * The text after the last forward or backslash is returned. *

     * a/b/c.txt --> c.txt
     * a.txt     --> a.txt
     * a/b/c     --> c
     * a/b/c/    --> ""
     * 
*

* The output will be the same irrespective of the machine that the code is running on. * * @param filename the filename to query, null returns null * @return the name of the file without the path, or an empty string if none exists */ public static String getName(String filename) { if (filename == null) { return null; } int index = indexOfLastSeparator(filename); return filename.substring(index + 1); } /** * Gets the base name, minus the full path and extension, from a full filename. *

* This method will handle a file in either Unix or Windows format. * The text after the last forward or backslash and before the last dot is returned. *

     * a/b/c.txt --> c
     * a.txt     --> a
     * a/b/c     --> c
     * a/b/c/    --> ""
     * 
*

* The output will be the same irrespective of the machine that the code is running on. * * @param filename the filename to query, null returns null * @return the name of the file without the path, or an empty string if none exists */ public static String getBaseName(String filename) { return removeExtension(getName(filename)); } /** * Gets the extension of a filename. *

* This method returns the textual part of the filename after the last dot. * There must be no directory separator after the dot. *

     * foo.txt      --> "txt"
     * a/b/c.jpg    --> "jpg"
     * a/b.txt/c    --> ""
     * a/b/c        --> ""
     * 
*

* The output will be the same irrespective of the machine that the code is running on. * * @param filename the filename to retrieve the extension of. * @return the extension of the file or an empty string if none exists or {@code null} * if the filename is {@code null}. */ public static String getExtension(String filename) { if (filename == null) { return null; } int index = indexOfExtension(filename); if (index == -1) { return ""; } else { return filename.substring(index + 1); } } //----------------------------------------------------------------------- /** * Removes the extension from a filename. *

* This method returns the textual part of the filename before the last dot. * There must be no directory separator after the dot. *

     * foo.txt    --> foo
     * a\b\c.jpg  --> a\b\c
     * a\b\c      --> a\b\c
     * a.b\c      --> a.b\c
     * 
*

* The output will be the same irrespective of the machine that the code is running on. * * @param filename the filename to query, null returns null * @return the filename minus the extension */ public static String removeExtension(String filename) { if (filename == null) { return null; } int index = indexOfExtension(filename); if (index == -1) { return filename; } else { return filename.substring(0, index); } } //----------------------------------------------------------------------- /** * Checks whether two filenames are equal exactly. *

* No processing is performed on the filenames other than comparison, * thus this is merely a null-safe case-sensitive equals. * * @param filename1 the first filename to query, may be null * @param filename2 the second filename to query, may be null * @return true if the filenames are equal, null equals null * @see IOCase#SENSITIVE */ public static boolean equals(String filename1, String filename2) { return equals(filename1, filename2, false, IOCase.SENSITIVE); } /** * Checks whether two filenames are equal using the case rules of the system. *

* No processing is performed on the filenames other than comparison. * The check is case-sensitive on Unix and case-insensitive on Windows. * * @param filename1 the first filename to query, may be null * @param filename2 the second filename to query, may be null * @return true if the filenames are equal, null equals null * @see IOCase#SYSTEM */ public static boolean equalsOnSystem(String filename1, String filename2) { return equals(filename1, filename2, false, IOCase.SYSTEM); } //----------------------------------------------------------------------- /** * Checks whether two filenames are equal after both have been normalized. *

* Both filenames are first passed to {@link #normalize(String)}. * The check is then performed in a case-sensitive manner. * * @param filename1 the first filename to query, may be null * @param filename2 the second filename to query, may be null * @return true if the filenames are equal, null equals null * @see IOCase#SENSITIVE */ public static boolean equalsNormalized(String filename1, String filename2) { return equals(filename1, filename2, true, IOCase.SENSITIVE); } /** * Checks whether two filenames are equal after both have been normalized * and using the case rules of the system. *

* Both filenames are first passed to {@link #normalize(String)}. * The check is then performed case-sensitive on Unix and * case-insensitive on Windows. * * @param filename1 the first filename to query, may be null * @param filename2 the second filename to query, may be null * @return true if the filenames are equal, null equals null * @see IOCase#SYSTEM */ public static boolean equalsNormalizedOnSystem(String filename1, String filename2) { return equals(filename1, filename2, true, IOCase.SYSTEM); } /** * Checks whether two filenames are equal, optionally normalizing and providing * control over the case-sensitivity. * * @param filename1 the first filename to query, may be null * @param filename2 the second filename to query, may be null * @param normalized whether to normalize the filenames * @param caseSensitivity what case sensitivity rule to use, null means case-sensitive * @return true if the filenames are equal, null equals null * @since 1.3 */ public static boolean equals( String filename1, String filename2, boolean normalized, IOCase caseSensitivity) { if (filename1 == null || filename2 == null) { return filename1 == null && filename2 == null; } if (normalized) { filename1 = normalize(filename1); filename2 = normalize(filename2); if (filename1 == null || filename2 == null) { throw new NullPointerException( "Error normalizing one or both of the file names"); } } if (caseSensitivity == null) { caseSensitivity = IOCase.SENSITIVE; } return caseSensitivity.checkEquals(filename1, filename2); } //----------------------------------------------------------------------- /** * Checks whether the extension of the filename is that specified. *

* This method obtains the extension as the textual part of the filename * after the last dot. There must be no directory separator after the dot. * The extension check is case-sensitive on all platforms. * * @param filename the filename to query, null returns false * @param extension the extension to check for, null or empty checks for no extension * @return true if the filename has the specified extension */ public static boolean isExtension(String filename, String extension) { if (filename == null) { return false; } if (extension == null || extension.length() == 0) { return indexOfExtension(filename) == -1; } String fileExt = getExtension(filename); return fileExt.equals(extension); } /** * Checks whether the extension of the filename is one of those specified. *

* This method obtains the extension as the textual part of the filename * after the last dot. There must be no directory separator after the dot. * The extension check is case-sensitive on all platforms. * * @param filename the filename to query, null returns false * @param extensions the extensions to check for, null checks for no extension * @return true if the filename is one of the extensions */ public static boolean isExtension(String filename, String[] extensions) { if (filename == null) { return false; } if (extensions == null || extensions.length == 0) { return indexOfExtension(filename) == -1; } String fileExt = getExtension(filename); for (String extension : extensions) { if (fileExt.equals(extension)) { return true; } } return false; } /** * Checks whether the extension of the filename is one of those specified. *

* This method obtains the extension as the textual part of the filename * after the last dot. There must be no directory separator after the dot. * The extension check is case-sensitive on all platforms. * * @param filename the filename to query, null returns false * @param extensions the extensions to check for, null checks for no extension * @return true if the filename is one of the extensions */ public static boolean isExtension(String filename, Collection extensions) { if (filename == null) { return false; } if (extensions == null || extensions.isEmpty()) { return indexOfExtension(filename) == -1; } String fileExt = getExtension(filename); for (String extension : extensions) { if (fileExt.equals(extension)) { return true; } } return false; } //----------------------------------------------------------------------- /** * Checks a filename to see if it matches the specified wildcard matcher, * always testing case-sensitive. *

* The wildcard matcher uses the characters '?' and '*' to represent a * single or multiple (zero or more) wildcard characters. * This is the same as often found on Dos/Unix command lines. * The check is case-sensitive always. *

     * wildcardMatch("c.txt", "*.txt")      --> true
     * wildcardMatch("c.txt", "*.jpg")      --> false
     * wildcardMatch("a/b/c.txt", "a/b/*")  --> true
     * wildcardMatch("c.txt", "*.???")      --> true
     * wildcardMatch("c.txt", "*.????")     --> false
     * 
* N.B. the sequence "*?" does not work properly at present in match strings. * * @param filename the filename to match on * @param wildcardMatcher the wildcard string to match against * @return true if the filename matches the wilcard string * @see IOCase#SENSITIVE */ public static boolean wildcardMatch(String filename, String wildcardMatcher) { return wildcardMatch(filename, wildcardMatcher, IOCase.SENSITIVE); } /** * Checks a filename to see if it matches the specified wildcard matcher * using the case rules of the system. *

* The wildcard matcher uses the characters '?' and '*' to represent a * single or multiple (zero or more) wildcard characters. * This is the same as often found on Dos/Unix command lines. * The check is case-sensitive on Unix and case-insensitive on Windows. *

     * wildcardMatch("c.txt", "*.txt")      --> true
     * wildcardMatch("c.txt", "*.jpg")      --> false
     * wildcardMatch("a/b/c.txt", "a/b/*")  --> true
     * wildcardMatch("c.txt", "*.???")      --> true
     * wildcardMatch("c.txt", "*.????")     --> false
     * 
* N.B. the sequence "*?" does not work properly at present in match strings. * * @param filename the filename to match on * @param wildcardMatcher the wildcard string to match against * @return true if the filename matches the wilcard string * @see IOCase#SYSTEM */ public static boolean wildcardMatchOnSystem(String filename, String wildcardMatcher) { return wildcardMatch(filename, wildcardMatcher, IOCase.SYSTEM); } /** * Checks a filename to see if it matches the specified wildcard matcher * allowing control over case-sensitivity. *

* The wildcard matcher uses the characters '?' and '*' to represent a * single or multiple (zero or more) wildcard characters. * N.B. the sequence "*?" does not work properly at present in match strings. * * @param filename the filename to match on * @param wildcardMatcher the wildcard string to match against * @param caseSensitivity what case sensitivity rule to use, null means case-sensitive * @return true if the filename matches the wilcard string * @since 1.3 */ public static boolean wildcardMatch(String filename, String wildcardMatcher, IOCase caseSensitivity) { if (filename == null && wildcardMatcher == null) { return true; } if (filename == null || wildcardMatcher == null) { return false; } if (caseSensitivity == null) { caseSensitivity = IOCase.SENSITIVE; } String[] wcs = splitOnTokens(wildcardMatcher); boolean anyChars = false; int textIdx = 0; int wcsIdx = 0; Stack backtrack = new Stack(); // loop around a backtrack stack, to handle complex * matching do { if (backtrack.size() > 0) { int[] array = backtrack.pop(); wcsIdx = array[0]; textIdx = array[1]; anyChars = true; } // loop whilst tokens and text left to process while (wcsIdx < wcs.length) { if (wcs[wcsIdx].equals("?")) { // ? so move to next text char textIdx++; if (textIdx > filename.length()) { break; } anyChars = false; } else if (wcs[wcsIdx].equals("*")) { // set any chars status anyChars = true; if (wcsIdx == wcs.length - 1) { textIdx = filename.length(); } } else { // matching text token if (anyChars) { // any chars then try to locate text token textIdx = caseSensitivity.checkIndexOf(filename, textIdx, wcs[wcsIdx]); if (textIdx == -1) { // token not found break; } int repeat = caseSensitivity.checkIndexOf(filename, textIdx + 1, wcs[wcsIdx]); if (repeat >= 0) { backtrack.push(new int[] {wcsIdx, repeat}); } } else { // matching from current position if (!caseSensitivity.checkRegionMatches(filename, textIdx, wcs[wcsIdx])) { // couldnt match token break; } } // matched text token, move text index to end of matched token textIdx += wcs[wcsIdx].length(); anyChars = false; } wcsIdx++; } // full match if (wcsIdx == wcs.length && textIdx == filename.length()) { return true; } } while (backtrack.size() > 0); return false; } /** * Splits a string into a number of tokens. * The text is split by '?' and '*'. * Where multiple '*' occur consecutively they are collapsed into a single '*'. * * @param text the text to split * @return the array of tokens, never null */ static String[] splitOnTokens(String text) { // used by wildcardMatch // package level so a unit test may run on this if (text.indexOf('?') == -1 && text.indexOf('*') == -1) { return new String[] { text }; } char[] array = text.toCharArray(); ArrayList list = new ArrayList(); StringBuilder buffer = new StringBuilder(); for (int i = 0; i < array.length; i++) { if (array[i] == '?' || array[i] == '*') { if (buffer.length() != 0) { list.add(buffer.toString()); buffer.setLength(0); } if (array[i] == '?') { list.add("?"); } else if (list.isEmpty() || i > 0 && list.get(list.size() - 1).equals("*") == false) { list.add("*"); } } else { buffer.append(array[i]); } } if (buffer.length() != 0) { list.add(buffer.toString()); } return list.toArray( new String[ list.size() ] ); } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/ByteOrderMark.java0000644000175000017500000001302012125050425027427 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.io.Serializable; /** * Byte Order Mark (BOM) representation - see {@link org.apache.commons.io.input.BOMInputStream}. * * @see org.apache.commons.io.input.BOMInputStream * @see Wikipedia: Byte Order Mark * @see W3C: Autodetection of Character Encodings * (Non-Normative) * @version $Id: ByteOrderMark.java 1347571 2012-06-07 11:13:53Z sebb $ * @since 2.0 */ public class ByteOrderMark implements Serializable { private static final long serialVersionUID = 1L; /** UTF-8 BOM */ public static final ByteOrderMark UTF_8 = new ByteOrderMark("UTF-8", 0xEF, 0xBB, 0xBF); /** UTF-16BE BOM (Big-Endian) */ public static final ByteOrderMark UTF_16BE = new ByteOrderMark("UTF-16BE", 0xFE, 0xFF); /** UTF-16LE BOM (Little-Endian) */ public static final ByteOrderMark UTF_16LE = new ByteOrderMark("UTF-16LE", 0xFF, 0xFE); /** * UTF-32BE BOM (Big-Endian) * @since 2.2 */ public static final ByteOrderMark UTF_32BE = new ByteOrderMark("UTF-32BE", 0x00, 0x00, 0xFE, 0xFF); /** * UTF-32LE BOM (Little-Endian) * @since 2.2 */ public static final ByteOrderMark UTF_32LE = new ByteOrderMark("UTF-32LE", 0xFF, 0xFE, 0x00, 0x00); private final String charsetName; private final int[] bytes; /** * Construct a new BOM. * * @param charsetName The name of the charset the BOM represents * @param bytes The BOM's bytes * @throws IllegalArgumentException if the charsetName is null or * zero length * @throws IllegalArgumentException if the bytes are null or zero * length */ public ByteOrderMark(String charsetName, int... bytes) { if (charsetName == null || charsetName.length() == 0) { throw new IllegalArgumentException("No charsetName specified"); } if (bytes == null || bytes.length == 0) { throw new IllegalArgumentException("No bytes specified"); } this.charsetName = charsetName; this.bytes = new int[bytes.length]; System.arraycopy(bytes, 0, this.bytes, 0, bytes.length); } /** * Return the name of the {@link java.nio.charset.Charset} the BOM represents. * * @return the character set name */ public String getCharsetName() { return charsetName; } /** * Return the length of the BOM's bytes. * * @return the length of the BOM's bytes */ public int length() { return bytes.length; } /** * The byte at the specified position. * * @param pos The position * @return The specified byte */ public int get(int pos) { return bytes[pos]; } /** * Return a copy of the BOM's bytes. * * @return a copy of the BOM's bytes */ public byte[] getBytes() { byte[] copy = new byte[bytes.length]; for (int i = 0; i < bytes.length; i++) { copy[i] = (byte)bytes[i]; } return copy; } /** * Indicates if this BOM's bytes equals another. * * @param obj The object to compare to * @return true if the bom's bytes are equal, otherwise * false */ @Override public boolean equals(Object obj) { if (!(obj instanceof ByteOrderMark)) { return false; } ByteOrderMark bom = (ByteOrderMark)obj; if (bytes.length != bom.length()) { return false; } for (int i = 0; i < bytes.length; i++) { if (bytes[i] != bom.get(i)) { return false; } } return true; } /** * Return the hashcode for this BOM. * * @return the hashcode for this BOM. * @see java.lang.Object#hashCode() */ @Override public int hashCode() { int hashCode = getClass().hashCode(); for (int b : bytes) { hashCode += b; } return hashCode; } /** * Provide a String representation of the BOM. * * @return the length of the BOM's bytes */ @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append(getClass().getSimpleName()); builder.append('['); builder.append(charsetName); builder.append(": "); for (int i = 0; i < bytes.length; i++) { if (i > 0) { builder.append(","); } builder.append("0x"); builder.append(Integer.toHexString(0xFF & bytes[i]).toUpperCase()); } builder.append(']'); return builder.toString(); } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/comparator/0000755000175000017500000000000012125050425026225 5ustar ebourgebourg././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/comparator/CompositeFileComparator.javalibcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/comparator/CompositeFileComparator.j0000644000175000017500000001047312125050425033177 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.comparator; import java.io.File; import java.io.Serializable; import java.util.ArrayList; import java.util.Comparator; import java.util.List; /** * Compare two files using a set of delegate file {@link Comparator}. *

* This comparator can be used to sort lists or arrays of files * by combining a number other comparators. *

* Example of sorting a list of files by type (i.e. directory or file) * and then by name: *

 *       CompositeFileComparator comparator =
 *                       new CompositeFileComparator(
 *                                   DirectoryFileComparator.DIRECTORY_COMPARATOR,
 *                                   NameFileComparator.NAME_COMPARATOR);
 *       List<File> list = ...
 *       comparator.sort(list);
 * 
* * @version $Id: CompositeFileComparator.java 1304052 2012-03-22 20:55:29Z ggregory $ * @since 2.0 */ public class CompositeFileComparator extends AbstractFileComparator implements Serializable { private static final Comparator[] NO_COMPARATORS = {}; private final Comparator[] delegates; /** * Create a composite comparator for the set of delegate comparators. * * @param delegates The delegate file comparators */ @SuppressWarnings("unchecked") // casts 1 & 2 must be OK because types are already correct public CompositeFileComparator(Comparator... delegates) { if (delegates == null) { this.delegates = (Comparator[]) NO_COMPARATORS;//1 } else { this.delegates = (Comparator[]) new Comparator[delegates.length];//2 System.arraycopy(delegates, 0, this.delegates, 0, delegates.length); } } /** * Create a composite comparator for the set of delegate comparators. * * @param delegates The delegate file comparators */ @SuppressWarnings("unchecked") // casts 1 & 2 must be OK because types are already correct public CompositeFileComparator(Iterable> delegates) { if (delegates == null) { this.delegates = (Comparator[]) NO_COMPARATORS; //1 } else { List> list = new ArrayList>(); for (Comparator comparator : delegates) { list.add(comparator); } this.delegates = (Comparator[]) list.toArray(new Comparator[list.size()]); //2 } } /** * Compare the two files using delegate comparators. * * @param file1 The first file to compare * @param file2 The second file to compare * @return the first non-zero result returned from * the delegate comparators or zero. */ public int compare(File file1, File file2) { int result = 0; for (Comparator delegate : delegates) { result = delegate.compare(file1, file2); if (result != 0) { break; } } return result; } /** * String representation of this file comparator. * * @return String representation of this file comparator */ @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append(super.toString()); builder.append('{'); for (int i = 0; i < delegates.length; i++) { if (i > 0) { builder.append(','); } builder.append(delegates[i]); } builder.append('}'); return builder.toString(); } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/comparator/PathFileComparator.java0000644000175000017500000001105012125050425032611 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.comparator; import java.io.File; import java.io.Serializable; import java.util.Comparator; import org.apache.commons.io.IOCase; /** * Compare the path of two files for order (see {@link File#getPath()}). *

* This comparator can be used to sort lists or arrays of files * by their path either in a case-sensitive, case-insensitive or * system dependant case sensitive way. A number of singleton instances * are provided for the various case sensitivity options (using {@link IOCase}) * and the reverse of those options. *

* Example of a case-sensitive file path sort using the * {@link #PATH_COMPARATOR} singleton instance: *

 *       List<File> list = ...
 *       PathFileComparator.PATH_COMPARATOR.sort(list);
 * 
*

* Example of a reverse case-insensitive file path sort using the * {@link #PATH_INSENSITIVE_REVERSE} singleton instance: *

 *       File[] array = ...
 *       PathFileComparator.PATH_INSENSITIVE_REVERSE.sort(array);
 * 
*

* * @version $Id: PathFileComparator.java 1304052 2012-03-22 20:55:29Z ggregory $ * @since 1.4 */ public class PathFileComparator extends AbstractFileComparator implements Serializable { /** Case-sensitive path comparator instance (see {@link IOCase#SENSITIVE}) */ public static final Comparator PATH_COMPARATOR = new PathFileComparator(); /** Reverse case-sensitive path comparator instance (see {@link IOCase#SENSITIVE}) */ public static final Comparator PATH_REVERSE = new ReverseComparator(PATH_COMPARATOR); /** Case-insensitive path comparator instance (see {@link IOCase#INSENSITIVE}) */ public static final Comparator PATH_INSENSITIVE_COMPARATOR = new PathFileComparator(IOCase.INSENSITIVE); /** Reverse case-insensitive path comparator instance (see {@link IOCase#INSENSITIVE}) */ public static final Comparator PATH_INSENSITIVE_REVERSE = new ReverseComparator(PATH_INSENSITIVE_COMPARATOR); /** System sensitive path comparator instance (see {@link IOCase#SYSTEM}) */ public static final Comparator PATH_SYSTEM_COMPARATOR = new PathFileComparator(IOCase.SYSTEM); /** Reverse system sensitive path comparator instance (see {@link IOCase#SYSTEM}) */ public static final Comparator PATH_SYSTEM_REVERSE = new ReverseComparator(PATH_SYSTEM_COMPARATOR); /** Whether the comparison is case sensitive. */ private final IOCase caseSensitivity; /** * Construct a case sensitive file path comparator instance. */ public PathFileComparator() { this.caseSensitivity = IOCase.SENSITIVE; } /** * Construct a file path comparator instance with the specified case-sensitivity. * * @param caseSensitivity how to handle case sensitivity, null means case-sensitive */ public PathFileComparator(IOCase caseSensitivity) { this.caseSensitivity = caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity; } /** * Compare the paths of two files the specified case sensitivity. * * @param file1 The first file to compare * @param file2 The second file to compare * @return a negative value if the first file's path * is less than the second, zero if the paths are the * same and a positive value if the first files path * is greater than the second file. * */ public int compare(File file1, File file2) { return caseSensitivity.checkCompareTo(file1.getPath(), file2.getPath()); } /** * String representation of this file comparator. * * @return String representation of this file comparator */ @Override public String toString() { return super.toString() + "[caseSensitivity=" + caseSensitivity + "]"; } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/comparator/LastModifiedFileComparator.javalibcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/comparator/LastModifiedFileComparato0000644000175000017500000000552212125050425033166 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.comparator; import java.io.File; import java.io.Serializable; import java.util.Comparator; /** * Compare the last modified date/time of two files for order * (see {@link File#lastModified()}). *

* This comparator can be used to sort lists or arrays of files * by their last modified date/time. *

* Example of sorting a list of files using the * {@link #LASTMODIFIED_COMPARATOR} singleton instance: *

 *       List<File> list = ...
 *       LastModifiedFileComparator.LASTMODIFIED_COMPARATOR.sort(list);
 * 
*

* Example of doing a reverse sort of an array of files using the * {@link #LASTMODIFIED_REVERSE} singleton instance: *

 *       File[] array = ...
 *       LastModifiedFileComparator.LASTMODIFIED_REVERSE.sort(array);
 * 
*

* * @version $Id: LastModifiedFileComparator.java 1304052 2012-03-22 20:55:29Z ggregory $ * @since 1.4 */ public class LastModifiedFileComparator extends AbstractFileComparator implements Serializable { /** Last modified comparator instance */ public static final Comparator LASTMODIFIED_COMPARATOR = new LastModifiedFileComparator(); /** Reverse last modified comparator instance */ public static final Comparator LASTMODIFIED_REVERSE = new ReverseComparator(LASTMODIFIED_COMPARATOR); /** * Compare the last the last modified date/time of two files. * * @param file1 The first file to compare * @param file2 The second file to compare * @return a negative value if the first file's lastmodified date/time * is less than the second, zero if the lastmodified date/time are the * same and a positive value if the first files lastmodified date/time * is greater than the second file. * */ public int compare(File file1, File file2) { long result = file1.lastModified() - file2.lastModified(); if (result < 0) { return -1; } else if (result > 0) { return 1; } else { return 0; } } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/comparator/ReverseComparator.java0000644000175000017500000000450212125050425032534 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.comparator; import java.io.File; import java.io.Serializable; import java.util.Comparator; /** * Reverses the result of comparing two objects using * the delegate {@link Comparator}. * * @version $Id: ReverseComparator.java 1304052 2012-03-22 20:55:29Z ggregory $ * @since 1.4 */ class ReverseComparator extends AbstractFileComparator implements Serializable { private final Comparator delegate; /** * Construct an instance with the sepecified delegate {@link Comparator}. * * @param delegate The comparator to delegate to */ public ReverseComparator(Comparator delegate) { if (delegate == null) { throw new IllegalArgumentException("Delegate comparator is missing"); } this.delegate = delegate; } /** * Compare using the delegate Comparator, but reversing the result. * * @param file1 The first file to compare * @param file2 The second file to compare * @return the result from the delegate {@link Comparator#compare(Object, Object)} * reversing the value (i.e. positive becomes negative and vice versa) */ public int compare(File file1, File file2) { return delegate.compare(file2, file1); // parameters switched round } /** * String representation of this file comparator. * * @return String representation of this file comparator */ @Override public String toString() { return super.toString() + "[" + delegate.toString() + "]"; } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/comparator/SizeFileComparator.java0000644000175000017500000001207212125050425032634 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.comparator; import java.io.File; import java.io.Serializable; import java.util.Comparator; import org.apache.commons.io.FileUtils; /** * Compare the length/size of two files for order (see * {@link File#length()} and {@link FileUtils#sizeOfDirectory(File)}). *

* This comparator can be used to sort lists or arrays of files * by their length/size. *

* Example of sorting a list of files using the * {@link #SIZE_COMPARATOR} singleton instance: *

 *       List<File> list = ...
 *       SizeFileComparator.SIZE_COMPARATOR.sort(list);
 * 
*

* Example of doing a reverse sort of an array of files using the * {@link #SIZE_REVERSE} singleton instance: *

 *       File[] array = ...
 *       SizeFileComparator.SIZE_REVERSE.sort(array);
 * 
*

* N.B. Directories are treated as zero size unless * sumDirectoryContents is {@code true}. * * @version $Id: SizeFileComparator.java 1307462 2012-03-30 15:13:11Z ggregory $ * @since 1.4 */ public class SizeFileComparator extends AbstractFileComparator implements Serializable { /** Size comparator instance - directories are treated as zero size */ public static final Comparator SIZE_COMPARATOR = new SizeFileComparator(); /** Reverse size comparator instance - directories are treated as zero size */ public static final Comparator SIZE_REVERSE = new ReverseComparator(SIZE_COMPARATOR); /** * Size comparator instance which sums the size of a directory's contents * using {@link FileUtils#sizeOfDirectory(File)} */ public static final Comparator SIZE_SUMDIR_COMPARATOR = new SizeFileComparator(true); /** * Reverse size comparator instance which sums the size of a directory's contents * using {@link FileUtils#sizeOfDirectory(File)} */ public static final Comparator SIZE_SUMDIR_REVERSE = new ReverseComparator(SIZE_SUMDIR_COMPARATOR); /** Whether the sum of the directory's contents should be calculated. */ private final boolean sumDirectoryContents; /** * Construct a file size comparator instance (directories treated as zero size). */ public SizeFileComparator() { this.sumDirectoryContents = false; } /** * Construct a file size comparator instance specifying whether the size of * the directory contents should be aggregated. *

* If the sumDirectoryContents is {@code true} The size of * directories is calculated using {@link FileUtils#sizeOfDirectory(File)}. * * @param sumDirectoryContents {@code true} if the sum of the directoryies contents * should be calculated, otherwise {@code false} if directories should be treated * as size zero (see {@link FileUtils#sizeOfDirectory(File)}). */ public SizeFileComparator(boolean sumDirectoryContents) { this.sumDirectoryContents = sumDirectoryContents; } /** * Compare the length of two files. * * @param file1 The first file to compare * @param file2 The second file to compare * @return a negative value if the first file's length * is less than the second, zero if the lengths are the * same and a positive value if the first files length * is greater than the second file. * */ public int compare(File file1, File file2) { long size1 = 0; if (file1.isDirectory()) { size1 = sumDirectoryContents && file1.exists() ? FileUtils.sizeOfDirectory(file1) : 0; } else { size1 = file1.length(); } long size2 = 0; if (file2.isDirectory()) { size2 = sumDirectoryContents && file2.exists() ? FileUtils.sizeOfDirectory(file2) : 0; } else { size2 = file2.length(); } long result = size1 - size2; if (result < 0) { return -1; } else if (result > 0) { return 1; } else { return 0; } } /** * String representation of this file comparator. * * @return String representation of this file comparator */ @Override public String toString() { return super.toString() + "[sumDirectoryContents=" + sumDirectoryContents + "]"; } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/comparator/DirectoryFileComparator.javalibcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/comparator/DirectoryFileComparator.j0000644000175000017500000000535012125050425033177 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.comparator; import java.io.File; import java.io.Serializable; import java.util.Comparator; /** * Compare two files using the {@link File#isDirectory()} method. *

* This comparator can be used to sort lists or arrays by directories and files. *

* Example of sorting a list of files/directories using the * {@link #DIRECTORY_COMPARATOR} singleton instance: *

 *       List<File> list = ...
 *       DirectoryFileComparator.DIRECTORY_COMPARATOR.sort(list);
 * 
*

* Example of doing a reverse sort of an array of files/directories using the * {@link #DIRECTORY_REVERSE} singleton instance: *

 *       File[] array = ...
 *       DirectoryFileComparator.DIRECTORY_REVERSE.sort(array);
 * 
*

* * @version $Id: DirectoryFileComparator.java 1304052 2012-03-22 20:55:29Z ggregory $ * @since 2.0 */ public class DirectoryFileComparator extends AbstractFileComparator implements Serializable { /** Singleton default comparator instance */ public static final Comparator DIRECTORY_COMPARATOR = new DirectoryFileComparator(); /** Singleton reverse default comparator instance */ public static final Comparator DIRECTORY_REVERSE = new ReverseComparator(DIRECTORY_COMPARATOR); /** * Compare the two files using the {@link File#isDirectory()} method. * * @param file1 The first file to compare * @param file2 The second file to compare * @return the result of calling file1's * {@link File#compareTo(File)} with file2 as the parameter. */ public int compare(File file1, File file2) { return getType(file1) - getType(file2); } /** * Convert type to numeric value. * * @param file The file * @return 1 for directories and 2 for files */ private int getType(File file) { if (file.isDirectory()) { return 1; } else { return 2; } } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/comparator/ExtensionFileComparator.javalibcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/comparator/ExtensionFileComparator.j0000644000175000017500000001200212125050425033177 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.comparator; import java.io.File; import java.io.Serializable; import java.util.Comparator; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOCase; /** * Compare the file name extensions for order * (see {@link FilenameUtils#getExtension(String)}). *

* This comparator can be used to sort lists or arrays of files * by their file extension either in a case-sensitive, case-insensitive or * system dependant case sensitive way. A number of singleton instances * are provided for the various case sensitivity options (using {@link IOCase}) * and the reverse of those options. *

* Example of a case-sensitive file extension sort using the * {@link #EXTENSION_COMPARATOR} singleton instance: *

 *       List<File> list = ...
 *       ExtensionFileComparator.EXTENSION_COMPARATOR.sort(list);
 * 
*

* Example of a reverse case-insensitive file extension sort using the * {@link #EXTENSION_INSENSITIVE_REVERSE} singleton instance: *

 *       File[] array = ...
 *       ExtensionFileComparator.EXTENSION_INSENSITIVE_REVERSE.sort(array);
 * 
*

* * @version $Id: ExtensionFileComparator.java 1304052 2012-03-22 20:55:29Z ggregory $ * @since 1.4 */ public class ExtensionFileComparator extends AbstractFileComparator implements Serializable { /** Case-sensitive extension comparator instance (see {@link IOCase#SENSITIVE}) */ public static final Comparator EXTENSION_COMPARATOR = new ExtensionFileComparator(); /** Reverse case-sensitive extension comparator instance (see {@link IOCase#SENSITIVE}) */ public static final Comparator EXTENSION_REVERSE = new ReverseComparator(EXTENSION_COMPARATOR); /** Case-insensitive extension comparator instance (see {@link IOCase#INSENSITIVE}) */ public static final Comparator EXTENSION_INSENSITIVE_COMPARATOR = new ExtensionFileComparator(IOCase.INSENSITIVE); /** Reverse case-insensitive extension comparator instance (see {@link IOCase#INSENSITIVE}) */ public static final Comparator EXTENSION_INSENSITIVE_REVERSE = new ReverseComparator(EXTENSION_INSENSITIVE_COMPARATOR); /** System sensitive extension comparator instance (see {@link IOCase#SYSTEM}) */ public static final Comparator EXTENSION_SYSTEM_COMPARATOR = new ExtensionFileComparator(IOCase.SYSTEM); /** Reverse system sensitive path comparator instance (see {@link IOCase#SYSTEM}) */ public static final Comparator EXTENSION_SYSTEM_REVERSE = new ReverseComparator(EXTENSION_SYSTEM_COMPARATOR); /** Whether the comparison is case sensitive. */ private final IOCase caseSensitivity; /** * Construct a case sensitive file extension comparator instance. */ public ExtensionFileComparator() { this.caseSensitivity = IOCase.SENSITIVE; } /** * Construct a file extension comparator instance with the specified case-sensitivity. * * @param caseSensitivity how to handle case sensitivity, null means case-sensitive */ public ExtensionFileComparator(IOCase caseSensitivity) { this.caseSensitivity = caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity; } /** * Compare the extensions of two files the specified case sensitivity. * * @param file1 The first file to compare * @param file2 The second file to compare * @return a negative value if the first file's extension * is less than the second, zero if the extensions are the * same and a positive value if the first files extension * is greater than the second file. * */ public int compare(File file1, File file2) { String suffix1 = FilenameUtils.getExtension(file1.getName()); String suffix2 = FilenameUtils.getExtension(file2.getName()); return caseSensitivity.checkCompareTo(suffix1, suffix2); } /** * String representation of this file comparator. * * @return String representation of this file comparator */ @Override public String toString() { return super.toString() + "[caseSensitivity=" + caseSensitivity + "]"; } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/comparator/AbstractFileComparator.javalibcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/comparator/AbstractFileComparator.ja0000644000175000017500000000441712125050425033142 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.comparator; import java.io.File; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * Abstract file {@link Comparator} which provides sorting for file arrays and lists. * * @version $Id: AbstractFileComparator.java 1304052 2012-03-22 20:55:29Z ggregory $ * @since 2.0 */ abstract class AbstractFileComparator implements Comparator { /** * Sort an array of files. *

* This method uses {@link Arrays#sort(Object[], Comparator)} * and returns the original array. * * @param files The files to sort, may be null * @return The sorted array * @since 2.0 */ public File[] sort(File... files) { if (files != null) { Arrays.sort(files, this); } return files; } /** * Sort a List of files. *

* This method uses {@link Collections#sort(List, Comparator)} * and returns the original list. * * @param files The files to sort, may be null * @return The sorted list * @since 2.0 */ public List sort(List files) { if (files != null) { Collections.sort(files, this); } return files; } /** * String representation of this file comparator. * * @return String representation of this file comparator */ @Override public String toString() { return getClass().getSimpleName(); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/comparator/DefaultFileComparator.javalibcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/comparator/DefaultFileComparator.jav0000644000175000017500000000467312125050425033155 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.comparator; import java.io.File; import java.io.Serializable; import java.util.Comparator; /** * Compare two files using the default {@link File#compareTo(File)} method. *

* This comparator can be used to sort lists or arrays of files * by using the default file comparison. *

* Example of sorting a list of files using the * {@link #DEFAULT_COMPARATOR} singleton instance: *

 *       List<File> list = ...
 *       DefaultFileComparator.DEFAULT_COMPARATOR.sort(list);
 * 
*

* Example of doing a reverse sort of an array of files using the * {@link #DEFAULT_REVERSE} singleton instance: *

 *       File[] array = ...
 *       DefaultFileComparator.DEFAULT_REVERSE.sort(array);
 * 
*

* * @version $Id: DefaultFileComparator.java 1304052 2012-03-22 20:55:29Z ggregory $ * @since 1.4 */ public class DefaultFileComparator extends AbstractFileComparator implements Serializable { /** Singleton default comparator instance */ public static final Comparator DEFAULT_COMPARATOR = new DefaultFileComparator(); /** Singleton reverse default comparator instance */ public static final Comparator DEFAULT_REVERSE = new ReverseComparator(DEFAULT_COMPARATOR); /** * Compare the two files using the {@link File#compareTo(File)} method. * * @param file1 The first file to compare * @param file2 The second file to compare * @return the result of calling file1's * {@link File#compareTo(File)} with file2 as the parameter. */ public int compare(File file1, File file2) { return file1.compareTo(file2); } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/comparator/NameFileComparator.java0000644000175000017500000001104612125050425032602 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.comparator; import java.io.File; import java.io.Serializable; import java.util.Comparator; import org.apache.commons.io.IOCase; /** * Compare the names of two files for order (see {@link File#getName()}). *

* This comparator can be used to sort lists or arrays of files * by their name either in a case-sensitive, case-insensitive or * system dependant case sensitive way. A number of singleton instances * are provided for the various case sensitivity options (using {@link IOCase}) * and the reverse of those options. *

* Example of a case-sensitive file name sort using the * {@link #NAME_COMPARATOR} singleton instance: *

 *       List<File> list = ...
 *       NameFileComparator.NAME_COMPARATOR.sort(list);
 * 
*

* Example of a reverse case-insensitive file name sort using the * {@link #NAME_INSENSITIVE_REVERSE} singleton instance: *

 *       File[] array = ...
 *       NameFileComparator.NAME_INSENSITIVE_REVERSE.sort(array);
 * 
*

* * @version $Id: NameFileComparator.java 1304052 2012-03-22 20:55:29Z ggregory $ * @since 1.4 */ public class NameFileComparator extends AbstractFileComparator implements Serializable { /** Case-sensitive name comparator instance (see {@link IOCase#SENSITIVE}) */ public static final Comparator NAME_COMPARATOR = new NameFileComparator(); /** Reverse case-sensitive name comparator instance (see {@link IOCase#SENSITIVE}) */ public static final Comparator NAME_REVERSE = new ReverseComparator(NAME_COMPARATOR); /** Case-insensitive name comparator instance (see {@link IOCase#INSENSITIVE}) */ public static final Comparator NAME_INSENSITIVE_COMPARATOR = new NameFileComparator(IOCase.INSENSITIVE); /** Reverse case-insensitive name comparator instance (see {@link IOCase#INSENSITIVE}) */ public static final Comparator NAME_INSENSITIVE_REVERSE = new ReverseComparator(NAME_INSENSITIVE_COMPARATOR); /** System sensitive name comparator instance (see {@link IOCase#SYSTEM}) */ public static final Comparator NAME_SYSTEM_COMPARATOR = new NameFileComparator(IOCase.SYSTEM); /** Reverse system sensitive name comparator instance (see {@link IOCase#SYSTEM}) */ public static final Comparator NAME_SYSTEM_REVERSE = new ReverseComparator(NAME_SYSTEM_COMPARATOR); /** Whether the comparison is case sensitive. */ private final IOCase caseSensitivity; /** * Construct a case sensitive file name comparator instance. */ public NameFileComparator() { this.caseSensitivity = IOCase.SENSITIVE; } /** * Construct a file name comparator instance with the specified case-sensitivity. * * @param caseSensitivity how to handle case sensitivity, null means case-sensitive */ public NameFileComparator(IOCase caseSensitivity) { this.caseSensitivity = caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity; } /** * Compare the names of two files with the specified case sensitivity. * * @param file1 The first file to compare * @param file2 The second file to compare * @return a negative value if the first file's name * is less than the second, zero if the names are the * same and a positive value if the first files name * is greater than the second file. */ public int compare(File file1, File file2) { return caseSensitivity.checkCompareTo(file1.getName(), file2.getName()); } /** * String representation of this file comparator. * * @return String representation of this file comparator */ @Override public String toString() { return super.toString() + "[caseSensitivity=" + caseSensitivity + "]"; } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/comparator/package.html0000644000175000017500000002161012125050425030506 0ustar ebourgebourg

This package provides various {@link java.util.Comparator} implementations for {@link java.io.File}s.

Sorting

All the compartors include convenience utility sort(File...) and sort(List) methods.

For example, to sort the files in a directory by name:

        File[] files = dir.listFiles();
        NameFileComparator.NAME_COMPARATOR.sort(files);
  

...alternatively you can do this in one line:

        File[] files = NameFileComparator.NAME_COMPARATOR.sort(dir.listFiles());
  

Composite Comparator

The CompositeFileComparator can be used to compare (and sort lists or arrays of files) by combining a number other comparators.

For example, to sort an array of files by type (i.e. directory or file) and then by name:

        CompositeFileComparator comparator =
                        new CompositeFileComparator(
                                    DirectoryFileComparator.DIRECTORY_COMPARATOR,
                                    NameFileComparator.NAME_COMPARATOR);
        File[] files = dir.listFiles();
        comparator.sort(files);
  

Singleton Instances (thread-safe)

The {@link java.util.Comparator} implementations have some convenience singleton(thread-safe) instances ready to use:

libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/TaggedIOException.java0000644000175000017500000001052712125050425030230 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.io.IOException; import java.io.Serializable; /** * An {@link IOException} decorator that adds a serializable tag to the * wrapped exception. Both the tag and the original exception can be used * to determine further processing when this exception is caught. * * @since 2.0 */ public class TaggedIOException extends IOExceptionWithCause { /** * Generated serial version UID. */ private static final long serialVersionUID = -6994123481142850163L; /** * Checks whether the given throwable is tagged with the given tag. *

* This check can only succeed if the throwable is a * {@link TaggedIOException} and the tag is {@link Serializable}, but * the argument types are intentionally more generic to make it easier * to use this method without type casts. *

* A typical use for this method is in a catch block to * determine how a caught exception should be handled: *

     * Serializable tag = ...;
     * try {
     *     ...;
     * } catch (Throwable t) {
     *     if (TaggedIOExcepton.isTaggedWith(t, tag)) {
     *         // special processing for tagged exception
     *     } else {
     *         // handling of other kinds of exceptions
     *     }
     * }
     * 
* * @param throwable The Throwable object to check * @param tag tag object * @return {@code true} if the throwable has the specified tag, * otherwise {@code false} */ public static boolean isTaggedWith(Throwable throwable, Object tag) { return tag != null && throwable instanceof TaggedIOException && tag.equals(((TaggedIOException) throwable).tag); } /** * Throws the original {@link IOException} if the given throwable is * a {@link TaggedIOException} decorator the given tag. Does nothing * if the given throwable is of a different type or if it is tagged * with some other tag. *

* This method is typically used in a catch block to * selectively rethrow tagged exceptions. *

     * Serializable tag = ...;
     * try {
     *     ...;
     * } catch (Throwable t) {
     *     TaggedIOExcepton.throwCauseIfTagged(t, tag);
     *     // handle other kinds of exceptions
     * }
     * 
* * @param throwable an exception * @param tag tag object * @throws IOException original exception from the tagged decorator, if any */ public static void throwCauseIfTaggedWith(Throwable throwable, Object tag) throws IOException { if (isTaggedWith(throwable, tag)) { throw ((TaggedIOException) throwable).getCause(); } } /** * The tag of this exception. */ private final Serializable tag; /** * Creates a tagged wrapper for the given exception. * * @param original the exception to be tagged * @param tag tag of this exception */ public TaggedIOException(IOException original, Serializable tag) { super(original.getMessage(), original); this.tag = tag; } /** * Returns the serializable tag object. * * @return tag object */ public Serializable getTag() { return tag; } /** * Returns the wrapped exception. The only difference to the overridden * {@link Throwable#getCause()} method is the narrower return type. * * @return wrapped exception */ @Override public IOException getCause() { return (IOException) super.getCause(); } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/Charsets.java0000644000175000017500000001407112125050425026500 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.nio.charset.Charset; import java.nio.charset.UnsupportedCharsetException; /** * Charsets required of every implementation of the Java platform. * * From the Java documentation * Standard charsets: *

* Every implementation of the Java platform is required to support the following character encodings. Consult the * release documentation for your implementation to see if any other encodings are supported. Consult the release * documentation for your implementation to see if any other encodings are supported. *

* *
    *
  • US-ASCII
    * Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the Unicode character set.
  • *
  • ISO-8859-1
    * ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1.
  • *
  • UTF-8
    * Eight-bit Unicode Transformation Format.
  • *
  • UTF-16BE
    * Sixteen-bit Unicode Transformation Format, big-endian byte order.
  • *
  • UTF-16LE
    * Sixteen-bit Unicode Transformation Format, little-endian byte order.
  • *
  • UTF-16
    * Sixteen-bit Unicode Transformation Format, byte order specified by a mandatory initial byte-order mark (either order * accepted on input, big-endian used on output.)
  • *
* * @see Standard charsets * @since 2.3 * @version $Id: Charsets.java 1311751 2012-04-10 14:26:21Z ggregory $ */ public class Charsets { // // This class should only contain Charset instances for required encodings. This guarantees that it will load // correctly and without delay on all Java platforms. // /** * Returns the given Charset or the default Charset if the given Charset is null. * * @param charset * A charset or null. * @return the given Charset or the default Charset if the given Charset is null */ public static Charset toCharset(Charset charset) { return charset == null ? Charset.defaultCharset() : charset; } /** * Returns a Charset for the named charset. If the name is null, return the default Charset. * * @param charset * The name of the requested charset, may be null. * @return a Charset for the named charset * @throws UnsupportedCharsetException * If the named charset is unavailable */ public static Charset toCharset(String charset) { return charset == null ? Charset.defaultCharset() : Charset.forName(charset); } /** * CharEncodingISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1.

*

* Every implementation of the Java platform is required to support this character encoding. *

* * @see Standard charsets */ public static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1"); /** *

* Seven-bit ASCII, also known as ISO646-US, also known as the Basic Latin block of the Unicode character set. *

*

* Every implementation of the Java platform is required to support this character encoding. *

* * @see Standard charsets */ public static final Charset US_ASCII = Charset.forName("US-ASCII"); /** *

* Sixteen-bit Unicode Transformation Format, The byte order specified by a mandatory initial byte-order mark * (either order accepted on input, big-endian used on output) *

*

* Every implementation of the Java platform is required to support this character encoding. *

* * @see Standard charsets */ public static final Charset UTF_16 = Charset.forName("UTF-16"); /** *

* Sixteen-bit Unicode Transformation Format, big-endian byte order. *

*

* Every implementation of the Java platform is required to support this character encoding. *

* * @see Standard charsets */ public static final Charset UTF_16BE = Charset.forName("UTF-16BE"); /** *

* Sixteen-bit Unicode Transformation Format, little-endian byte order. *

*

* Every implementation of the Java platform is required to support this character encoding. *

* * @see Standard charsets */ public static final Charset UTF_16LE = Charset.forName("UTF-16LE"); /** *

* Eight-bit Unicode Transformation Format. *

*

* Every implementation of the Java platform is required to support this character encoding. *

* * @see Standard charsets */ public static final Charset UTF_8 = Charset.forName("UTF-8"); } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/HexDump.java0000644000175000017500000001326712125050425026304 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.io.IOException; import java.io.OutputStream; /** * Dumps data in hexadecimal format. *

* Provides a single function to take an array of bytes and display it * in hexadecimal form. *

* Origin of code: POI. * * @version $Id: HexDump.java 1302748 2012-03-20 01:35:32Z ggregory $ */ public class HexDump { /** * Instances should NOT be constructed in standard programming. */ public HexDump() { super(); } /** * Dump an array of bytes to an OutputStream. The output is formatted * for human inspection, with a hexadecimal offset followed by the * hexadecimal values of the next 16 bytes of data and the printable ASCII * characters (if any) that those bytes represent printed per each line * of output. *

* The offset argument specifies the start offset of the data array * within a larger entity like a file or an incoming stream. For example, * if the data array contains the third kibibyte of a file, then the * offset argument should be set to 2048. The offset value printed * at the beginning of each line indicates where in that larger entity * the first byte on that line is located. *

* All bytes between the given index (inclusive) and the end of the * data array are dumped. * * @param data the byte array to be dumped * @param offset offset of the byte array within a larger entity * @param stream the OutputStream to which the data is to be * written * @param index initial index into the byte array * * @throws IOException is thrown if anything goes wrong writing * the data to stream * @throws ArrayIndexOutOfBoundsException if the index is * outside the data array's bounds * @throws IllegalArgumentException if the output stream is null */ public static void dump(byte[] data, long offset, OutputStream stream, int index) throws IOException, ArrayIndexOutOfBoundsException, IllegalArgumentException { if (index < 0 || index >= data.length) { throw new ArrayIndexOutOfBoundsException( "illegal index: " + index + " into array of length " + data.length); } if (stream == null) { throw new IllegalArgumentException("cannot write to nullstream"); } long display_offset = offset + index; StringBuilder buffer = new StringBuilder(74); for (int j = index; j < data.length; j += 16) { int chars_read = data.length - j; if (chars_read > 16) { chars_read = 16; } dump(buffer, display_offset).append(' '); for (int k = 0; k < 16; k++) { if (k < chars_read) { dump(buffer, data[k + j]); } else { buffer.append(" "); } buffer.append(' '); } for (int k = 0; k < chars_read; k++) { if (data[k + j] >= ' ' && data[k + j] < 127) { buffer.append((char) data[k + j]); } else { buffer.append('.'); } } buffer.append(EOL); stream.write(buffer.toString().getBytes()); stream.flush(); buffer.setLength(0); display_offset += chars_read; } } /** * The line-separator (initializes to "line.separator" system property. */ public static final String EOL = System.getProperty("line.separator"); private static final char[] _hexcodes = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; private static final int[] _shifts = { 28, 24, 20, 16, 12, 8, 4, 0 }; /** * Dump a long value into a StringBuilder. * * @param _lbuffer the StringBuilder to dump the value in * @param value the long value to be dumped * @return StringBuilder containing the dumped value. */ private static StringBuilder dump(StringBuilder _lbuffer, long value) { for (int j = 0; j < 8; j++) { _lbuffer .append(_hexcodes[(int) (value >> _shifts[j]) & 15]); } return _lbuffer; } /** * Dump a byte value into a StringBuilder. * * @param _cbuffer the StringBuilder to dump the value in * @param value the byte value to be dumped * @return StringBuilder containing the dumped value. */ private static StringBuilder dump(StringBuilder _cbuffer, byte value) { for (int j = 0; j < 2; j++) { _cbuffer.append(_hexcodes[value >> _shifts[j + 6] & 15]); } return _cbuffer; } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/ThreadMonitor.java0000644000175000017500000000712712125050425027507 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; /** * Monitors a thread, interrupting it of it reaches the specified timout. *

* This works by sleeping until the specified timout amount and then * interrupting the thread being monitored. If the thread being monitored * completes its work before being interrupted, it should interrupt() * the monitor thread. *

* *

 *       long timeoutInMillis = 1000;
 *       try {
 *           Thread monitor = ThreadMonitor.start(timeoutInMillis);
 *           // do some work here
 *           ThreadMonitor.stop(monitor);
 *       } catch (InterruptedException e) {
 *           // timed amount was reached
 *       }
 * 
* * @version $Id: ThreadMonitor.java 1307459 2012-03-30 15:11:44Z ggregory $ */ class ThreadMonitor implements Runnable { private final Thread thread; private final long timeout; /** * Start monitoring the current thread. * * @param timeout The timout amount in milliseconds * or no timeout if the value is zero or less * @return The monitor thread or {@code null} * if the timout amount is not greater than zero */ public static Thread start(long timeout) { return start(Thread.currentThread(), timeout); } /** * Start monitoring the specified thread. * * @param thread The thread The thread to monitor * @param timeout The timout amount in milliseconds * or no timeout if the value is zero or less * @return The monitor thread or {@code null} * if the timout amount is not greater than zero */ public static Thread start(Thread thread, long timeout) { Thread monitor = null; if (timeout > 0) { ThreadMonitor timout = new ThreadMonitor(thread, timeout); monitor = new Thread(timout, ThreadMonitor.class.getSimpleName()); monitor.setDaemon(true); monitor.start(); } return monitor; } /** * Stop monitoring the specified thread. * * @param thread The monitor thread, may be {@code null} */ public static void stop(Thread thread) { if (thread != null) { thread.interrupt(); } } /** * Construct and new monitor. * * @param thread The thread to monitor * @param timeout The timout amount in milliseconds */ private ThreadMonitor(Thread thread, long timeout) { this.thread = thread; this.timeout = timeout; } /** * Sleep until the specified timout amount and then * interrupt the thread being monitored. * * @see Runnable#run() */ public void run() { try { Thread.sleep(timeout); thread.interrupt(); } catch (InterruptedException e) { // timeout not reached } } }libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/overview.html0000644000175000017500000000235212125050425026614 0ustar ebourgebourg

The commons-io component contains utility classes, filters, streams, readers and writers.

These classes aim to add to the standard JDK IO classes. The utilities provide convenience wrappers around the JDK, simplifying various operations into pre-tested units of code. The filters and streams provide useful implementations that perhaps should be in the JDK itself.

libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/IOExceptionWithCause.java0000644000175000017500000000465312125050425030734 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.io.IOException; /** * Subclasses IOException with the {@link Throwable} constructors missing before Java 6. If you are using Java 6, * consider this class deprecated and use {@link IOException}. * * @version $Id: IOExceptionWithCause.java 1307459 2012-03-30 15:11:44Z ggregory $ * @since 1.4 */ public class IOExceptionWithCause extends IOException { /** * Defines the serial version UID. */ private static final long serialVersionUID = 1L; /** * Constructs a new instance with the given message and cause. *

* As specified in {@link Throwable}, the message in the given cause is not used in this instance's * message. *

* * @param message * the message (see {@link #getMessage()}) * @param cause * the cause (see {@link #getCause()}). A {@code null} value is allowed. */ public IOExceptionWithCause(String message, Throwable cause) { super(message); this.initCause(cause); } /** * Constructs a new instance with the given cause. *

* The message is set to cause==null ? null : cause.toString(), which by default contains the class * and message of cause. This constructor is useful for call sites that just wrap another throwable. *

* * @param cause * the cause (see {@link #getCause()}). A {@code null} value is allowed. */ public IOExceptionWithCause(Throwable cause) { super(cause == null ? null : cause.toString()); this.initCause(cause); } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/CopyUtils.java0000644000175000017500000003142512125050425026661 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.StringReader; import java.io.Writer; /** * This class provides static utility methods for buffered * copying between sources (InputStream, Reader, * String and byte[]) and destinations * (OutputStream, Writer, String and * byte[]). *

* Unless otherwise noted, these copy methods do not * flush or close the streams. Often doing so would require making non-portable * assumptions about the streams' origin and further use. This means that both * streams' close() methods must be called after copying. if one * omits this step, then the stream resources (sockets, file descriptors) are * released when the associated Stream is garbage-collected. It is not a good * idea to rely on this mechanism. For a good overview of the distinction * between "memory management" and "resource management", see * this * UnixReview article. *

* For byte-to-char methods, a copy variant allows the encoding * to be selected (otherwise the platform default is used). We would like to * encourage you to always specify the encoding because relying on the platform * default can lead to unexpected results. *

copy methods that * let you specify the buffer size because in modern VMs the impact on speed * seems to be minimal. We're using a default buffer size of 4 KB. *

* The copy methods use an internal buffer when copying. It is * therefore advisable not to deliberately wrap the stream arguments * to the copy methods in Buffered* streams. For * example, don't do the following: *

 *  copy( new BufferedInputStream( in ), new BufferedOutputStream( out ) );
 *  
* The rationale is as follows: *

* Imagine that an InputStream's read() is a very expensive operation, which * would usually suggest wrapping in a BufferedInputStream. The * BufferedInputStream works by issuing infrequent * {@link java.io.InputStream#read(byte[] b, int off, int len)} requests on the * underlying InputStream, to fill an internal buffer, from which further * read requests can inexpensively get their data (until the buffer * runs out). *

* However, the copy methods do the same thing, keeping an * internal buffer, populated by * {@link InputStream#read(byte[] b, int off, int len)} requests. Having two * buffers (or three if the destination stream is also buffered) is pointless, * and the unnecessary buffer management hurts performance slightly (about 3%, * according to some simple experiments). *

* Behold, intrepid explorers; a map of this class: *

 *       Method      Input               Output          Dependency
 *       ------      -----               ------          -------
 * 1     copy        InputStream         OutputStream    (primitive)
 * 2     copy        Reader              Writer          (primitive)
 *
 * 3     copy        InputStream         Writer          2
 *
 * 4     copy        Reader              OutputStream    2
 *
 * 5     copy        String              OutputStream    2
 * 6     copy        String              Writer          (trivial)
 *
 * 7     copy        byte[]              Writer          3
 * 8     copy        byte[]              OutputStream    (trivial)
 * 
*

* Note that only the first two methods shuffle bytes; the rest use these * two, or (if possible) copy using native Java copy methods. As there are * method variants to specify the encoding, each row may * correspond to up to 2 methods. *

* Origin of code: Excalibur. * * @version $Id: CopyUtils.java 1302056 2012-03-18 03:03:38Z ggregory $ * @deprecated Use IOUtils. Will be removed in 2.0. * Methods renamed to IOUtils.write() or IOUtils.copy(). * Null handling behaviour changed in IOUtils (null data does not * throw NullPointerException). */ @Deprecated public class CopyUtils { /** * The default size of the buffer. */ private static final int DEFAULT_BUFFER_SIZE = 1024 * 4; /** * Instances should NOT be constructed in standard programming. */ public CopyUtils() { } // ---------------------------------------------------------------- // byte[] -> OutputStream // ---------------------------------------------------------------- /** * Copy bytes from a byte[] to an OutputStream. * @param input the byte array to read from * @param output the OutputStream to write to * @throws IOException In case of an I/O problem */ public static void copy(byte[] input, OutputStream output) throws IOException { output.write(input); } // ---------------------------------------------------------------- // byte[] -> Writer // ---------------------------------------------------------------- /** * Copy and convert bytes from a byte[] to chars on a * Writer. * The platform's default encoding is used for the byte-to-char conversion. * @param input the byte array to read from * @param output the Writer to write to * @throws IOException In case of an I/O problem */ public static void copy(byte[] input, Writer output) throws IOException { ByteArrayInputStream in = new ByteArrayInputStream(input); copy(in, output); } /** * Copy and convert bytes from a byte[] to chars on a * Writer, using the specified encoding. * @param input the byte array to read from * @param output the Writer to write to * @param encoding The name of a supported character encoding. See the * IANA * Charset Registry for a list of valid encoding types. * @throws IOException In case of an I/O problem */ public static void copy( byte[] input, Writer output, String encoding) throws IOException { ByteArrayInputStream in = new ByteArrayInputStream(input); copy(in, output, encoding); } // ---------------------------------------------------------------- // Core copy methods // ---------------------------------------------------------------- /** * Copy bytes from an InputStream to an * OutputStream. * @param input the InputStream to read from * @param output the OutputStream to write to * @return the number of bytes copied * @throws IOException In case of an I/O problem */ public static int copy( InputStream input, OutputStream output) throws IOException { byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; int count = 0; int n = 0; while (-1 != (n = input.read(buffer))) { output.write(buffer, 0, n); count += n; } return count; } // ---------------------------------------------------------------- // Reader -> Writer // ---------------------------------------------------------------- /** * Copy chars from a Reader to a Writer. * @param input the Reader to read from * @param output the Writer to write to * @return the number of characters copied * @throws IOException In case of an I/O problem */ public static int copy( Reader input, Writer output) throws IOException { char[] buffer = new char[DEFAULT_BUFFER_SIZE]; int count = 0; int n = 0; while (-1 != (n = input.read(buffer))) { output.write(buffer, 0, n); count += n; } return count; } // ---------------------------------------------------------------- // InputStream -> Writer // ---------------------------------------------------------------- /** * Copy and convert bytes from an InputStream to chars on a * Writer. * The platform's default encoding is used for the byte-to-char conversion. * @param input the InputStream to read from * @param output the Writer to write to * @throws IOException In case of an I/O problem */ public static void copy( InputStream input, Writer output) throws IOException { InputStreamReader in = new InputStreamReader(input); copy(in, output); } /** * Copy and convert bytes from an InputStream to chars on a * Writer, using the specified encoding. * @param input the InputStream to read from * @param output the Writer to write to * @param encoding The name of a supported character encoding. See the * IANA * Charset Registry for a list of valid encoding types. * @throws IOException In case of an I/O problem */ public static void copy( InputStream input, Writer output, String encoding) throws IOException { InputStreamReader in = new InputStreamReader(input, encoding); copy(in, output); } // ---------------------------------------------------------------- // Reader -> OutputStream // ---------------------------------------------------------------- /** * Serialize chars from a Reader to bytes on an * OutputStream, and flush the OutputStream. * @param input the Reader to read from * @param output the OutputStream to write to * @throws IOException In case of an I/O problem */ public static void copy( Reader input, OutputStream output) throws IOException { OutputStreamWriter out = new OutputStreamWriter(output); copy(input, out); // XXX Unless anyone is planning on rewriting OutputStreamWriter, we // have to flush here. out.flush(); } // ---------------------------------------------------------------- // String -> OutputStream // ---------------------------------------------------------------- /** * Serialize chars from a String to bytes on an * OutputStream, and * flush the OutputStream. * @param input the String to read from * @param output the OutputStream to write to * @throws IOException In case of an I/O problem */ public static void copy( String input, OutputStream output) throws IOException { StringReader in = new StringReader(input); OutputStreamWriter out = new OutputStreamWriter(output); copy(in, out); // XXX Unless anyone is planning on rewriting OutputStreamWriter, we // have to flush here. out.flush(); } // ---------------------------------------------------------------- // String -> Writer // ---------------------------------------------------------------- /** * Copy chars from a String to a Writer. * @param input the String to read from * @param output the Writer to write to * @throws IOException In case of an I/O problem */ public static void copy(String input, Writer output) throws IOException { output.write(input); } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/FileSystemUtils.java0000644000175000017500000005300712125050425030033 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.StringTokenizer; /** * General File System utilities. *

* This class provides static utility methods for general file system * functions not provided via the JDK {@link java.io.File File} class. *

* The current functions provided are: *

    *
  • Get the free space on a drive *
* * @version $Id: FileSystemUtils.java 1304052 2012-03-22 20:55:29Z ggregory $ * @since 1.1 */ public class FileSystemUtils { /** Singleton instance, used mainly for testing. */ private static final FileSystemUtils INSTANCE = new FileSystemUtils(); /** Operating system state flag for error. */ private static final int INIT_PROBLEM = -1; /** Operating system state flag for neither Unix nor Windows. */ private static final int OTHER = 0; /** Operating system state flag for Windows. */ private static final int WINDOWS = 1; /** Operating system state flag for Unix. */ private static final int UNIX = 2; /** Operating system state flag for Posix flavour Unix. */ private static final int POSIX_UNIX = 3; /** The operating system flag. */ private static final int OS; /** The path to df */ private static final String DF; static { int os = OTHER; String dfPath = "df"; try { String osName = System.getProperty("os.name"); if (osName == null) { throw new IOException("os.name not found"); } osName = osName.toLowerCase(Locale.ENGLISH); // match if (osName.indexOf("windows") != -1) { os = WINDOWS; } else if (osName.indexOf("linux") != -1 || osName.indexOf("mpe/ix") != -1 || osName.indexOf("freebsd") != -1 || osName.indexOf("irix") != -1 || osName.indexOf("digital unix") != -1 || osName.indexOf("unix") != -1 || osName.indexOf("mac os x") != -1) { os = UNIX; } else if (osName.indexOf("sun os") != -1 || osName.indexOf("sunos") != -1 || osName.indexOf("solaris") != -1) { os = POSIX_UNIX; dfPath = "/usr/xpg4/bin/df"; } else if (osName.indexOf("hp-ux") != -1 || osName.indexOf("aix") != -1) { os = POSIX_UNIX; } else { os = OTHER; } } catch (Exception ex) { os = INIT_PROBLEM; } OS = os; DF = dfPath; } /** * Instances should NOT be constructed in standard programming. */ public FileSystemUtils() { super(); } //----------------------------------------------------------------------- /** * Returns the free space on a drive or volume by invoking * the command line. * This method does not normalize the result, and typically returns * bytes on Windows, 512 byte units on OS X and kilobytes on Unix. * As this is not very useful, this method is deprecated in favour * of {@link #freeSpaceKb(String)} which returns a result in kilobytes. *

* Note that some OS's are NOT currently supported, including OS/390, * OpenVMS. *

     * FileSystemUtils.freeSpace("C:");       // Windows
     * FileSystemUtils.freeSpace("/volume");  // *nix
     * 
* The free space is calculated via the command line. * It uses 'dir /-c' on Windows and 'df' on *nix. * * @param path the path to get free space for, not null, not empty on Unix * @return the amount of free drive space on the drive or volume * @throws IllegalArgumentException if the path is invalid * @throws IllegalStateException if an error occurred in initialisation * @throws IOException if an error occurs when finding the free space * @since 1.1, enhanced OS support in 1.2 and 1.3 * @deprecated Use freeSpaceKb(String) * Deprecated from 1.3, may be removed in 2.0 */ @Deprecated public static long freeSpace(String path) throws IOException { return INSTANCE.freeSpaceOS(path, OS, false, -1); } //----------------------------------------------------------------------- /** * Returns the free space on a drive or volume in kilobytes by invoking * the command line. *
     * FileSystemUtils.freeSpaceKb("C:");       // Windows
     * FileSystemUtils.freeSpaceKb("/volume");  // *nix
     * 
* The free space is calculated via the command line. * It uses 'dir /-c' on Windows, 'df -kP' on AIX/HP-UX and 'df -k' on other Unix. *

* In order to work, you must be running Windows, or have a implementation of * Unix df that supports GNU format when passed -k (or -kP). If you are going * to rely on this code, please check that it works on your OS by running * some simple tests to compare the command line with the output from this class. * If your operating system isn't supported, please raise a JIRA call detailing * the exact result from df -k and as much other detail as possible, thanks. * * @param path the path to get free space for, not null, not empty on Unix * @return the amount of free drive space on the drive or volume in kilobytes * @throws IllegalArgumentException if the path is invalid * @throws IllegalStateException if an error occurred in initialisation * @throws IOException if an error occurs when finding the free space * @since 1.2, enhanced OS support in 1.3 */ public static long freeSpaceKb(String path) throws IOException { return freeSpaceKb(path, -1); } /** * Returns the free space on a drive or volume in kilobytes by invoking * the command line. *

     * FileSystemUtils.freeSpaceKb("C:");       // Windows
     * FileSystemUtils.freeSpaceKb("/volume");  // *nix
     * 
* The free space is calculated via the command line. * It uses 'dir /-c' on Windows, 'df -kP' on AIX/HP-UX and 'df -k' on other Unix. *

* In order to work, you must be running Windows, or have a implementation of * Unix df that supports GNU format when passed -k (or -kP). If you are going * to rely on this code, please check that it works on your OS by running * some simple tests to compare the command line with the output from this class. * If your operating system isn't supported, please raise a JIRA call detailing * the exact result from df -k and as much other detail as possible, thanks. * * @param path the path to get free space for, not null, not empty on Unix * @param timeout The timout amount in milliseconds or no timeout if the value * is zero or less * @return the amount of free drive space on the drive or volume in kilobytes * @throws IllegalArgumentException if the path is invalid * @throws IllegalStateException if an error occurred in initialisation * @throws IOException if an error occurs when finding the free space * @since 2.0 */ public static long freeSpaceKb(String path, long timeout) throws IOException { return INSTANCE.freeSpaceOS(path, OS, true, timeout); } /** * Returns the disk size of the volume which holds the working directory. *

* Identical to: *

     * freeSpaceKb(new File(".").getAbsolutePath())
     * 
* @return the amount of free drive space on the drive or volume in kilobytes * @throws IllegalStateException if an error occurred in initialisation * @throws IOException if an error occurs when finding the free space * @since 2.0 */ public static long freeSpaceKb() throws IOException { return freeSpaceKb(-1); } /** * Returns the disk size of the volume which holds the working directory. *

* Identical to: *

     * freeSpaceKb(new File(".").getAbsolutePath())
     * 
* @param timeout The timout amount in milliseconds or no timeout if the value * is zero or less * @return the amount of free drive space on the drive or volume in kilobytes * @throws IllegalStateException if an error occurred in initialisation * @throws IOException if an error occurs when finding the free space * @since 2.0 */ public static long freeSpaceKb(long timeout) throws IOException { return freeSpaceKb(new File(".").getAbsolutePath(), timeout); } //----------------------------------------------------------------------- /** * Returns the free space on a drive or volume in a cross-platform manner. * Note that some OS's are NOT currently supported, including OS/390. *
     * FileSystemUtils.freeSpace("C:");  // Windows
     * FileSystemUtils.freeSpace("/volume");  // *nix
     * 
* The free space is calculated via the command line. * It uses 'dir /-c' on Windows and 'df' on *nix. * * @param path the path to get free space for, not null, not empty on Unix * @param os the operating system code * @param kb whether to normalize to kilobytes * @param timeout The timout amount in milliseconds or no timeout if the value * is zero or less * @return the amount of free drive space on the drive or volume * @throws IllegalArgumentException if the path is invalid * @throws IllegalStateException if an error occurred in initialisation * @throws IOException if an error occurs when finding the free space */ long freeSpaceOS(String path, int os, boolean kb, long timeout) throws IOException { if (path == null) { throw new IllegalArgumentException("Path must not be empty"); } switch (os) { case WINDOWS: return kb ? freeSpaceWindows(path, timeout) / FileUtils.ONE_KB : freeSpaceWindows(path, timeout); case UNIX: return freeSpaceUnix(path, kb, false, timeout); case POSIX_UNIX: return freeSpaceUnix(path, kb, true, timeout); case OTHER: throw new IllegalStateException("Unsupported operating system"); default: throw new IllegalStateException( "Exception caught when determining operating system"); } } //----------------------------------------------------------------------- /** * Find free space on the Windows platform using the 'dir' command. * * @param path the path to get free space for, including the colon * @param timeout The timout amount in milliseconds or no timeout if the value * is zero or less * @return the amount of free drive space on the drive * @throws IOException if an error occurs */ long freeSpaceWindows(String path, long timeout) throws IOException { path = FilenameUtils.normalize(path, false); if (path.length() > 0 && path.charAt(0) != '"') { path = "\"" + path + "\""; } // build and run the 'dir' command String[] cmdAttribs = new String[] {"cmd.exe", "/C", "dir /a /-c " + path}; // read in the output of the command to an ArrayList List lines = performCommand(cmdAttribs, Integer.MAX_VALUE, timeout); // now iterate over the lines we just read and find the LAST // non-empty line (the free space bytes should be in the last element // of the ArrayList anyway, but this will ensure it works even if it's // not, still assuming it is on the last non-blank line) for (int i = lines.size() - 1; i >= 0; i--) { String line = lines.get(i); if (line.length() > 0) { return parseDir(line, path); } } // all lines are blank throw new IOException( "Command line 'dir /-c' did not return any info " + "for path '" + path + "'"); } /** * Parses the Windows dir response last line * * @param line the line to parse * @param path the path that was sent * @return the number of bytes * @throws IOException if an error occurs */ long parseDir(String line, String path) throws IOException { // read from the end of the line to find the last numeric // character on the line, then continue until we find the first // non-numeric character, and everything between that and the last // numeric character inclusive is our free space bytes count int bytesStart = 0; int bytesEnd = 0; int j = line.length() - 1; innerLoop1: while (j >= 0) { char c = line.charAt(j); if (Character.isDigit(c)) { // found the last numeric character, this is the end of // the free space bytes count bytesEnd = j + 1; break innerLoop1; } j--; } innerLoop2: while (j >= 0) { char c = line.charAt(j); if (!Character.isDigit(c) && c != ',' && c != '.') { // found the next non-numeric character, this is the // beginning of the free space bytes count bytesStart = j + 1; break innerLoop2; } j--; } if (j < 0) { throw new IOException( "Command line 'dir /-c' did not return valid info " + "for path '" + path + "'"); } // remove commas and dots in the bytes count StringBuilder buf = new StringBuilder(line.substring(bytesStart, bytesEnd)); for (int k = 0; k < buf.length(); k++) { if (buf.charAt(k) == ',' || buf.charAt(k) == '.') { buf.deleteCharAt(k--); } } return parseBytes(buf.toString(), path); } //----------------------------------------------------------------------- /** * Find free space on the *nix platform using the 'df' command. * * @param path the path to get free space for * @param kb whether to normalize to kilobytes * @param posix whether to use the posix standard format flag * @param timeout The timout amount in milliseconds or no timeout if the value * is zero or less * @return the amount of free drive space on the volume * @throws IOException if an error occurs */ long freeSpaceUnix(String path, boolean kb, boolean posix, long timeout) throws IOException { if (path.length() == 0) { throw new IllegalArgumentException("Path must not be empty"); } // build and run the 'dir' command String flags = "-"; if (kb) { flags += "k"; } if (posix) { flags += "P"; } String[] cmdAttribs = flags.length() > 1 ? new String[] {DF, flags, path} : new String[] {DF, path}; // perform the command, asking for up to 3 lines (header, interesting, overflow) List lines = performCommand(cmdAttribs, 3, timeout); if (lines.size() < 2) { // unknown problem, throw exception throw new IOException( "Command line '" + DF + "' did not return info as expected " + "for path '" + path + "'- response was " + lines); } String line2 = lines.get(1); // the line we're interested in // Now, we tokenize the string. The fourth element is what we want. StringTokenizer tok = new StringTokenizer(line2, " "); if (tok.countTokens() < 4) { // could be long Filesystem, thus data on third line if (tok.countTokens() == 1 && lines.size() >= 3) { String line3 = lines.get(2); // the line may be interested in tok = new StringTokenizer(line3, " "); } else { throw new IOException( "Command line '" + DF + "' did not return data as expected " + "for path '" + path + "'- check path is valid"); } } else { tok.nextToken(); // Ignore Filesystem } tok.nextToken(); // Ignore 1K-blocks tok.nextToken(); // Ignore Used String freeSpace = tok.nextToken(); return parseBytes(freeSpace, path); } //----------------------------------------------------------------------- /** * Parses the bytes from a string. * * @param freeSpace the free space string * @param path the path * @return the number of bytes * @throws IOException if an error occurs */ long parseBytes(String freeSpace, String path) throws IOException { try { long bytes = Long.parseLong(freeSpace); if (bytes < 0) { throw new IOException( "Command line '" + DF + "' did not find free space in response " + "for path '" + path + "'- check path is valid"); } return bytes; } catch (NumberFormatException ex) { throw new IOExceptionWithCause( "Command line '" + DF + "' did not return numeric data as expected " + "for path '" + path + "'- check path is valid", ex); } } //----------------------------------------------------------------------- /** * Performs the os command. * * @param cmdAttribs the command line parameters * @param max The maximum limit for the lines returned * @param timeout The timout amount in milliseconds or no timeout if the value * is zero or less * @return the parsed data * @throws IOException if an error occurs */ List performCommand(String[] cmdAttribs, int max, long timeout) throws IOException { // this method does what it can to avoid the 'Too many open files' error // based on trial and error and these links: // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4784692 // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4801027 // http://forum.java.sun.com/thread.jspa?threadID=533029&messageID=2572018 // however, its still not perfect as the JDK support is so poor // (see commond-exec or ant for a better multi-threaded multi-os solution) List lines = new ArrayList(20); Process proc = null; InputStream in = null; OutputStream out = null; InputStream err = null; BufferedReader inr = null; try { Thread monitor = ThreadMonitor.start(timeout); proc = openProcess(cmdAttribs); in = proc.getInputStream(); out = proc.getOutputStream(); err = proc.getErrorStream(); inr = new BufferedReader(new InputStreamReader(in)); String line = inr.readLine(); while (line != null && lines.size() < max) { line = line.toLowerCase(Locale.ENGLISH).trim(); lines.add(line); line = inr.readLine(); } proc.waitFor(); ThreadMonitor.stop(monitor); if (proc.exitValue() != 0) { // os command problem, throw exception throw new IOException( "Command line returned OS error code '" + proc.exitValue() + "' for command " + Arrays.asList(cmdAttribs)); } if (lines.isEmpty()) { // unknown problem, throw exception throw new IOException( "Command line did not return any info " + "for command " + Arrays.asList(cmdAttribs)); } return lines; } catch (InterruptedException ex) { throw new IOExceptionWithCause( "Command line threw an InterruptedException " + "for command " + Arrays.asList(cmdAttribs) + " timeout=" + timeout, ex); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); IOUtils.closeQuietly(err); IOUtils.closeQuietly(inr); if (proc != null) { proc.destroy(); } } } /** * Opens the process to the operating system. * * @param cmdAttribs the command line parameters * @return the process * @throws IOException if an error occurs */ Process openProcess(String[] cmdAttribs) throws IOException { return Runtime.getRuntime().exec(cmdAttribs); } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/FileCleaner.java0000644000175000017500000001551412125050425027100 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.io.File; /** * Keeps track of files awaiting deletion, and deletes them when an associated * marker object is reclaimed by the garbage collector. *

* This utility creates a background thread to handle file deletion. * Each file to be deleted is registered with a handler object. * When the handler object is garbage collected, the file is deleted. *

* In an environment with multiple class loaders (a servlet container, for * example), you should consider stopping the background thread if it is no * longer needed. This is done by invoking the method * {@link #exitWhenFinished}, typically in * {@link javax.servlet.ServletContextListener#contextDestroyed} or similar. * * @version $Id: FileCleaner.java 1302056 2012-03-18 03:03:38Z ggregory $ * @deprecated Use {@link FileCleaningTracker} */ @Deprecated public class FileCleaner { /** * The instance to use for the deprecated, static methods. */ static final FileCleaningTracker theInstance = new FileCleaningTracker(); //----------------------------------------------------------------------- /** * Track the specified file, using the provided marker, deleting the file * when the marker instance is garbage collected. * The {@link FileDeleteStrategy#NORMAL normal} deletion strategy will be used. * * @param file the file to be tracked, not null * @param marker the marker object used to track the file, not null * @throws NullPointerException if the file is null * @deprecated Use {@link FileCleaningTracker#track(File, Object)}. */ @Deprecated public static void track(File file, Object marker) { theInstance.track(file, marker); } /** * Track the specified file, using the provided marker, deleting the file * when the marker instance is garbage collected. * The speified deletion strategy is used. * * @param file the file to be tracked, not null * @param marker the marker object used to track the file, not null * @param deleteStrategy the strategy to delete the file, null means normal * @throws NullPointerException if the file is null * @deprecated Use {@link FileCleaningTracker#track(File, Object, FileDeleteStrategy)}. */ @Deprecated public static void track(File file, Object marker, FileDeleteStrategy deleteStrategy) { theInstance.track(file, marker, deleteStrategy); } /** * Track the specified file, using the provided marker, deleting the file * when the marker instance is garbage collected. * The {@link FileDeleteStrategy#NORMAL normal} deletion strategy will be used. * * @param path the full path to the file to be tracked, not null * @param marker the marker object used to track the file, not null * @throws NullPointerException if the path is null * @deprecated Use {@link FileCleaningTracker#track(String, Object)}. */ @Deprecated public static void track(String path, Object marker) { theInstance.track(path, marker); } /** * Track the specified file, using the provided marker, deleting the file * when the marker instance is garbage collected. * The speified deletion strategy is used. * * @param path the full path to the file to be tracked, not null * @param marker the marker object used to track the file, not null * @param deleteStrategy the strategy to delete the file, null means normal * @throws NullPointerException if the path is null * @deprecated Use {@link FileCleaningTracker#track(String, Object, FileDeleteStrategy)}. */ @Deprecated public static void track(String path, Object marker, FileDeleteStrategy deleteStrategy) { theInstance.track(path, marker, deleteStrategy); } //----------------------------------------------------------------------- /** * Retrieve the number of files currently being tracked, and therefore * awaiting deletion. * * @return the number of files being tracked * @deprecated Use {@link FileCleaningTracker#getTrackCount()}. */ @Deprecated public static int getTrackCount() { return theInstance.getTrackCount(); } /** * Call this method to cause the file cleaner thread to terminate when * there are no more objects being tracked for deletion. *

* In a simple environment, you don't need this method as the file cleaner * thread will simply exit when the JVM exits. In a more complex environment, * with multiple class loaders (such as an application server), you should be * aware that the file cleaner thread will continue running even if the class * loader it was started from terminates. This can consitute a memory leak. *

* For example, suppose that you have developed a web application, which * contains the commons-io jar file in your WEB-INF/lib directory. In other * words, the FileCleaner class is loaded through the class loader of your * web application. If the web application is terminated, but the servlet * container is still running, then the file cleaner thread will still exist, * posing a memory leak. *

* This method allows the thread to be terminated. Simply call this method * in the resource cleanup code, such as {@link javax.servlet.ServletContextListener#contextDestroyed}. * One called, no new objects can be tracked by the file cleaner. * @deprecated Use {@link FileCleaningTracker#exitWhenFinished()}. */ @Deprecated public static synchronized void exitWhenFinished() { theInstance.exitWhenFinished(); } /** * Returns the singleton instance, which is used by the deprecated, static methods. * This is mainly useful for code, which wants to support the new * {@link FileCleaningTracker} class while maintain compatibility with the * deprecated {@link FileCleaner}. * * @return the singleton instance */ public static FileCleaningTracker getInstance() { return theInstance; } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/IOUtils.java0000644000175000017500000027720412125050425026265 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.CharArrayWriter; import java.io.Closeable; import java.io.EOFException; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.net.HttpURLConnection; import java.net.ServerSocket; import java.net.Socket; import java.net.URI; import java.net.URL; import java.net.URLConnection; import java.nio.channels.Selector; import java.nio.charset.Charset; import java.nio.charset.UnsupportedCharsetException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.apache.commons.io.output.ByteArrayOutputStream; import org.apache.commons.io.output.StringBuilderWriter; /** * General IO stream manipulation utilities. *

* This class provides static utility methods for input/output operations. *

    *
  • closeQuietly - these methods close a stream ignoring nulls and exceptions *
  • toXxx/read - these methods read data from a stream *
  • write - these methods write data to a stream *
  • copy - these methods copy all the data from one stream to another *
  • contentEquals - these methods compare the content of two streams *
*

* The byte-to-char methods and char-to-byte methods involve a conversion step. * Two methods are provided in each case, one that uses the platform default * encoding and the other which allows you to specify an encoding. You are * encouraged to always specify an encoding because relying on the platform * default can lead to unexpected results, for example when moving from * development to production. *

* All the methods in this class that read a stream are buffered internally. * This means that there is no cause to use a BufferedInputStream * or BufferedReader. The default buffer size of 4K has been shown * to be efficient in tests. *

* Wherever possible, the methods in this class do not flush or close * the stream. This is to avoid making non-portable assumptions about the * streams' origin and further use. Thus the caller is still responsible for * closing streams after use. *

* Origin of code: Excalibur. * * @version $Id: IOUtils.java 1326636 2012-04-16 14:54:53Z ggregory $ */ public class IOUtils { // NOTE: This class is focussed on InputStream, OutputStream, Reader and // Writer. Each method should take at least one of these as a parameter, // or return one of them. private static final int EOF = -1; /** * The Unix directory separator character. */ public static final char DIR_SEPARATOR_UNIX = '/'; /** * The Windows directory separator character. */ public static final char DIR_SEPARATOR_WINDOWS = '\\'; /** * The system directory separator character. */ public static final char DIR_SEPARATOR = File.separatorChar; /** * The Unix line separator string. */ public static final String LINE_SEPARATOR_UNIX = "\n"; /** * The Windows line separator string. */ public static final String LINE_SEPARATOR_WINDOWS = "\r\n"; /** * The system line separator string. */ public static final String LINE_SEPARATOR; static { // avoid security issues StringBuilderWriter buf = new StringBuilderWriter(4); PrintWriter out = new PrintWriter(buf); out.println(); LINE_SEPARATOR = buf.toString(); out.close(); } /** * The default buffer size ({@value}) to use for * {@link #copyLarge(InputStream, OutputStream)} * and * {@link #copyLarge(Reader, Writer)} */ private static final int DEFAULT_BUFFER_SIZE = 1024 * 4; /** * The default buffer size to use for the skip() methods. */ private static final int SKIP_BUFFER_SIZE = 2048; // Allocated in the relevant skip method if necessary. /* * N.B. no need to synchronize these because: * - we don't care if the buffer is created multiple times (the data is ignored) * - we always use the same size buffer, so if it it is recreated it will still be OK * (if the buffer size were variable, we would need to synch. to ensure some other thread * did not create a smaller one) */ private static char[] SKIP_CHAR_BUFFER; private static byte[] SKIP_BYTE_BUFFER; /** * Instances should NOT be constructed in standard programming. */ public IOUtils() { super(); } //----------------------------------------------------------------------- /** * Closes a URLConnection. * * @param conn the connection to close. * @since 2.4 */ public static void close(URLConnection conn) { if (conn instanceof HttpURLConnection) { ((HttpURLConnection) conn).disconnect(); } } /** * Unconditionally close an Reader. *

* Equivalent to {@link Reader#close()}, except any exceptions will be ignored. * This is typically used in finally blocks. *

* Example code: *

     *   char[] data = new char[1024];
     *   Reader in = null;
     *   try {
     *       in = new FileReader("foo.txt");
     *       in.read(data);
     *       in.close(); //close errors are handled
     *   } catch (Exception e) {
     *       // error handling
     *   } finally {
     *       IOUtils.closeQuietly(in);
     *   }
     * 
* * @param input the Reader to close, may be null or already closed */ public static void closeQuietly(Reader input) { closeQuietly((Closeable)input); } /** * Unconditionally close a Writer. *

* Equivalent to {@link Writer#close()}, except any exceptions will be ignored. * This is typically used in finally blocks. *

* Example code: *

     *   Writer out = null;
     *   try {
     *       out = new StringWriter();
     *       out.write("Hello World");
     *       out.close(); //close errors are handled
     *   } catch (Exception e) {
     *       // error handling
     *   } finally {
     *       IOUtils.closeQuietly(out);
     *   }
     * 
* * @param output the Writer to close, may be null or already closed */ public static void closeQuietly(Writer output) { closeQuietly((Closeable)output); } /** * Unconditionally close an InputStream. *

* Equivalent to {@link InputStream#close()}, except any exceptions will be ignored. * This is typically used in finally blocks. *

* Example code: *

     *   byte[] data = new byte[1024];
     *   InputStream in = null;
     *   try {
     *       in = new FileInputStream("foo.txt");
     *       in.read(data);
     *       in.close(); //close errors are handled
     *   } catch (Exception e) {
     *       // error handling
     *   } finally {
     *       IOUtils.closeQuietly(in);
     *   }
     * 
* * @param input the InputStream to close, may be null or already closed */ public static void closeQuietly(InputStream input) { closeQuietly((Closeable)input); } /** * Unconditionally close an OutputStream. *

* Equivalent to {@link OutputStream#close()}, except any exceptions will be ignored. * This is typically used in finally blocks. *

* Example code: *

     * byte[] data = "Hello, World".getBytes();
     *
     * OutputStream out = null;
     * try {
     *     out = new FileOutputStream("foo.txt");
     *     out.write(data);
     *     out.close(); //close errors are handled
     * } catch (IOException e) {
     *     // error handling
     * } finally {
     *     IOUtils.closeQuietly(out);
     * }
     * 
* * @param output the OutputStream to close, may be null or already closed */ public static void closeQuietly(OutputStream output) { closeQuietly((Closeable)output); } /** * Unconditionally close a Closeable. *

* Equivalent to {@link Closeable#close()}, except any exceptions will be ignored. * This is typically used in finally blocks. *

* Example code: *

     *   Closeable closeable = null;
     *   try {
     *       closeable = new FileReader("foo.txt");
     *       // process closeable
     *       closeable.close();
     *   } catch (Exception e) {
     *       // error handling
     *   } finally {
     *       IOUtils.closeQuietly(closeable);
     *   }
     * 
* * @param closeable the object to close, may be null or already closed * @since 2.0 */ public static void closeQuietly(Closeable closeable) { try { if (closeable != null) { closeable.close(); } } catch (IOException ioe) { // ignore } } /** * Unconditionally close a Socket. *

* Equivalent to {@link Socket#close()}, except any exceptions will be ignored. * This is typically used in finally blocks. *

* Example code: *

     *   Socket socket = null;
     *   try {
     *       socket = new Socket("http://www.foo.com/", 80);
     *       // process socket
     *       socket.close();
     *   } catch (Exception e) {
     *       // error handling
     *   } finally {
     *       IOUtils.closeQuietly(socket);
     *   }
     * 
* * @param sock the Socket to close, may be null or already closed * @since 2.0 */ public static void closeQuietly(Socket sock){ if (sock != null){ try { sock.close(); } catch (IOException ioe) { // ignored } } } /** * Unconditionally close a Selector. *

* Equivalent to {@link Selector#close()}, except any exceptions will be ignored. * This is typically used in finally blocks. *

* Example code: *

     *   Selector selector = null;
     *   try {
     *       selector = Selector.open();
     *       // process socket
     *       
     *   } catch (Exception e) {
     *       // error handling
     *   } finally {
     *       IOUtils.closeQuietly(selector);
     *   }
     * 
* * @param selector the Selector to close, may be null or already closed * @since 2.2 */ public static void closeQuietly(Selector selector){ if (selector != null){ try { selector.close(); } catch (IOException ioe) { // ignored } } } /** * Unconditionally close a ServerSocket. *

* Equivalent to {@link ServerSocket#close()}, except any exceptions will be ignored. * This is typically used in finally blocks. *

* Example code: *

     *   ServerSocket socket = null;
     *   try {
     *       socket = new ServerSocket();
     *       // process socket
     *       socket.close();
     *   } catch (Exception e) {
     *       // error handling
     *   } finally {
     *       IOUtils.closeQuietly(socket);
     *   }
     * 
* * @param sock the ServerSocket to close, may be null or already closed * @since 2.2 */ public static void closeQuietly(ServerSocket sock){ if (sock != null){ try { sock.close(); } catch (IOException ioe) { // ignored } } } /** * Fetches entire contents of an InputStream and represent * same data as result InputStream. *

* This method is useful where, *

    *
  • Source InputStream is slow.
  • *
  • It has network resources associated, so we cannot keep it open for * long time.
  • *
  • It has network timeout associated.
  • *
* It can be used in favor of {@link #toByteArray(InputStream)}, since it * avoids unnecessary allocation and copy of byte[].
* This method buffers the input internally, so there is no need to use a * BufferedInputStream. * * @param input Stream to be fully buffered. * @return A fully buffered stream. * @throws IOException if an I/O error occurs * @since 2.0 */ public static InputStream toBufferedInputStream(InputStream input) throws IOException { return ByteArrayOutputStream.toBufferedInputStream(input); } /** * Returns the given reader if it is a {@link BufferedReader}, otherwise creates a toBufferedReader for the given * reader. * * @param reader * the reader to wrap or return * @return the given reader or a new {@link BufferedReader} for the given reader * @since 2.2 */ public static BufferedReader toBufferedReader(Reader reader) { return reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader); } // read toByteArray //----------------------------------------------------------------------- /** * Get the contents of an InputStream as a byte[]. *

* This method buffers the input internally, so there is no need to use a * BufferedInputStream. * * @param input the InputStream to read from * @return the requested byte array * @throws NullPointerException if the input is null * @throws IOException if an I/O error occurs */ public static byte[] toByteArray(InputStream input) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); copy(input, output); return output.toByteArray(); } /** * Get contents of an InputStream as a byte[]. * Use this method instead of toByteArray(InputStream) * when InputStream size is known. * NOTE: the method checks that the length can safely be cast to an int without truncation * before using {@link IOUtils#toByteArray(java.io.InputStream, int)} to read into the byte array. * (Arrays can have no more than Integer.MAX_VALUE entries anyway) * * @param input the InputStream to read from * @param size the size of InputStream * @return the requested byte array * @throws IOException if an I/O error occurs or InputStream size differ from parameter size * @throws IllegalArgumentException if size is less than zero or size is greater than Integer.MAX_VALUE * @see IOUtils#toByteArray(java.io.InputStream, int) * @since 2.1 */ public static byte[] toByteArray(InputStream input, long size) throws IOException { if(size > Integer.MAX_VALUE) { throw new IllegalArgumentException("Size cannot be greater than Integer max value: " + size); } return toByteArray(input, (int) size); } /** * Get the contents of an InputStream as a byte[]. * Use this method instead of toByteArray(InputStream) * when InputStream size is known * @param input the InputStream to read from * @param size the size of InputStream * @return the requested byte array * @throws IOException if an I/O error occurs or InputStream size differ from parameter size * @throws IllegalArgumentException if size is less than zero * @since 2.1 */ public static byte[] toByteArray(InputStream input, int size) throws IOException { if (size < 0) { throw new IllegalArgumentException("Size must be equal or greater than zero: " + size); } if (size == 0) { return new byte[0]; } byte[] data = new byte[size]; int offset = 0; int readed; while (offset < size && (readed = input.read(data, offset, size - offset)) != EOF) { offset += readed; } if (offset != size) { throw new IOException("Unexpected readed size. current: " + offset + ", excepted: " + size); } return data; } /** * Get the contents of a Reader as a byte[] * using the default character encoding of the platform. *

* This method buffers the input internally, so there is no need to use a * BufferedReader. * * @param input the Reader to read from * @return the requested byte array * @throws NullPointerException if the input is null * @throws IOException if an I/O error occurs */ public static byte[] toByteArray(Reader input) throws IOException { return toByteArray(input, Charset.defaultCharset()); } /** * Get the contents of a Reader as a byte[] * using the specified character encoding. *

* This method buffers the input internally, so there is no need to use a * BufferedReader. * * @param input the Reader to read from * @param encoding the encoding to use, null means platform default * @return the requested byte array * @throws NullPointerException if the input is null * @throws IOException if an I/O error occurs * @since 2.3 */ public static byte[] toByteArray(Reader input, Charset encoding) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); copy(input, output, encoding); return output.toByteArray(); } /** * Get the contents of a Reader as a byte[] * using the specified character encoding. *

* Character encoding names can be found at * IANA. *

* This method buffers the input internally, so there is no need to use a * BufferedReader. * * @param input the Reader to read from * @param encoding the encoding to use, null means platform default * @return the requested byte array * @throws NullPointerException if the input is null * @throws IOException if an I/O error occurs * @throws UnsupportedCharsetException * thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not * supported. * @since 1.1 */ public static byte[] toByteArray(Reader input, String encoding) throws IOException { return toByteArray(input, Charsets.toCharset(encoding)); } /** * Get the contents of a String as a byte[] * using the default character encoding of the platform. *

* This is the same as {@link String#getBytes()}. * * @param input the String to convert * @return the requested byte array * @throws NullPointerException if the input is null * @throws IOException if an I/O error occurs (never occurs) * @deprecated Use {@link String#getBytes()} */ @Deprecated public static byte[] toByteArray(String input) throws IOException { return input.getBytes(); } /** * Get the contents of a URI as a byte[]. * * @param uri * the URI to read * @return the requested byte array * @throws NullPointerException * if the uri is null * @throws IOException * if an I/O exception occurs * @since 2.4 */ public static byte[] toByteArray(URI uri) throws IOException { return IOUtils.toByteArray(uri.toURL()); } /** * Get the contents of a URL as a byte[]. * * @param url * the URL to read * @return the requested byte array * @throws NullPointerException * if the input is null * @throws IOException * if an I/O exception occurs * @since 2.4 */ public static byte[] toByteArray(URL url) throws IOException { URLConnection conn = url.openConnection(); try { return IOUtils.toByteArray(conn); } finally { close(conn); } } /** * Get the contents of a URLConnection as a byte[]. * * @param urlConn * the URLConnection to read * @return the requested byte array * @throws NullPointerException * if the urlConn is null * @throws IOException * if an I/O exception occurs * @since 2.4 */ public static byte[] toByteArray(URLConnection urlConn) throws IOException { InputStream inputStream = urlConn.getInputStream(); try { return IOUtils.toByteArray(inputStream); } finally { inputStream.close(); } } // read char[] //----------------------------------------------------------------------- /** * Get the contents of an InputStream as a character array * using the default character encoding of the platform. *

* This method buffers the input internally, so there is no need to use a * BufferedInputStream. * * @param is the InputStream to read from * @return the requested character array * @throws NullPointerException if the input is null * @throws IOException if an I/O error occurs * @since 1.1 */ public static char[] toCharArray(InputStream is) throws IOException { return toCharArray(is, Charset.defaultCharset()); } /** * Get the contents of an InputStream as a character array * using the specified character encoding. *

* This method buffers the input internally, so there is no need to use a * BufferedInputStream. * * @param is the InputStream to read from * @param encoding the encoding to use, null means platform default * @return the requested character array * @throws NullPointerException if the input is null * @throws IOException if an I/O error occurs * @since 2.3 */ public static char[] toCharArray(InputStream is, Charset encoding) throws IOException { CharArrayWriter output = new CharArrayWriter(); copy(is, output, encoding); return output.toCharArray(); } /** * Get the contents of an InputStream as a character array * using the specified character encoding. *

* Character encoding names can be found at * IANA. *

* This method buffers the input internally, so there is no need to use a * BufferedInputStream. * * @param is the InputStream to read from * @param encoding the encoding to use, null means platform default * @return the requested character array * @throws NullPointerException if the input is null * @throws IOException if an I/O error occurs * @throws UnsupportedCharsetException * thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not * supported. * @since 1.1 */ public static char[] toCharArray(InputStream is, String encoding) throws IOException { return toCharArray(is, Charsets.toCharset(encoding)); } /** * Get the contents of a Reader as a character array. *

* This method buffers the input internally, so there is no need to use a * BufferedReader. * * @param input the Reader to read from * @return the requested character array * @throws NullPointerException if the input is null * @throws IOException if an I/O error occurs * @since 1.1 */ public static char[] toCharArray(Reader input) throws IOException { CharArrayWriter sw = new CharArrayWriter(); copy(input, sw); return sw.toCharArray(); } // read toString //----------------------------------------------------------------------- /** * Get the contents of an InputStream as a String * using the default character encoding of the platform. *

* This method buffers the input internally, so there is no need to use a * BufferedInputStream. * * @param input the InputStream to read from * @return the requested String * @throws NullPointerException if the input is null * @throws IOException if an I/O error occurs */ public static String toString(InputStream input) throws IOException { return toString(input, Charset.defaultCharset()); } /** * Get the contents of an InputStream as a String * using the specified character encoding. *

* This method buffers the input internally, so there is no need to use a * BufferedInputStream. *

* @param input the InputStream to read from * @param encoding the encoding to use, null means platform default * @return the requested String * @throws NullPointerException if the input is null * @throws IOException if an I/O error occurs * @since 2.3 */ public static String toString(InputStream input, Charset encoding) throws IOException { StringBuilderWriter sw = new StringBuilderWriter(); copy(input, sw, encoding); return sw.toString(); } /** * Get the contents of an InputStream as a String * using the specified character encoding. *

* Character encoding names can be found at * IANA. *

* This method buffers the input internally, so there is no need to use a * BufferedInputStream. * * @param input the InputStream to read from * @param encoding the encoding to use, null means platform default * @return the requested String * @throws NullPointerException if the input is null * @throws IOException if an I/O error occurs * @throws UnsupportedCharsetException * thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not * supported. */ public static String toString(InputStream input, String encoding) throws IOException { return toString(input, Charsets.toCharset(encoding)); } /** * Get the contents of a Reader as a String. *

* This method buffers the input internally, so there is no need to use a * BufferedReader. * * @param input the Reader to read from * @return the requested String * @throws NullPointerException if the input is null * @throws IOException if an I/O error occurs */ public static String toString(Reader input) throws IOException { StringBuilderWriter sw = new StringBuilderWriter(); copy(input, sw); return sw.toString(); } /** * Gets the contents at the given URI. * * @param uri * The URI source. * @return The contents of the URL as a String. * @throws IOException if an I/O exception occurs. * @since 2.1 */ public static String toString(URI uri) throws IOException { return toString(uri, Charset.defaultCharset()); } /** * Gets the contents at the given URI. * * @param uri * The URI source. * @param encoding * The encoding name for the URL contents. * @return The contents of the URL as a String. * @throws IOException if an I/O exception occurs. * @since 2.3. */ public static String toString(URI uri, Charset encoding) throws IOException { return toString(uri.toURL(), Charsets.toCharset(encoding)); } /** * Gets the contents at the given URI. * * @param uri * The URI source. * @param encoding * The encoding name for the URL contents. * @return The contents of the URL as a String. * @throws IOException if an I/O exception occurs. * @throws UnsupportedCharsetException * thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not * supported. * @since 2.1 */ public static String toString(URI uri, String encoding) throws IOException { return toString(uri, Charsets.toCharset(encoding)); } /** * Gets the contents at the given URL. * * @param url * The URL source. * @return The contents of the URL as a String. * @throws IOException if an I/O exception occurs. * @since 2.1 */ public static String toString(URL url) throws IOException { return toString(url, Charset.defaultCharset()); } /** * Gets the contents at the given URL. * * @param url * The URL source. * @param encoding * The encoding name for the URL contents. * @return The contents of the URL as a String. * @throws IOException if an I/O exception occurs. * @since 2.3 */ public static String toString(URL url, Charset encoding) throws IOException { InputStream inputStream = url.openStream(); try { return toString(inputStream, encoding); } finally { inputStream.close(); } } /** * Gets the contents at the given URL. * * @param url * The URL source. * @param encoding * The encoding name for the URL contents. * @return The contents of the URL as a String. * @throws IOException if an I/O exception occurs. * @throws UnsupportedCharsetException * thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not * supported. * @since 2.1 */ public static String toString(URL url, String encoding) throws IOException { return toString(url, Charsets.toCharset(encoding)); } /** * Get the contents of a byte[] as a String * using the default character encoding of the platform. * * @param input the byte array to read from * @return the requested String * @throws NullPointerException if the input is null * @throws IOException if an I/O error occurs (never occurs) * @deprecated Use {@link String#String(byte[])} */ @Deprecated public static String toString(byte[] input) throws IOException { return new String(input); } /** * Get the contents of a byte[] as a String * using the specified character encoding. *

* Character encoding names can be found at * IANA. * * @param input the byte array to read from * @param encoding the encoding to use, null means platform default * @return the requested String * @throws NullPointerException if the input is null * @throws IOException if an I/O error occurs (never occurs) */ public static String toString(byte[] input, String encoding) throws IOException { return new String(input, Charsets.toCharset(encoding)); } // readLines //----------------------------------------------------------------------- /** * Get the contents of an InputStream as a list of Strings, * one entry per line, using the default character encoding of the platform. *

* This method buffers the input internally, so there is no need to use a * BufferedInputStream. * * @param input the InputStream to read from, not null * @return the list of Strings, never null * @throws NullPointerException if the input is null * @throws IOException if an I/O error occurs * @since 1.1 */ public static List readLines(InputStream input) throws IOException { return readLines(input, Charset.defaultCharset()); } /** * Get the contents of an InputStream as a list of Strings, * one entry per line, using the specified character encoding. *

* This method buffers the input internally, so there is no need to use a * BufferedInputStream. * * @param input the InputStream to read from, not null * @param encoding the encoding to use, null means platform default * @return the list of Strings, never null * @throws NullPointerException if the input is null * @throws IOException if an I/O error occurs * @since 2.3 */ public static List readLines(InputStream input, Charset encoding) throws IOException { InputStreamReader reader = new InputStreamReader(input, Charsets.toCharset(encoding)); return readLines(reader); } /** * Get the contents of an InputStream as a list of Strings, * one entry per line, using the specified character encoding. *

* Character encoding names can be found at * IANA. *

* This method buffers the input internally, so there is no need to use a * BufferedInputStream. * * @param input the InputStream to read from, not null * @param encoding the encoding to use, null means platform default * @return the list of Strings, never null * @throws NullPointerException if the input is null * @throws IOException if an I/O error occurs * @throws UnsupportedCharsetException * thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not * supported. * @since 1.1 */ public static List readLines(InputStream input, String encoding) throws IOException { return readLines(input, Charsets.toCharset(encoding)); } /** * Get the contents of a Reader as a list of Strings, * one entry per line. *

* This method buffers the input internally, so there is no need to use a * BufferedReader. * * @param input the Reader to read from, not null * @return the list of Strings, never null * @throws NullPointerException if the input is null * @throws IOException if an I/O error occurs * @since 1.1 */ public static List readLines(Reader input) throws IOException { BufferedReader reader = toBufferedReader(input); List list = new ArrayList(); String line = reader.readLine(); while (line != null) { list.add(line); line = reader.readLine(); } return list; } // lineIterator //----------------------------------------------------------------------- /** * Return an Iterator for the lines in a Reader. *

* LineIterator holds a reference to the open * Reader specified here. When you have finished with the * iterator you should close the reader to free internal resources. * This can be done by closing the reader directly, or by calling * {@link LineIterator#close()} or {@link LineIterator#closeQuietly(LineIterator)}. *

* The recommended usage pattern is: *

     * try {
     *   LineIterator it = IOUtils.lineIterator(reader);
     *   while (it.hasNext()) {
     *     String line = it.nextLine();
     *     /// do something with line
     *   }
     * } finally {
     *   IOUtils.closeQuietly(reader);
     * }
     * 
* * @param reader the Reader to read from, not null * @return an Iterator of the lines in the reader, never null * @throws IllegalArgumentException if the reader is null * @since 1.2 */ public static LineIterator lineIterator(Reader reader) { return new LineIterator(reader); } /** * Return an Iterator for the lines in an InputStream, using * the character encoding specified (or default encoding if null). *

* LineIterator holds a reference to the open * InputStream specified here. When you have finished with * the iterator you should close the stream to free internal resources. * This can be done by closing the stream directly, or by calling * {@link LineIterator#close()} or {@link LineIterator#closeQuietly(LineIterator)}. *

* The recommended usage pattern is: *

     * try {
     *   LineIterator it = IOUtils.lineIterator(stream, charset);
     *   while (it.hasNext()) {
     *     String line = it.nextLine();
     *     /// do something with line
     *   }
     * } finally {
     *   IOUtils.closeQuietly(stream);
     * }
     * 
* * @param input the InputStream to read from, not null * @param encoding the encoding to use, null means platform default * @return an Iterator of the lines in the reader, never null * @throws IllegalArgumentException if the input is null * @throws IOException if an I/O error occurs, such as if the encoding is invalid * @since 2.3 */ public static LineIterator lineIterator(InputStream input, Charset encoding) throws IOException { return new LineIterator(new InputStreamReader(input, Charsets.toCharset(encoding))); } /** * Return an Iterator for the lines in an InputStream, using * the character encoding specified (or default encoding if null). *

* LineIterator holds a reference to the open * InputStream specified here. When you have finished with * the iterator you should close the stream to free internal resources. * This can be done by closing the stream directly, or by calling * {@link LineIterator#close()} or {@link LineIterator#closeQuietly(LineIterator)}. *

* The recommended usage pattern is: *

     * try {
     *   LineIterator it = IOUtils.lineIterator(stream, "UTF-8");
     *   while (it.hasNext()) {
     *     String line = it.nextLine();
     *     /// do something with line
     *   }
     * } finally {
     *   IOUtils.closeQuietly(stream);
     * }
     * 
* * @param input the InputStream to read from, not null * @param encoding the encoding to use, null means platform default * @return an Iterator of the lines in the reader, never null * @throws IllegalArgumentException if the input is null * @throws IOException if an I/O error occurs, such as if the encoding is invalid * @throws UnsupportedCharsetException * thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not * supported. * @since 1.2 */ public static LineIterator lineIterator(InputStream input, String encoding) throws IOException { return lineIterator(input, Charsets.toCharset(encoding)); } //----------------------------------------------------------------------- /** * Convert the specified CharSequence to an input stream, encoded as bytes * using the default character encoding of the platform. * * @param input the CharSequence to convert * @return an input stream * @since 2.0 */ public static InputStream toInputStream(CharSequence input) { return toInputStream(input, Charset.defaultCharset()); } /** * Convert the specified CharSequence to an input stream, encoded as bytes * using the specified character encoding. * * @param input the CharSequence to convert * @param encoding the encoding to use, null means platform default * @return an input stream * @since 2.3 */ public static InputStream toInputStream(CharSequence input, Charset encoding) { return toInputStream(input.toString(), encoding); } /** * Convert the specified CharSequence to an input stream, encoded as bytes * using the specified character encoding. *

* Character encoding names can be found at * IANA. * * @param input the CharSequence to convert * @param encoding the encoding to use, null means platform default * @return an input stream * @throws IOException if the encoding is invalid * @throws UnsupportedCharsetException * thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not * supported. * @since 2.0 */ public static InputStream toInputStream(CharSequence input, String encoding) throws IOException { return toInputStream(input, Charsets.toCharset(encoding)); } //----------------------------------------------------------------------- /** * Convert the specified string to an input stream, encoded as bytes * using the default character encoding of the platform. * * @param input the string to convert * @return an input stream * @since 1.1 */ public static InputStream toInputStream(String input) { return toInputStream(input, Charset.defaultCharset()); } /** * Convert the specified string to an input stream, encoded as bytes * using the specified character encoding. * * @param input the string to convert * @param encoding the encoding to use, null means platform default * @return an input stream * @since 2.3 */ public static InputStream toInputStream(String input, Charset encoding) { return new ByteArrayInputStream(input.getBytes(Charsets.toCharset(encoding))); } /** * Convert the specified string to an input stream, encoded as bytes * using the specified character encoding. *

* Character encoding names can be found at * IANA. * * @param input the string to convert * @param encoding the encoding to use, null means platform default * @return an input stream * @throws IOException if the encoding is invalid * @throws UnsupportedCharsetException * thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not * supported. * @since 1.1 */ public static InputStream toInputStream(String input, String encoding) throws IOException { byte[] bytes = input.getBytes(Charsets.toCharset(encoding)); return new ByteArrayInputStream(bytes); } // write byte[] //----------------------------------------------------------------------- /** * Writes bytes from a byte[] to an OutputStream. * * @param data the byte array to write, do not modify during output, * null ignored * @param output the OutputStream to write to * @throws NullPointerException if output is null * @throws IOException if an I/O error occurs * @since 1.1 */ public static void write(byte[] data, OutputStream output) throws IOException { if (data != null) { output.write(data); } } /** * Writes bytes from a byte[] to chars on a Writer * using the default character encoding of the platform. *

* This method uses {@link String#String(byte[])}. * * @param data the byte array to write, do not modify during output, * null ignored * @param output the Writer to write to * @throws NullPointerException if output is null * @throws IOException if an I/O error occurs * @since 1.1 */ public static void write(byte[] data, Writer output) throws IOException { write(data, output, Charset.defaultCharset()); } /** * Writes bytes from a byte[] to chars on a Writer * using the specified character encoding. *

* This method uses {@link String#String(byte[], String)}. * * @param data the byte array to write, do not modify during output, * null ignored * @param output the Writer to write to * @param encoding the encoding to use, null means platform default * @throws NullPointerException if output is null * @throws IOException if an I/O error occurs * @since 2.3 */ public static void write(byte[] data, Writer output, Charset encoding) throws IOException { if (data != null) { output.write(new String(data, Charsets.toCharset(encoding))); } } /** * Writes bytes from a byte[] to chars on a Writer * using the specified character encoding. *

* Character encoding names can be found at * IANA. *

* This method uses {@link String#String(byte[], String)}. * * @param data the byte array to write, do not modify during output, * null ignored * @param output the Writer to write to * @param encoding the encoding to use, null means platform default * @throws NullPointerException if output is null * @throws IOException if an I/O error occurs * @throws UnsupportedCharsetException * thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not * supported. * @since 1.1 */ public static void write(byte[] data, Writer output, String encoding) throws IOException { write(data, output, Charsets.toCharset(encoding)); } // write char[] //----------------------------------------------------------------------- /** * Writes chars from a char[] to a Writer * using the default character encoding of the platform. * * @param data the char array to write, do not modify during output, * null ignored * @param output the Writer to write to * @throws NullPointerException if output is null * @throws IOException if an I/O error occurs * @since 1.1 */ public static void write(char[] data, Writer output) throws IOException { if (data != null) { output.write(data); } } /** * Writes chars from a char[] to bytes on an * OutputStream. *

* This method uses {@link String#String(char[])} and * {@link String#getBytes()}. * * @param data the char array to write, do not modify during output, * null ignored * @param output the OutputStream to write to * @throws NullPointerException if output is null * @throws IOException if an I/O error occurs * @since 1.1 */ public static void write(char[] data, OutputStream output) throws IOException { write(data, output, Charset.defaultCharset()); } /** * Writes chars from a char[] to bytes on an * OutputStream using the specified character encoding. *

* This method uses {@link String#String(char[])} and * {@link String#getBytes(String)}. * * @param data the char array to write, do not modify during output, * null ignored * @param output the OutputStream to write to * @param encoding the encoding to use, null means platform default * @throws NullPointerException if output is null * @throws IOException if an I/O error occurs * @since 2.3 */ public static void write(char[] data, OutputStream output, Charset encoding) throws IOException { if (data != null) { output.write(new String(data).getBytes(Charsets.toCharset(encoding))); } } /** * Writes chars from a char[] to bytes on an * OutputStream using the specified character encoding. *

* Character encoding names can be found at * IANA. *

* This method uses {@link String#String(char[])} and * {@link String#getBytes(String)}. * * @param data the char array to write, do not modify during output, * null ignored * @param output the OutputStream to write to * @param encoding the encoding to use, null means platform default * @throws NullPointerException if output is null * @throws IOException if an I/O error occurs * @throws UnsupportedCharsetException * thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not * supported. * @since 1.1 */ public static void write(char[] data, OutputStream output, String encoding) throws IOException { write(data, output, Charsets.toCharset(encoding)); } // write CharSequence //----------------------------------------------------------------------- /** * Writes chars from a CharSequence to a Writer. * * @param data the CharSequence to write, null ignored * @param output the Writer to write to * @throws NullPointerException if output is null * @throws IOException if an I/O error occurs * @since 2.0 */ public static void write(CharSequence data, Writer output) throws IOException { if (data != null) { write(data.toString(), output); } } /** * Writes chars from a CharSequence to bytes on an * OutputStream using the default character encoding of the * platform. *

* This method uses {@link String#getBytes()}. * * @param data the CharSequence to write, null ignored * @param output the OutputStream to write to * @throws NullPointerException if output is null * @throws IOException if an I/O error occurs * @since 2.0 */ public static void write(CharSequence data, OutputStream output) throws IOException { write(data, output, Charset.defaultCharset()); } /** * Writes chars from a CharSequence to bytes on an * OutputStream using the specified character encoding. *

* This method uses {@link String#getBytes(String)}. * * @param data the CharSequence to write, null ignored * @param output the OutputStream to write to * @param encoding the encoding to use, null means platform default * @throws NullPointerException if output is null * @throws IOException if an I/O error occurs * @since 2.3 */ public static void write(CharSequence data, OutputStream output, Charset encoding) throws IOException { if (data != null) { write(data.toString(), output, encoding); } } /** * Writes chars from a CharSequence to bytes on an * OutputStream using the specified character encoding. *

* Character encoding names can be found at * IANA. *

* This method uses {@link String#getBytes(String)}. * * @param data the CharSequence to write, null ignored * @param output the OutputStream to write to * @param encoding the encoding to use, null means platform default * @throws NullPointerException if output is null * @throws IOException if an I/O error occurs * @throws UnsupportedCharsetException * thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not * supported. * @since 2.0 */ public static void write(CharSequence data, OutputStream output, String encoding) throws IOException { write(data, output, Charsets.toCharset(encoding)); } // write String //----------------------------------------------------------------------- /** * Writes chars from a String to a Writer. * * @param data the String to write, null ignored * @param output the Writer to write to * @throws NullPointerException if output is null * @throws IOException if an I/O error occurs * @since 1.1 */ public static void write(String data, Writer output) throws IOException { if (data != null) { output.write(data); } } /** * Writes chars from a String to bytes on an * OutputStream using the default character encoding of the * platform. *

* This method uses {@link String#getBytes()}. * * @param data the String to write, null ignored * @param output the OutputStream to write to * @throws NullPointerException if output is null * @throws IOException if an I/O error occurs * @since 1.1 */ public static void write(String data, OutputStream output) throws IOException { write(data, output, Charset.defaultCharset()); } /** * Writes chars from a String to bytes on an * OutputStream using the specified character encoding. *

* This method uses {@link String#getBytes(String)}. * * @param data the String to write, null ignored * @param output the OutputStream to write to * @param encoding the encoding to use, null means platform default * @throws NullPointerException if output is null * @throws IOException if an I/O error occurs * @since 2.3 */ public static void write(String data, OutputStream output, Charset encoding) throws IOException { if (data != null) { output.write(data.getBytes(Charsets.toCharset(encoding))); } } /** * Writes chars from a String to bytes on an * OutputStream using the specified character encoding. *

* Character encoding names can be found at * IANA. *

* This method uses {@link String#getBytes(String)}. * * @param data the String to write, null ignored * @param output the OutputStream to write to * @param encoding the encoding to use, null means platform default * @throws NullPointerException if output is null * @throws IOException if an I/O error occurs * @throws UnsupportedCharsetException * thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not * supported. * @since 1.1 */ public static void write(String data, OutputStream output, String encoding) throws IOException { write(data, output, Charsets.toCharset(encoding)); } // write StringBuffer //----------------------------------------------------------------------- /** * Writes chars from a StringBuffer to a Writer. * * @param data the StringBuffer to write, null ignored * @param output the Writer to write to * @throws NullPointerException if output is null * @throws IOException if an I/O error occurs * @since 1.1 * @deprecated replaced by write(CharSequence, Writer) */ @Deprecated public static void write(StringBuffer data, Writer output) throws IOException { if (data != null) { output.write(data.toString()); } } /** * Writes chars from a StringBuffer to bytes on an * OutputStream using the default character encoding of the * platform. *

* This method uses {@link String#getBytes()}. * * @param data the StringBuffer to write, null ignored * @param output the OutputStream to write to * @throws NullPointerException if output is null * @throws IOException if an I/O error occurs * @since 1.1 * @deprecated replaced by write(CharSequence, OutputStream) */ @Deprecated public static void write(StringBuffer data, OutputStream output) throws IOException { write(data, output, (String) null); } /** * Writes chars from a StringBuffer to bytes on an * OutputStream using the specified character encoding. *

* Character encoding names can be found at * IANA. *

* This method uses {@link String#getBytes(String)}. * * @param data the StringBuffer to write, null ignored * @param output the OutputStream to write to * @param encoding the encoding to use, null means platform default * @throws NullPointerException if output is null * @throws IOException if an I/O error occurs * @throws UnsupportedCharsetException * thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not * supported. * @since 1.1 * @deprecated replaced by write(CharSequence, OutputStream, String) */ @Deprecated public static void write(StringBuffer data, OutputStream output, String encoding) throws IOException { if (data != null) { output.write(data.toString().getBytes(Charsets.toCharset(encoding))); } } // writeLines //----------------------------------------------------------------------- /** * Writes the toString() value of each item in a collection to * an OutputStream line by line, using the default character * encoding of the platform and the specified line ending. * * @param lines the lines to write, null entries produce blank lines * @param lineEnding the line separator to use, null is system default * @param output the OutputStream to write to, not null, not closed * @throws NullPointerException if the output is null * @throws IOException if an I/O error occurs * @since 1.1 */ public static void writeLines(Collection lines, String lineEnding, OutputStream output) throws IOException { writeLines(lines, lineEnding, output, Charset.defaultCharset()); } /** * Writes the toString() value of each item in a collection to * an OutputStream line by line, using the specified character * encoding and the specified line ending. * * @param lines the lines to write, null entries produce blank lines * @param lineEnding the line separator to use, null is system default * @param output the OutputStream to write to, not null, not closed * @param encoding the encoding to use, null means platform default * @throws NullPointerException if the output is null * @throws IOException if an I/O error occurs * @since 2.3 */ public static void writeLines(Collection lines, String lineEnding, OutputStream output, Charset encoding) throws IOException { if (lines == null) { return; } if (lineEnding == null) { lineEnding = LINE_SEPARATOR; } Charset cs = Charsets.toCharset(encoding); for (Object line : lines) { if (line != null) { output.write(line.toString().getBytes(cs)); } output.write(lineEnding.getBytes(cs)); } } /** * Writes the toString() value of each item in a collection to * an OutputStream line by line, using the specified character * encoding and the specified line ending. *

* Character encoding names can be found at * IANA. * * @param lines the lines to write, null entries produce blank lines * @param lineEnding the line separator to use, null is system default * @param output the OutputStream to write to, not null, not closed * @param encoding the encoding to use, null means platform default * @throws NullPointerException if the output is null * @throws IOException if an I/O error occurs * @throws UnsupportedCharsetException * thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not * supported. * @since 1.1 */ public static void writeLines(Collection lines, String lineEnding, OutputStream output, String encoding) throws IOException { writeLines(lines, lineEnding, output, Charsets.toCharset(encoding)); } /** * Writes the toString() value of each item in a collection to * a Writer line by line, using the specified line ending. * * @param lines the lines to write, null entries produce blank lines * @param lineEnding the line separator to use, null is system default * @param writer the Writer to write to, not null, not closed * @throws NullPointerException if the input is null * @throws IOException if an I/O error occurs * @since 1.1 */ public static void writeLines(Collection lines, String lineEnding, Writer writer) throws IOException { if (lines == null) { return; } if (lineEnding == null) { lineEnding = LINE_SEPARATOR; } for (Object line : lines) { if (line != null) { writer.write(line.toString()); } writer.write(lineEnding); } } // copy from InputStream //----------------------------------------------------------------------- /** * Copy bytes from an InputStream to an * OutputStream. *

* This method buffers the input internally, so there is no need to use a * BufferedInputStream. *

* Large streams (over 2GB) will return a bytes copied value of * -1 after the copy has completed since the correct * number of bytes cannot be returned as an int. For large streams * use the copyLarge(InputStream, OutputStream) method. * * @param input the InputStream to read from * @param output the OutputStream to write to * @return the number of bytes copied, or -1 if > Integer.MAX_VALUE * @throws NullPointerException if the input or output is null * @throws IOException if an I/O error occurs * @since 1.1 */ public static int copy(InputStream input, OutputStream output) throws IOException { long count = copyLarge(input, output); if (count > Integer.MAX_VALUE) { return -1; } return (int) count; } /** * Copy bytes from a large (over 2GB) InputStream to an * OutputStream. *

* This method buffers the input internally, so there is no need to use a * BufferedInputStream. *

* The buffer size is given by {@link #DEFAULT_BUFFER_SIZE}. * * @param input the InputStream to read from * @param output the OutputStream to write to * @return the number of bytes copied * @throws NullPointerException if the input or output is null * @throws IOException if an I/O error occurs * @since 1.3 */ public static long copyLarge(InputStream input, OutputStream output) throws IOException { return copyLarge(input, output, new byte[DEFAULT_BUFFER_SIZE]); } /** * Copy bytes from a large (over 2GB) InputStream to an * OutputStream. *

* This method uses the provided buffer, so there is no need to use a * BufferedInputStream. *

* * @param input the InputStream to read from * @param output the OutputStream to write to * @param buffer the buffer to use for the copy * @return the number of bytes copied * @throws NullPointerException if the input or output is null * @throws IOException if an I/O error occurs * @since 2.2 */ public static long copyLarge(InputStream input, OutputStream output, byte[] buffer) throws IOException { long count = 0; int n = 0; while (EOF != (n = input.read(buffer))) { output.write(buffer, 0, n); count += n; } return count; } /** * Copy some or all bytes from a large (over 2GB) InputStream to an * OutputStream, optionally skipping input bytes. *

* This method buffers the input internally, so there is no need to use a * BufferedInputStream. *

* The buffer size is given by {@link #DEFAULT_BUFFER_SIZE}. * * @param input the InputStream to read from * @param output the OutputStream to write to * @param inputOffset : number of bytes to skip from input before copying * -ve values are ignored * @param length : number of bytes to copy. -ve means all * @return the number of bytes copied * @throws NullPointerException if the input or output is null * @throws IOException if an I/O error occurs * @since 2.2 */ public static long copyLarge(InputStream input, OutputStream output, long inputOffset, long length) throws IOException { return copyLarge(input, output, inputOffset, length, new byte[DEFAULT_BUFFER_SIZE]); } /** * Copy some or all bytes from a large (over 2GB) InputStream to an * OutputStream, optionally skipping input bytes. *

* This method uses the provided buffer, so there is no need to use a * BufferedInputStream. *

* * @param input the InputStream to read from * @param output the OutputStream to write to * @param inputOffset : number of bytes to skip from input before copying * -ve values are ignored * @param length : number of bytes to copy. -ve means all * @param buffer the buffer to use for the copy * * @return the number of bytes copied * @throws NullPointerException if the input or output is null * @throws IOException if an I/O error occurs * @since 2.2 */ public static long copyLarge(InputStream input, OutputStream output, final long inputOffset, final long length, byte[] buffer) throws IOException { if (inputOffset > 0) { skipFully(input, inputOffset); } if (length == 0) { return 0; } final int bufferLength = buffer.length; int bytesToRead = bufferLength; if (length > 0 && length < bufferLength) { bytesToRead = (int) length; } int read; long totalRead = 0; while (bytesToRead > 0 && EOF != (read = input.read(buffer, 0, bytesToRead))) { output.write(buffer, 0, read); totalRead += read; if (length > 0) { // only adjust length if not reading to the end // Note the cast must work because buffer.length is an integer bytesToRead = (int) Math.min(length - totalRead, bufferLength); } } return totalRead; } /** * Copy bytes from an InputStream to chars on a * Writer using the default character encoding of the platform. *

* This method buffers the input internally, so there is no need to use a * BufferedInputStream. *

* This method uses {@link InputStreamReader}. * * @param input the InputStream to read from * @param output the Writer to write to * @throws NullPointerException if the input or output is null * @throws IOException if an I/O error occurs * @since 1.1 */ public static void copy(InputStream input, Writer output) throws IOException { copy(input, output, Charset.defaultCharset()); } /** * Copy bytes from an InputStream to chars on a * Writer using the specified character encoding. *

* This method buffers the input internally, so there is no need to use a * BufferedInputStream. *

* This method uses {@link InputStreamReader}. * * @param input the InputStream to read from * @param output the Writer to write to * @param encoding the encoding to use, null means platform default * @throws NullPointerException if the input or output is null * @throws IOException if an I/O error occurs * @since 2.3 */ public static void copy(InputStream input, Writer output, Charset encoding) throws IOException { InputStreamReader in = new InputStreamReader(input, Charsets.toCharset(encoding)); copy(in, output); } /** * Copy bytes from an InputStream to chars on a * Writer using the specified character encoding. *

* This method buffers the input internally, so there is no need to use a * BufferedInputStream. *

* Character encoding names can be found at * IANA. *

* This method uses {@link InputStreamReader}. * * @param input the InputStream to read from * @param output the Writer to write to * @param encoding the encoding to use, null means platform default * @throws NullPointerException if the input or output is null * @throws IOException if an I/O error occurs * @throws UnsupportedCharsetException * thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not * supported. * @since 1.1 */ public static void copy(InputStream input, Writer output, String encoding) throws IOException { copy(input, output, Charsets.toCharset(encoding)); } // copy from Reader //----------------------------------------------------------------------- /** * Copy chars from a Reader to a Writer. *

* This method buffers the input internally, so there is no need to use a * BufferedReader. *

* Large streams (over 2GB) will return a chars copied value of * -1 after the copy has completed since the correct * number of chars cannot be returned as an int. For large streams * use the copyLarge(Reader, Writer) method. * * @param input the Reader to read from * @param output the Writer to write to * @return the number of characters copied, or -1 if > Integer.MAX_VALUE * @throws NullPointerException if the input or output is null * @throws IOException if an I/O error occurs * @since 1.1 */ public static int copy(Reader input, Writer output) throws IOException { long count = copyLarge(input, output); if (count > Integer.MAX_VALUE) { return -1; } return (int) count; } /** * Copy chars from a large (over 2GB) Reader to a Writer. *

* This method buffers the input internally, so there is no need to use a * BufferedReader. *

* The buffer size is given by {@link #DEFAULT_BUFFER_SIZE}. * * @param input the Reader to read from * @param output the Writer to write to * @return the number of characters copied * @throws NullPointerException if the input or output is null * @throws IOException if an I/O error occurs * @since 1.3 */ public static long copyLarge(Reader input, Writer output) throws IOException { return copyLarge(input, output, new char[DEFAULT_BUFFER_SIZE]); } /** * Copy chars from a large (over 2GB) Reader to a Writer. *

* This method uses the provided buffer, so there is no need to use a * BufferedReader. *

* * @param input the Reader to read from * @param output the Writer to write to * @param buffer the buffer to be used for the copy * @return the number of characters copied * @throws NullPointerException if the input or output is null * @throws IOException if an I/O error occurs * @since 2.2 */ public static long copyLarge(Reader input, Writer output, char [] buffer) throws IOException { long count = 0; int n = 0; while (EOF != (n = input.read(buffer))) { output.write(buffer, 0, n); count += n; } return count; } /** * Copy some or all chars from a large (over 2GB) InputStream to an * OutputStream, optionally skipping input chars. *

* This method buffers the input internally, so there is no need to use a * BufferedReader. *

* The buffer size is given by {@link #DEFAULT_BUFFER_SIZE}. * * @param input the Reader to read from * @param output the Writer to write to * @param inputOffset : number of chars to skip from input before copying * -ve values are ignored * @param length : number of chars to copy. -ve means all * @return the number of chars copied * @throws NullPointerException if the input or output is null * @throws IOException if an I/O error occurs * @since 2.2 */ public static long copyLarge(Reader input, Writer output, final long inputOffset, final long length) throws IOException { return copyLarge(input, output, inputOffset, length, new char[DEFAULT_BUFFER_SIZE]); } /** * Copy some or all chars from a large (over 2GB) InputStream to an * OutputStream, optionally skipping input chars. *

* This method uses the provided buffer, so there is no need to use a * BufferedReader. *

* * @param input the Reader to read from * @param output the Writer to write to * @param inputOffset : number of chars to skip from input before copying * -ve values are ignored * @param length : number of chars to copy. -ve means all * @param buffer the buffer to be used for the copy * @return the number of chars copied * @throws NullPointerException if the input or output is null * @throws IOException if an I/O error occurs * @since 2.2 */ public static long copyLarge(Reader input, Writer output, final long inputOffset, final long length, char [] buffer) throws IOException { if (inputOffset > 0) { skipFully(input, inputOffset); } if (length == 0) { return 0; } int bytesToRead = buffer.length; if (length > 0 && length < buffer.length) { bytesToRead = (int) length; } int read; long totalRead = 0; while (bytesToRead > 0 && EOF != (read = input.read(buffer, 0, bytesToRead))) { output.write(buffer, 0, read); totalRead += read; if (length > 0) { // only adjust length if not reading to the end // Note the cast must work because buffer.length is an integer bytesToRead = (int) Math.min(length - totalRead, buffer.length); } } return totalRead; } /** * Copy chars from a Reader to bytes on an * OutputStream using the default character encoding of the * platform, and calling flush. *

* This method buffers the input internally, so there is no need to use a * BufferedReader. *

* Due to the implementation of OutputStreamWriter, this method performs a * flush. *

* This method uses {@link OutputStreamWriter}. * * @param input the Reader to read from * @param output the OutputStream to write to * @throws NullPointerException if the input or output is null * @throws IOException if an I/O error occurs * @since 1.1 */ public static void copy(Reader input, OutputStream output) throws IOException { copy(input, output, Charset.defaultCharset()); } /** * Copy chars from a Reader to bytes on an * OutputStream using the specified character encoding, and * calling flush. *

* This method buffers the input internally, so there is no need to use a * BufferedReader. *

*

* Due to the implementation of OutputStreamWriter, this method performs a * flush. *

*

* This method uses {@link OutputStreamWriter}. *

* * @param input the Reader to read from * @param output the OutputStream to write to * @param encoding the encoding to use, null means platform default * @throws NullPointerException if the input or output is null * @throws IOException if an I/O error occurs * @since 2.3 */ public static void copy(Reader input, OutputStream output, Charset encoding) throws IOException { OutputStreamWriter out = new OutputStreamWriter(output, Charsets.toCharset(encoding)); copy(input, out); // XXX Unless anyone is planning on rewriting OutputStreamWriter, // we have to flush here. out.flush(); } /** * Copy chars from a Reader to bytes on an * OutputStream using the specified character encoding, and * calling flush. *

* This method buffers the input internally, so there is no need to use a * BufferedReader. *

* Character encoding names can be found at * IANA. *

* Due to the implementation of OutputStreamWriter, this method performs a * flush. *

* This method uses {@link OutputStreamWriter}. * * @param input the Reader to read from * @param output the OutputStream to write to * @param encoding the encoding to use, null means platform default * @throws NullPointerException if the input or output is null * @throws IOException if an I/O error occurs * @throws UnsupportedCharsetException * thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not * supported. * @since 1.1 */ public static void copy(Reader input, OutputStream output, String encoding) throws IOException { copy(input, output, Charsets.toCharset(encoding)); } // content equals //----------------------------------------------------------------------- /** * Compare the contents of two Streams to determine if they are equal or * not. *

* This method buffers the input internally using * BufferedInputStream if they are not already buffered. * * @param input1 the first stream * @param input2 the second stream * @return true if the content of the streams are equal or they both don't * exist, false otherwise * @throws NullPointerException if either input is null * @throws IOException if an I/O error occurs */ public static boolean contentEquals(InputStream input1, InputStream input2) throws IOException { if (!(input1 instanceof BufferedInputStream)) { input1 = new BufferedInputStream(input1); } if (!(input2 instanceof BufferedInputStream)) { input2 = new BufferedInputStream(input2); } int ch = input1.read(); while (EOF != ch) { int ch2 = input2.read(); if (ch != ch2) { return false; } ch = input1.read(); } int ch2 = input2.read(); return ch2 == EOF; } /** * Compare the contents of two Readers to determine if they are equal or * not. *

* This method buffers the input internally using * BufferedReader if they are not already buffered. * * @param input1 the first reader * @param input2 the second reader * @return true if the content of the readers are equal or they both don't * exist, false otherwise * @throws NullPointerException if either input is null * @throws IOException if an I/O error occurs * @since 1.1 */ public static boolean contentEquals(Reader input1, Reader input2) throws IOException { input1 = toBufferedReader(input1); input2 = toBufferedReader(input2); int ch = input1.read(); while (EOF != ch) { int ch2 = input2.read(); if (ch != ch2) { return false; } ch = input1.read(); } int ch2 = input2.read(); return ch2 == EOF; } /** * Compare the contents of two Readers to determine if they are equal or * not, ignoring EOL characters. *

* This method buffers the input internally using * BufferedReader if they are not already buffered. * * @param input1 the first reader * @param input2 the second reader * @return true if the content of the readers are equal (ignoring EOL differences), false otherwise * @throws NullPointerException if either input is null * @throws IOException if an I/O error occurs * @since 2.2 */ public static boolean contentEqualsIgnoreEOL(Reader input1, Reader input2) throws IOException { BufferedReader br1 = toBufferedReader(input1); BufferedReader br2 = toBufferedReader(input2); String line1 = br1.readLine(); String line2 = br2.readLine(); while (line1 != null && line2 != null && line1.equals(line2)) { line1 = br1.readLine(); line2 = br2.readLine(); } return line1 == null ? line2 == null ? true : false : line1.equals(line2); } /** * Skip bytes from an input byte stream. * This implementation guarantees that it will read as many bytes * as possible before giving up; this may not always be the case for * subclasses of {@link Reader}. * * @param input byte stream to skip * @param toSkip number of bytes to skip. * @return number of bytes actually skipped. * * @see InputStream#skip(long) * * @throws IOException if there is a problem reading the file * @throws IllegalArgumentException if toSkip is negative * @since 2.0 */ public static long skip(InputStream input, long toSkip) throws IOException { if (toSkip < 0) { throw new IllegalArgumentException("Skip count must be non-negative, actual: " + toSkip); } /* * N.B. no need to synchronize this because: - we don't care if the buffer is created multiple times (the data * is ignored) - we always use the same size buffer, so if it it is recreated it will still be OK (if the buffer * size were variable, we would need to synch. to ensure some other thread did not create a smaller one) */ if (SKIP_BYTE_BUFFER == null) { SKIP_BYTE_BUFFER = new byte[SKIP_BUFFER_SIZE]; } long remain = toSkip; while (remain > 0) { long n = input.read(SKIP_BYTE_BUFFER, 0, (int) Math.min(remain, SKIP_BUFFER_SIZE)); if (n < 0) { // EOF break; } remain -= n; } return toSkip - remain; } /** * Skip characters from an input character stream. * This implementation guarantees that it will read as many characters * as possible before giving up; this may not always be the case for * subclasses of {@link Reader}. * * @param input character stream to skip * @param toSkip number of characters to skip. * @return number of characters actually skipped. * * @see Reader#skip(long) * * @throws IOException if there is a problem reading the file * @throws IllegalArgumentException if toSkip is negative * @since 2.0 */ public static long skip(Reader input, long toSkip) throws IOException { if (toSkip < 0) { throw new IllegalArgumentException("Skip count must be non-negative, actual: " + toSkip); } /* * N.B. no need to synchronize this because: - we don't care if the buffer is created multiple times (the data * is ignored) - we always use the same size buffer, so if it it is recreated it will still be OK (if the buffer * size were variable, we would need to synch. to ensure some other thread did not create a smaller one) */ if (SKIP_CHAR_BUFFER == null) { SKIP_CHAR_BUFFER = new char[SKIP_BUFFER_SIZE]; } long remain = toSkip; while (remain > 0) { long n = input.read(SKIP_CHAR_BUFFER, 0, (int) Math.min(remain, SKIP_BUFFER_SIZE)); if (n < 0) { // EOF break; } remain -= n; } return toSkip - remain; } /** * Skip the requested number of bytes or fail if there are not enough left. *

* This allows for the possibility that {@link InputStream#skip(long)} may * not skip as many bytes as requested (most likely because of reaching EOF). * * @param input stream to skip * @param toSkip the number of bytes to skip * @see InputStream#skip(long) * * @throws IOException if there is a problem reading the file * @throws IllegalArgumentException if toSkip is negative * @throws EOFException if the number of bytes skipped was incorrect * @since 2.0 */ public static void skipFully(InputStream input, long toSkip) throws IOException { if (toSkip < 0) { throw new IllegalArgumentException("Bytes to skip must not be negative: " + toSkip); } long skipped = skip(input, toSkip); if (skipped != toSkip) { throw new EOFException("Bytes to skip: " + toSkip + " actual: " + skipped); } } /** * Skip the requested number of characters or fail if there are not enough left. *

* This allows for the possibility that {@link Reader#skip(long)} may * not skip as many characters as requested (most likely because of reaching EOF). * * @param input stream to skip * @param toSkip the number of characters to skip * @see Reader#skip(long) * * @throws IOException if there is a problem reading the file * @throws IllegalArgumentException if toSkip is negative * @throws EOFException if the number of characters skipped was incorrect * @since 2.0 */ public static void skipFully(Reader input, long toSkip) throws IOException { long skipped = skip(input, toSkip); if (skipped != toSkip) { throw new EOFException("Chars to skip: " + toSkip + " actual: " + skipped); } } /** * Read characters from an input character stream. * This implementation guarantees that it will read as many characters * as possible before giving up; this may not always be the case for * subclasses of {@link Reader}. * * @param input where to read input from * @param buffer destination * @param offset inital offset into buffer * @param length length to read, must be >= 0 * @return actual length read; may be less than requested if EOF was reached * @throws IOException if a read error occurs * @since 2.2 */ public static int read(Reader input, char[] buffer, int offset, int length) throws IOException { if (length < 0) { throw new IllegalArgumentException("Length must not be negative: " + length); } int remaining = length; while (remaining > 0) { int location = length - remaining; int count = input.read(buffer, offset + location, remaining); if (EOF == count) { // EOF break; } remaining -= count; } return length - remaining; } /** * Read characters from an input character stream. * This implementation guarantees that it will read as many characters * as possible before giving up; this may not always be the case for * subclasses of {@link Reader}. * * @param input where to read input from * @param buffer destination * @return actual length read; may be less than requested if EOF was reached * @throws IOException if a read error occurs * @since 2.2 */ public static int read(Reader input, char[] buffer) throws IOException { return read(input, buffer, 0, buffer.length); } /** * Read bytes from an input stream. * This implementation guarantees that it will read as many bytes * as possible before giving up; this may not always be the case for * subclasses of {@link InputStream}. * * @param input where to read input from * @param buffer destination * @param offset inital offset into buffer * @param length length to read, must be >= 0 * @return actual length read; may be less than requested if EOF was reached * @throws IOException if a read error occurs * @since 2.2 */ public static int read(InputStream input, byte[] buffer, int offset, int length) throws IOException { if (length < 0) { throw new IllegalArgumentException("Length must not be negative: " + length); } int remaining = length; while (remaining > 0) { int location = length - remaining; int count = input.read(buffer, offset + location, remaining); if (EOF == count) { // EOF break; } remaining -= count; } return length - remaining; } /** * Read bytes from an input stream. * This implementation guarantees that it will read as many bytes * as possible before giving up; this may not always be the case for * subclasses of {@link InputStream}. * * @param input where to read input from * @param buffer destination * @return actual length read; may be less than requested if EOF was reached * @throws IOException if a read error occurs * @since 2.2 */ public static int read(InputStream input, byte[] buffer) throws IOException { return read(input, buffer, 0, buffer.length); } /** * Read the requested number of characters or fail if there are not enough left. *

* This allows for the possibility that {@link Reader#read(char[], int, int)} may * not read as many characters as requested (most likely because of reaching EOF). * * @param input where to read input from * @param buffer destination * @param offset inital offset into buffer * @param length length to read, must be >= 0 * * @throws IOException if there is a problem reading the file * @throws IllegalArgumentException if length is negative * @throws EOFException if the number of characters read was incorrect * @since 2.2 */ public static void readFully(Reader input, char[] buffer, int offset, int length) throws IOException { int actual = read(input, buffer, offset, length); if (actual != length) { throw new EOFException("Length to read: " + length + " actual: " + actual); } } /** * Read the requested number of characters or fail if there are not enough left. *

* This allows for the possibility that {@link Reader#read(char[], int, int)} may * not read as many characters as requested (most likely because of reaching EOF). * * @param input where to read input from * @param buffer destination * * @throws IOException if there is a problem reading the file * @throws IllegalArgumentException if length is negative * @throws EOFException if the number of characters read was incorrect * @since 2.2 */ public static void readFully(Reader input, char[] buffer) throws IOException { readFully(input, buffer, 0, buffer.length); } /** * Read the requested number of bytes or fail if there are not enough left. *

* This allows for the possibility that {@link InputStream#read(byte[], int, int)} may * not read as many bytes as requested (most likely because of reaching EOF). * * @param input where to read input from * @param buffer destination * @param offset inital offset into buffer * @param length length to read, must be >= 0 * * @throws IOException if there is a problem reading the file * @throws IllegalArgumentException if length is negative * @throws EOFException if the number of bytes read was incorrect * @since 2.2 */ public static void readFully(InputStream input, byte[] buffer, int offset, int length) throws IOException { int actual = read(input, buffer, offset, length); if (actual != length) { throw new EOFException("Length to read: " + length + " actual: " + actual); } } /** * Read the requested number of bytes or fail if there are not enough left. *

* This allows for the possibility that {@link InputStream#read(byte[], int, int)} may * not read as many bytes as requested (most likely because of reaching EOF). * * @param input where to read input from * @param buffer destination * * @throws IOException if there is a problem reading the file * @throws IllegalArgumentException if length is negative * @throws EOFException if the number of bytes read was incorrect * @since 2.2 */ public static void readFully(InputStream input, byte[] buffer) throws IOException { readFully(input, buffer, 0, buffer.length); } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/FileDeleteStrategy.java0000644000175000017500000001315612125050425030454 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.io.File; import java.io.IOException; /** * Strategy for deleting files. *

* There is more than one way to delete a file. * You may want to limit access to certain directories, to only delete * directories if they are empty, or maybe to force deletion. *

* This class captures the strategy to use and is designed for user subclassing. * * @version $Id: FileDeleteStrategy.java 1307461 2012-03-30 15:12:29Z ggregory $ * @since 1.3 */ public class FileDeleteStrategy { /** * The singleton instance for normal file deletion, which does not permit * the deletion of directories that are not empty. */ public static final FileDeleteStrategy NORMAL = new FileDeleteStrategy("Normal"); /** * The singleton instance for forced file deletion, which always deletes, * even if the file represents a non-empty directory. */ public static final FileDeleteStrategy FORCE = new ForceFileDeleteStrategy(); /** The name of the strategy. */ private final String name; //----------------------------------------------------------------------- /** * Restricted constructor. * * @param name the name by which the strategy is known */ protected FileDeleteStrategy(String name) { this.name = name; } //----------------------------------------------------------------------- /** * Deletes the file object, which may be a file or a directory. * All IOExceptions are caught and false returned instead. * If the file does not exist or is null, true is returned. *

* Subclass writers should override {@link #doDelete(File)}, not this method. * * @param fileToDelete the file to delete, null returns true * @return true if the file was deleted, or there was no such file */ public boolean deleteQuietly(File fileToDelete) { if (fileToDelete == null || fileToDelete.exists() == false) { return true; } try { return doDelete(fileToDelete); } catch (IOException ex) { return false; } } /** * Deletes the file object, which may be a file or a directory. * If the file does not exist, the method just returns. *

* Subclass writers should override {@link #doDelete(File)}, not this method. * * @param fileToDelete the file to delete, not null * @throws NullPointerException if the file is null * @throws IOException if an error occurs during file deletion */ public void delete(File fileToDelete) throws IOException { if (fileToDelete.exists() && doDelete(fileToDelete) == false) { throw new IOException("Deletion failed: " + fileToDelete); } } /** * Actually deletes the file object, which may be a file or a directory. *

* This method is designed for subclasses to override. * The implementation may return either false or an IOException * when deletion fails. The {@link #delete(File)} and {@link #deleteQuietly(File)} * methods will handle either response appropriately. * A check has been made to ensure that the file will exist. *

* This implementation uses {@link File#delete()}. * * @param fileToDelete the file to delete, exists, not null * @return true if the file was deleteds * @throws NullPointerException if the file is null * @throws IOException if an error occurs during file deletion */ protected boolean doDelete(File fileToDelete) throws IOException { return fileToDelete.delete(); } //----------------------------------------------------------------------- /** * Gets a string describing the delete strategy. * * @return a string describing the delete strategy */ @Override public String toString() { return "FileDeleteStrategy[" + name + "]"; } //----------------------------------------------------------------------- /** * Force file deletion strategy. */ static class ForceFileDeleteStrategy extends FileDeleteStrategy { /** Default Constructor */ ForceFileDeleteStrategy() { super("Force"); } /** * Deletes the file object. *

* This implementation uses FileUtils.forceDelete() * if the file exists. * * @param fileToDelete the file to delete, not null * @return Always returns {@code true} * @throws NullPointerException if the file is null * @throws IOException if an error occurs during file deletion */ @Override protected boolean doDelete(File fileToDelete) throws IOException { FileUtils.forceDelete(fileToDelete); return true; } } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/output/0000755000175000017500000000000012125050425025416 5ustar ebourgebourglibcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/output/StringBuilderWriter.java0000644000175000017500000001064012125050425032234 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.output; import java.io.Serializable; import java.io.Writer; /** * {@link Writer} implementation that outputs to a {@link StringBuilder}. *

* NOTE: This implementation, as an alternative to * java.io.StringWriter, provides an un-synchronized * (i.e. for use in a single thread) implementation for better performance. * For safe usage with multiple {@link Thread}s then * java.io.StringWriter should be used. * * @version $Id: StringBuilderWriter.java 1304052 2012-03-22 20:55:29Z ggregory $ * @since 2.0 */ public class StringBuilderWriter extends Writer implements Serializable { private final StringBuilder builder; /** * Construct a new {@link StringBuilder} instance with default capacity. */ public StringBuilderWriter() { this.builder = new StringBuilder(); } /** * Construct a new {@link StringBuilder} instance with the specified capacity. * * @param capacity The initial capacity of the underlying {@link StringBuilder} */ public StringBuilderWriter(int capacity) { this.builder = new StringBuilder(capacity); } /** * Construct a new instance with the specified {@link StringBuilder}. * * @param builder The String builder */ public StringBuilderWriter(StringBuilder builder) { this.builder = builder != null ? builder : new StringBuilder(); } /** * Append a single character to this Writer. * * @param value The character to append * @return This writer instance */ @Override public Writer append(char value) { builder.append(value); return this; } /** * Append a character sequence to this Writer. * * @param value The character to append * @return This writer instance */ @Override public Writer append(CharSequence value) { builder.append(value); return this; } /** * Append a portion of a character sequence to the {@link StringBuilder}. * * @param value The character to append * @param start The index of the first character * @param end The index of the last character + 1 * @return This writer instance */ @Override public Writer append(CharSequence value, int start, int end) { builder.append(value, start, end); return this; } /** * Closing this writer has no effect. */ @Override public void close() { } /** * Flushing this writer has no effect. */ @Override public void flush() { } /** * Write a String to the {@link StringBuilder}. * * @param value The value to write */ @Override public void write(String value) { if (value != null) { builder.append(value); } } /** * Write a portion of a character array to the {@link StringBuilder}. * * @param value The value to write * @param offset The index of the first character * @param length The number of characters to write */ @Override public void write(char[] value, int offset, int length) { if (value != null) { builder.append(value, offset, length); } } /** * Return the underlying builder. * * @return The underlying builder */ public StringBuilder getBuilder() { return builder; } /** * Returns {@link StringBuilder#toString()}. * * @return The contents of the String builder. */ @Override public String toString() { return builder.toString(); } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/output/ThresholdingOutputStream.java0000644000175000017500000001610212125050425033310 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.output; import java.io.IOException; import java.io.OutputStream; /** * An output stream which triggers an event when a specified number of bytes of * data have been written to it. The event can be used, for example, to throw * an exception if a maximum has been reached, or to switch the underlying * stream type when the threshold is exceeded. *

* This class overrides all OutputStream methods. However, these * overrides ultimately call the corresponding methods in the underlying output * stream implementation. *

* NOTE: This implementation may trigger the event before the threshold * is actually reached, since it triggers when a pending write operation would * cause the threshold to be exceeded. * * @version $Id: ThresholdingOutputStream.java 1307462 2012-03-30 15:13:11Z ggregory $ */ public abstract class ThresholdingOutputStream extends OutputStream { // ----------------------------------------------------------- Data members /** * The threshold at which the event will be triggered. */ private final int threshold; /** * The number of bytes written to the output stream. */ private long written; /** * Whether or not the configured threshold has been exceeded. */ private boolean thresholdExceeded; // ----------------------------------------------------------- Constructors /** * Constructs an instance of this class which will trigger an event at the * specified threshold. * * @param threshold The number of bytes at which to trigger an event. */ public ThresholdingOutputStream(int threshold) { this.threshold = threshold; } // --------------------------------------------------- OutputStream methods /** * Writes the specified byte to this output stream. * * @param b The byte to be written. * * @exception IOException if an error occurs. */ @Override public void write(int b) throws IOException { checkThreshold(1); getStream().write(b); written++; } /** * Writes b.length bytes from the specified byte array to this * output stream. * * @param b The array of bytes to be written. * * @exception IOException if an error occurs. */ @Override public void write(byte b[]) throws IOException { checkThreshold(b.length); getStream().write(b); written += b.length; } /** * Writes len bytes from the specified byte array starting at * offset off to this output stream. * * @param b The byte array from which the data will be written. * @param off The start offset in the byte array. * @param len The number of bytes to write. * * @exception IOException if an error occurs. */ @Override public void write(byte b[], int off, int len) throws IOException { checkThreshold(len); getStream().write(b, off, len); written += len; } /** * Flushes this output stream and forces any buffered output bytes to be * written out. * * @exception IOException if an error occurs. */ @Override public void flush() throws IOException { getStream().flush(); } /** * Closes this output stream and releases any system resources associated * with this stream. * * @exception IOException if an error occurs. */ @Override public void close() throws IOException { try { flush(); } catch (IOException ignored) { // ignore } getStream().close(); } // --------------------------------------------------------- Public methods /** * Returns the threshold, in bytes, at which an event will be triggered. * * @return The threshold point, in bytes. */ public int getThreshold() { return threshold; } /** * Returns the number of bytes that have been written to this output stream. * * @return The number of bytes written. */ public long getByteCount() { return written; } /** * Determines whether or not the configured threshold has been exceeded for * this output stream. * * @return {@code true} if the threshold has been reached; * {@code false} otherwise. */ public boolean isThresholdExceeded() { return written > threshold; } // ------------------------------------------------------ Protected methods /** * Checks to see if writing the specified number of bytes would cause the * configured threshold to be exceeded. If so, triggers an event to allow * a concrete implementation to take action on this. * * @param count The number of bytes about to be written to the underlying * output stream. * * @exception IOException if an error occurs. */ protected void checkThreshold(int count) throws IOException { if (!thresholdExceeded && written + count > threshold) { thresholdExceeded = true; thresholdReached(); } } /** * Resets the byteCount to zero. You can call this from * {@link #thresholdReached()} if you want the event to be triggered again. */ protected void resetByteCount() { this.thresholdExceeded = false; this.written = 0; } // ------------------------------------------------------- Abstract methods /** * Returns the underlying output stream, to which the corresponding * OutputStream methods in this class will ultimately delegate. * * @return The underlying output stream. * * @exception IOException if an error occurs. */ protected abstract OutputStream getStream() throws IOException; /** * Indicates that the configured threshold has been reached, and that a * subclass should take whatever action necessary on this event. This may * include changing the underlying output stream. * * @exception IOException if an error occurs. */ protected abstract void thresholdReached() throws IOException; } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/output/ProxyOutputStream.java0000644000175000017500000001256512125050425032010 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.output; import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; /** * A Proxy stream which acts as expected, that is it passes the method * calls on to the proxied stream and doesn't change which methods are * being called. It is an alternative base class to FilterOutputStream * to increase reusability. *

* See the protected methods for ways in which a subclass can easily decorate * a stream with custom pre-, post- or error processing functionality. * * @version $Id: ProxyOutputStream.java 1304052 2012-03-22 20:55:29Z ggregory $ */ public class ProxyOutputStream extends FilterOutputStream { /** * Constructs a new ProxyOutputStream. * * @param proxy the OutputStream to delegate to */ public ProxyOutputStream(OutputStream proxy) { super(proxy); // the proxy is stored in a protected superclass variable named 'out' } /** * Invokes the delegate's write(int) method. * @param idx the byte to write * @throws IOException if an I/O error occurs */ @Override public void write(int idx) throws IOException { try { beforeWrite(1); out.write(idx); afterWrite(1); } catch (IOException e) { handleIOException(e); } } /** * Invokes the delegate's write(byte[]) method. * @param bts the bytes to write * @throws IOException if an I/O error occurs */ @Override public void write(byte[] bts) throws IOException { try { int len = bts != null ? bts.length : 0; beforeWrite(len); out.write(bts); afterWrite(len); } catch (IOException e) { handleIOException(e); } } /** * Invokes the delegate's write(byte[]) method. * @param bts the bytes to write * @param st The start offset * @param end The number of bytes to write * @throws IOException if an I/O error occurs */ @Override public void write(byte[] bts, int st, int end) throws IOException { try { beforeWrite(end); out.write(bts, st, end); afterWrite(end); } catch (IOException e) { handleIOException(e); } } /** * Invokes the delegate's flush() method. * @throws IOException if an I/O error occurs */ @Override public void flush() throws IOException { try { out.flush(); } catch (IOException e) { handleIOException(e); } } /** * Invokes the delegate's close() method. * @throws IOException if an I/O error occurs */ @Override public void close() throws IOException { try { out.close(); } catch (IOException e) { handleIOException(e); } } /** * Invoked by the write methods before the call is proxied. The number * of bytes to be written (1 for the {@link #write(int)} method, buffer * length for {@link #write(byte[])}, etc.) is given as an argument. *

* Subclasses can override this method to add common pre-processing * functionality without having to override all the write methods. * The default implementation does nothing. * * @since 2.0 * @param n number of bytes to be written * @throws IOException if the pre-processing fails */ protected void beforeWrite(int n) throws IOException { } /** * Invoked by the write methods after the proxied call has returned * successfully. The number of bytes written (1 for the * {@link #write(int)} method, buffer length for {@link #write(byte[])}, * etc.) is given as an argument. *

* Subclasses can override this method to add common post-processing * functionality without having to override all the write methods. * The default implementation does nothing. * * @since 2.0 * @param n number of bytes written * @throws IOException if the post-processing fails */ protected void afterWrite(int n) throws IOException { } /** * Handle any IOExceptions thrown. *

* This method provides a point to implement custom exception * handling. The default behaviour is to re-throw the exception. * @param e The IOException thrown * @throws IOException if an I/O error occurs * @since 2.0 */ protected void handleIOException(IOException e) throws IOException { throw e; } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/output/LockableFileWriter.java0000644000175000017500000003160212125050425031774 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.output; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.nio.charset.Charset; import java.nio.charset.UnsupportedCharsetException; import org.apache.commons.io.Charsets; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; /** * FileWriter that will create and honor lock files to allow simple * cross thread file lock handling. *

* This class provides a simple alternative to FileWriter * that will use a lock file to prevent duplicate writes. *

* N.B. the lock file is deleted when {@link #close()} is called * - or if the main file cannot be opened initially. * In the (unlikely) event that the lockfile cannot be deleted, * this is not reported, and subsequent requests using * the same lockfile will fail. *

* By default, the file will be overwritten, but this may be changed to append. * The lock directory may be specified, but defaults to the system property * java.io.tmpdir. * The encoding may also be specified, and defaults to the platform default. * * @version $Id: LockableFileWriter.java 1347574 2012-06-07 11:20:39Z sebb $ */ public class LockableFileWriter extends Writer { // Cannot extend ProxyWriter, as requires writer to be // known when super() is called /** The extension for the lock file. */ private static final String LCK = ".lck"; /** The writer to decorate. */ private final Writer out; /** The lock file. */ private final File lockFile; /** * Constructs a LockableFileWriter. * If the file exists, it is overwritten. * * @param fileName the file to write to, not null * @throws NullPointerException if the file is null * @throws IOException in case of an I/O error */ public LockableFileWriter(String fileName) throws IOException { this(fileName, false, null); } /** * Constructs a LockableFileWriter. * * @param fileName file to write to, not null * @param append true if content should be appended, false to overwrite * @throws NullPointerException if the file is null * @throws IOException in case of an I/O error */ public LockableFileWriter(String fileName, boolean append) throws IOException { this(fileName, append, null); } /** * Constructs a LockableFileWriter. * * @param fileName the file to write to, not null * @param append true if content should be appended, false to overwrite * @param lockDir the directory in which the lock file should be held * @throws NullPointerException if the file is null * @throws IOException in case of an I/O error */ public LockableFileWriter(String fileName, boolean append, String lockDir) throws IOException { this(new File(fileName), append, lockDir); } /** * Constructs a LockableFileWriter. * If the file exists, it is overwritten. * * @param file the file to write to, not null * @throws NullPointerException if the file is null * @throws IOException in case of an I/O error */ public LockableFileWriter(File file) throws IOException { this(file, false, null); } /** * Constructs a LockableFileWriter. * * @param file the file to write to, not null * @param append true if content should be appended, false to overwrite * @throws NullPointerException if the file is null * @throws IOException in case of an I/O error */ public LockableFileWriter(File file, boolean append) throws IOException { this(file, append, null); } /** * Constructs a LockableFileWriter. * * @param file the file to write to, not null * @param append true if content should be appended, false to overwrite * @param lockDir the directory in which the lock file should be held * @throws NullPointerException if the file is null * @throws IOException in case of an I/O error */ public LockableFileWriter(File file, boolean append, String lockDir) throws IOException { this(file, Charset.defaultCharset(), append, lockDir); } /** * Constructs a LockableFileWriter with a file encoding. * * @param file the file to write to, not null * @param encoding the encoding to use, null means platform default * @throws NullPointerException if the file is null * @throws IOException in case of an I/O error * @since 2.3 */ public LockableFileWriter(File file, Charset encoding) throws IOException { this(file, encoding, false, null); } /** * Constructs a LockableFileWriter with a file encoding. * * @param file the file to write to, not null * @param encoding the encoding to use, null means platform default * @throws NullPointerException if the file is null * @throws IOException in case of an I/O error * @throws UnsupportedCharsetException * thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not * supported. */ public LockableFileWriter(File file, String encoding) throws IOException { this(file, encoding, false, null); } /** * Constructs a LockableFileWriter with a file encoding. * * @param file the file to write to, not null * @param encoding the encoding to use, null means platform default * @param append true if content should be appended, false to overwrite * @param lockDir the directory in which the lock file should be held * @throws NullPointerException if the file is null * @throws IOException in case of an I/O error * @since 2.3 */ public LockableFileWriter(File file, Charset encoding, boolean append, String lockDir) throws IOException { super(); // init file to create/append file = file.getAbsoluteFile(); if (file.getParentFile() != null) { FileUtils.forceMkdir(file.getParentFile()); } if (file.isDirectory()) { throw new IOException("File specified is a directory"); } // init lock file if (lockDir == null) { lockDir = System.getProperty("java.io.tmpdir"); } File lockDirFile = new File(lockDir); FileUtils.forceMkdir(lockDirFile); testLockDir(lockDirFile); lockFile = new File(lockDirFile, file.getName() + LCK); // check if locked createLock(); // init wrapped writer out = initWriter(file, encoding, append); } /** * Constructs a LockableFileWriter with a file encoding. * * @param file the file to write to, not null * @param encoding the encoding to use, null means platform default * @param append true if content should be appended, false to overwrite * @param lockDir the directory in which the lock file should be held * @throws NullPointerException if the file is null * @throws IOException in case of an I/O error * @throws UnsupportedCharsetException * thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not * supported. */ public LockableFileWriter(File file, String encoding, boolean append, String lockDir) throws IOException { this(file, Charsets.toCharset(encoding), append, lockDir); } //----------------------------------------------------------------------- /** * Tests that we can write to the lock directory. * * @param lockDir the File representing the lock directory * @throws IOException if we cannot write to the lock directory * @throws IOException if we cannot find the lock file */ private void testLockDir(File lockDir) throws IOException { if (!lockDir.exists()) { throw new IOException( "Could not find lockDir: " + lockDir.getAbsolutePath()); } if (!lockDir.canWrite()) { throw new IOException( "Could not write to lockDir: " + lockDir.getAbsolutePath()); } } /** * Creates the lock file. * * @throws IOException if we cannot create the file */ private void createLock() throws IOException { synchronized (LockableFileWriter.class) { if (!lockFile.createNewFile()) { throw new IOException("Can't write file, lock " + lockFile.getAbsolutePath() + " exists"); } lockFile.deleteOnExit(); } } /** * Initialise the wrapped file writer. * Ensure that a cleanup occurs if the writer creation fails. * * @param file the file to be accessed * @param encoding the encoding to use * @param append true to append * @return The initialised writer * @throws IOException if an error occurs */ private Writer initWriter(File file, Charset encoding, boolean append) throws IOException { boolean fileExistedAlready = file.exists(); OutputStream stream = null; Writer writer = null; try { stream = new FileOutputStream(file.getAbsolutePath(), append); writer = new OutputStreamWriter(stream, Charsets.toCharset(encoding)); } catch (IOException ex) { IOUtils.closeQuietly(writer); IOUtils.closeQuietly(stream); FileUtils.deleteQuietly(lockFile); if (fileExistedAlready == false) { FileUtils.deleteQuietly(file); } throw ex; } catch (RuntimeException ex) { IOUtils.closeQuietly(writer); IOUtils.closeQuietly(stream); FileUtils.deleteQuietly(lockFile); if (fileExistedAlready == false) { FileUtils.deleteQuietly(file); } throw ex; } return writer; } //----------------------------------------------------------------------- /** * Closes the file writer and deletes the lockfile (if possible). * * @throws IOException if an I/O error occurs */ @Override public void close() throws IOException { try { out.close(); } finally { lockFile.delete(); } } //----------------------------------------------------------------------- /** * Write a character. * @param idx the character to write * @throws IOException if an I/O error occurs */ @Override public void write(int idx) throws IOException { out.write(idx); } /** * Write the characters from an array. * @param chr the characters to write * @throws IOException if an I/O error occurs */ @Override public void write(char[] chr) throws IOException { out.write(chr); } /** * Write the specified characters from an array. * @param chr the characters to write * @param st The start offset * @param end The number of characters to write * @throws IOException if an I/O error occurs */ @Override public void write(char[] chr, int st, int end) throws IOException { out.write(chr, st, end); } /** * Write the characters from a string. * @param str the string to write * @throws IOException if an I/O error occurs */ @Override public void write(String str) throws IOException { out.write(str); } /** * Write the specified characters from a string. * @param str the string to write * @param st The start offset * @param end The number of characters to write * @throws IOException if an I/O error occurs */ @Override public void write(String str, int st, int end) throws IOException { out.write(str, st, end); } /** * Flush the stream. * @throws IOException if an I/O error occurs */ @Override public void flush() throws IOException { out.flush(); } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/output/TaggedOutputStream.java0000644000175000017500000000774612125050425032067 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.output; import java.io.IOException; import java.io.OutputStream; import java.io.Serializable; import java.util.UUID; import org.apache.commons.io.TaggedIOException; /** * An output stream decorator that tags potential exceptions so that the * stream that caused the exception can easily be identified. This is * done by using the {@link TaggedIOException} class to wrap all thrown * {@link IOException}s. See below for an example of using this class. *

 * TaggedOutputStream stream = new TaggedOutputStream(...);
 * try {
 *     // Processing that may throw an IOException either from this stream
 *     // or from some other IO activity like temporary files, etc.
 *     writeToStream(stream);
 * } catch (IOException e) {
 *     if (stream.isCauseOf(e)) {
 *         // The exception was caused by this stream.
 *         // Use e.getCause() to get the original exception.
 *     } else {
 *         // The exception was caused by something else.
 *     }
 * }
 * 
*

* Alternatively, the {@link #throwIfCauseOf(Exception)} method can be * used to let higher levels of code handle the exception caused by this * stream while other processing errors are being taken care of at this * lower level. *

 * TaggedOutputStream stream = new TaggedOutputStream(...);
 * try {
 *     writeToStream(stream);
 * } catch (IOException e) {
 *     stream.throwIfCauseOf(e);
 *     // ... or process the exception that was caused by something else
 * }
 * 
* * @see TaggedIOException * @since 2.0 */ public class TaggedOutputStream extends ProxyOutputStream { /** * The unique tag associated with exceptions from stream. */ private final Serializable tag = UUID.randomUUID(); /** * Creates a tagging decorator for the given output stream. * * @param proxy output stream to be decorated */ public TaggedOutputStream(OutputStream proxy) { super(proxy); } /** * Tests if the given exception was caused by this stream. * * @param exception an exception * @return {@code true} if the exception was thrown by this stream, * {@code false} otherwise */ public boolean isCauseOf(Exception exception) { return TaggedIOException.isTaggedWith(exception, tag); } /** * Re-throws the original exception thrown by this stream. This method * first checks whether the given exception is a {@link TaggedIOException} * wrapper created by this decorator, and then unwraps and throws the * original wrapped exception. Returns normally if the exception was * not thrown by this stream. * * @param exception an exception * @throws IOException original exception, if any, thrown by this stream */ public void throwIfCauseOf(Exception exception) throws IOException { TaggedIOException.throwCauseIfTaggedWith(exception, tag); } /** * Tags any IOExceptions thrown, wrapping and re-throwing. * * @param e The IOException thrown * @throws IOException if an I/O error occurs */ @Override protected void handleIOException(IOException e) throws IOException { throw new TaggedIOException(e, tag); } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/output/NullWriter.java0000644000175000017500000000723312125050425030375 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.output; import java.io.Writer; /** * This {@link Writer} writes all data to the famous /dev/null. *

* This Writer has no destination (file/socket etc.) and all * characters written to it are ignored and lost. * * @version $Id: NullWriter.java 1304052 2012-03-22 20:55:29Z ggregory $ */ public class NullWriter extends Writer { /** * A singleton. */ public static final NullWriter NULL_WRITER = new NullWriter(); /** * Constructs a new NullWriter. */ public NullWriter() { } /** * Does nothing - output to /dev/null. * @param c The character to write * @return this writer * @since 2.0 */ @Override public Writer append(char c) { //to /dev/null return this; } /** * Does nothing - output to /dev/null. * @param csq The character sequence to write * @param start The index of the first character to write * @param end The index of the first character to write (exclusive) * @return this writer * @since 2.0 */ @Override public Writer append(CharSequence csq, int start, int end) { //to /dev/null return this; } /** * Does nothing - output to /dev/null. * @param csq The character sequence to write * @return this writer * @since 2.0 */ @Override public Writer append(CharSequence csq) { //to /dev/null return this; } /** * Does nothing - output to /dev/null. * @param idx The character to write */ @Override public void write(int idx) { //to /dev/null } /** * Does nothing - output to /dev/null. * @param chr The characters to write */ @Override public void write(char[] chr) { //to /dev/null } /** * Does nothing - output to /dev/null. * @param chr The characters to write * @param st The start offset * @param end The number of characters to write */ @Override public void write(char[] chr, int st, int end) { //to /dev/null } /** * Does nothing - output to /dev/null. * @param str The string to write */ @Override public void write(String str) { //to /dev/null } /** * Does nothing - output to /dev/null. * @param str The string to write * @param st The start offset * @param end The number of characters to write */ @Override public void write(String str, int st, int end) { //to /dev/null } /** @see java.io.Writer#flush() */ @Override public void flush() { //to /dev/null } /** @see java.io.Writer#close() */ @Override public void close() { //to /dev/null } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/output/FileWriterWithEncoding.java0000644000175000017500000002760712125050425032654 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.output; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; /** * Writer of files that allows the encoding to be set. *

* This class provides a simple alternative to FileWriter * that allows an encoding to be set. Unfortunately, it cannot subclass * FileWriter. *

* By default, the file will be overwritten, but this may be changed to append. *

* The encoding must be specified using either the name of the {@link Charset}, * the {@link Charset}, or a {@link CharsetEncoder}. If the default encoding * is required then use the {@link java.io.FileWriter} directly, rather than * this implementation. *

* * * @since 1.4 * @version $Id: FileWriterWithEncoding.java 1304052 2012-03-22 20:55:29Z ggregory $ */ public class FileWriterWithEncoding extends Writer { // Cannot extend ProxyWriter, as requires writer to be // known when super() is called /** The writer to decorate. */ private final Writer out; /** * Constructs a FileWriterWithEncoding with a file encoding. * * @param filename the name of the file to write to, not null * @param encoding the encoding to use, not null * @throws NullPointerException if the file name or encoding is null * @throws IOException in case of an I/O error */ public FileWriterWithEncoding(String filename, String encoding) throws IOException { this(new File(filename), encoding, false); } /** * Constructs a FileWriterWithEncoding with a file encoding. * * @param filename the name of the file to write to, not null * @param encoding the encoding to use, not null * @param append true if content should be appended, false to overwrite * @throws NullPointerException if the file name or encoding is null * @throws IOException in case of an I/O error */ public FileWriterWithEncoding(String filename, String encoding, boolean append) throws IOException { this(new File(filename), encoding, append); } /** * Constructs a FileWriterWithEncoding with a file encoding. * * @param filename the name of the file to write to, not null * @param encoding the encoding to use, not null * @throws NullPointerException if the file name or encoding is null * @throws IOException in case of an I/O error */ public FileWriterWithEncoding(String filename, Charset encoding) throws IOException { this(new File(filename), encoding, false); } /** * Constructs a FileWriterWithEncoding with a file encoding. * * @param filename the name of the file to write to, not null * @param encoding the encoding to use, not null * @param append true if content should be appended, false to overwrite * @throws NullPointerException if the file name or encoding is null * @throws IOException in case of an I/O error */ public FileWriterWithEncoding(String filename, Charset encoding, boolean append) throws IOException { this(new File(filename), encoding, append); } /** * Constructs a FileWriterWithEncoding with a file encoding. * * @param filename the name of the file to write to, not null * @param encoding the encoding to use, not null * @throws NullPointerException if the file name or encoding is null * @throws IOException in case of an I/O error */ public FileWriterWithEncoding(String filename, CharsetEncoder encoding) throws IOException { this(new File(filename), encoding, false); } /** * Constructs a FileWriterWithEncoding with a file encoding. * * @param filename the name of the file to write to, not null * @param encoding the encoding to use, not null * @param append true if content should be appended, false to overwrite * @throws NullPointerException if the file name or encoding is null * @throws IOException in case of an I/O error */ public FileWriterWithEncoding(String filename, CharsetEncoder encoding, boolean append) throws IOException { this(new File(filename), encoding, append); } /** * Constructs a FileWriterWithEncoding with a file encoding. * * @param file the file to write to, not null * @param encoding the encoding to use, not null * @throws NullPointerException if the file or encoding is null * @throws IOException in case of an I/O error */ public FileWriterWithEncoding(File file, String encoding) throws IOException { this(file, encoding, false); } /** * Constructs a FileWriterWithEncoding with a file encoding. * * @param file the file to write to, not null * @param encoding the encoding to use, not null * @param append true if content should be appended, false to overwrite * @throws NullPointerException if the file or encoding is null * @throws IOException in case of an I/O error */ public FileWriterWithEncoding(File file, String encoding, boolean append) throws IOException { super(); this.out = initWriter(file, encoding, append); } /** * Constructs a FileWriterWithEncoding with a file encoding. * * @param file the file to write to, not null * @param encoding the encoding to use, not null * @throws NullPointerException if the file or encoding is null * @throws IOException in case of an I/O error */ public FileWriterWithEncoding(File file, Charset encoding) throws IOException { this(file, encoding, false); } /** * Constructs a FileWriterWithEncoding with a file encoding. * * @param file the file to write to, not null * @param encoding the encoding to use, not null * @param append true if content should be appended, false to overwrite * @throws NullPointerException if the file or encoding is null * @throws IOException in case of an I/O error */ public FileWriterWithEncoding(File file, Charset encoding, boolean append) throws IOException { super(); this.out = initWriter(file, encoding, append); } /** * Constructs a FileWriterWithEncoding with a file encoding. * * @param file the file to write to, not null * @param encoding the encoding to use, not null * @throws NullPointerException if the file or encoding is null * @throws IOException in case of an I/O error */ public FileWriterWithEncoding(File file, CharsetEncoder encoding) throws IOException { this(file, encoding, false); } /** * Constructs a FileWriterWithEncoding with a file encoding. * * @param file the file to write to, not null * @param encoding the encoding to use, not null * @param append true if content should be appended, false to overwrite * @throws NullPointerException if the file or encoding is null * @throws IOException in case of an I/O error */ public FileWriterWithEncoding(File file, CharsetEncoder encoding, boolean append) throws IOException { super(); this.out = initWriter(file, encoding, append); } //----------------------------------------------------------------------- /** * Initialise the wrapped file writer. * Ensure that a cleanup occurs if the writer creation fails. * * @param file the file to be accessed * @param encoding the encoding to use - may be Charset, CharsetEncoder or String * @param append true to append * @return the initialised writer * @throws NullPointerException if the file or encoding is null * @throws IOException if an error occurs */ private static Writer initWriter(File file, Object encoding, boolean append) throws IOException { if (file == null) { throw new NullPointerException("File is missing"); } if (encoding == null) { throw new NullPointerException("Encoding is missing"); } boolean fileExistedAlready = file.exists(); OutputStream stream = null; Writer writer = null; try { stream = new FileOutputStream(file, append); if (encoding instanceof Charset) { writer = new OutputStreamWriter(stream, (Charset)encoding); } else if (encoding instanceof CharsetEncoder) { writer = new OutputStreamWriter(stream, (CharsetEncoder)encoding); } else { writer = new OutputStreamWriter(stream, (String)encoding); } } catch (IOException ex) { IOUtils.closeQuietly(writer); IOUtils.closeQuietly(stream); if (fileExistedAlready == false) { FileUtils.deleteQuietly(file); } throw ex; } catch (RuntimeException ex) { IOUtils.closeQuietly(writer); IOUtils.closeQuietly(stream); if (fileExistedAlready == false) { FileUtils.deleteQuietly(file); } throw ex; } return writer; } //----------------------------------------------------------------------- /** * Write a character. * @param idx the character to write * @throws IOException if an I/O error occurs */ @Override public void write(int idx) throws IOException { out.write(idx); } /** * Write the characters from an array. * @param chr the characters to write * @throws IOException if an I/O error occurs */ @Override public void write(char[] chr) throws IOException { out.write(chr); } /** * Write the specified characters from an array. * @param chr the characters to write * @param st The start offset * @param end The number of characters to write * @throws IOException if an I/O error occurs */ @Override public void write(char[] chr, int st, int end) throws IOException { out.write(chr, st, end); } /** * Write the characters from a string. * @param str the string to write * @throws IOException if an I/O error occurs */ @Override public void write(String str) throws IOException { out.write(str); } /** * Write the specified characters from a string. * @param str the string to write * @param st The start offset * @param end The number of characters to write * @throws IOException if an I/O error occurs */ @Override public void write(String str, int st, int end) throws IOException { out.write(str, st, end); } /** * Flush the stream. * @throws IOException if an I/O error occurs */ @Override public void flush() throws IOException { out.flush(); } /** * Close the stream. * @throws IOException if an I/O error occurs */ @Override public void close() throws IOException { out.close(); } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/output/DeferredFileOutputStream.java0000644000175000017500000002137312125050425033204 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.output; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import org.apache.commons.io.IOUtils; /** * An output stream which will retain data in memory until a specified * threshold is reached, and only then commit it to disk. If the stream is * closed before the threshold is reached, the data will not be written to * disk at all. *

* This class originated in FileUpload processing. In this use case, you do * not know in advance the size of the file being uploaded. If the file is small * you want to store it in memory (for speed), but if the file is large you want * to store it to file (to avoid memory issues). * * @version $Id: DeferredFileOutputStream.java 1307462 2012-03-30 15:13:11Z ggregory $ */ public class DeferredFileOutputStream extends ThresholdingOutputStream { // ----------------------------------------------------------- Data members /** * The output stream to which data will be written prior to the theshold * being reached. */ private ByteArrayOutputStream memoryOutputStream; /** * The output stream to which data will be written at any given time. This * will always be one of memoryOutputStream or * diskOutputStream. */ private OutputStream currentOutputStream; /** * The file to which output will be directed if the threshold is exceeded. */ private File outputFile; /** * The temporary file prefix. */ private final String prefix; /** * The temporary file suffix. */ private final String suffix; /** * The directory to use for temporary files. */ private final File directory; /** * True when close() has been called successfully. */ private boolean closed = false; // ----------------------------------------------------------- Constructors /** * Constructs an instance of this class which will trigger an event at the * specified threshold, and save data to a file beyond that point. * * @param threshold The number of bytes at which to trigger an event. * @param outputFile The file to which data is saved beyond the threshold. */ public DeferredFileOutputStream(int threshold, File outputFile) { this(threshold, outputFile, null, null, null); } /** * Constructs an instance of this class which will trigger an event at the * specified threshold, and save data to a temporary file beyond that point. * * @param threshold The number of bytes at which to trigger an event. * @param prefix Prefix to use for the temporary file. * @param suffix Suffix to use for the temporary file. * @param directory Temporary file directory. * * @since 1.4 */ public DeferredFileOutputStream(int threshold, String prefix, String suffix, File directory) { this(threshold, null, prefix, suffix, directory); if (prefix == null) { throw new IllegalArgumentException("Temporary file prefix is missing"); } } /** * Constructs an instance of this class which will trigger an event at the * specified threshold, and save data either to a file beyond that point. * * @param threshold The number of bytes at which to trigger an event. * @param outputFile The file to which data is saved beyond the threshold. * @param prefix Prefix to use for the temporary file. * @param suffix Suffix to use for the temporary file. * @param directory Temporary file directory. */ private DeferredFileOutputStream(int threshold, File outputFile, String prefix, String suffix, File directory) { super(threshold); this.outputFile = outputFile; memoryOutputStream = new ByteArrayOutputStream(); currentOutputStream = memoryOutputStream; this.prefix = prefix; this.suffix = suffix; this.directory = directory; } // --------------------------------------- ThresholdingOutputStream methods /** * Returns the current output stream. This may be memory based or disk * based, depending on the current state with respect to the threshold. * * @return The underlying output stream. * * @exception IOException if an error occurs. */ @Override protected OutputStream getStream() throws IOException { return currentOutputStream; } /** * Switches the underlying output stream from a memory based stream to one * that is backed by disk. This is the point at which we realise that too * much data is being written to keep in memory, so we elect to switch to * disk-based storage. * * @exception IOException if an error occurs. */ @Override protected void thresholdReached() throws IOException { if (prefix != null) { outputFile = File.createTempFile(prefix, suffix, directory); } FileOutputStream fos = new FileOutputStream(outputFile); memoryOutputStream.writeTo(fos); currentOutputStream = fos; memoryOutputStream = null; } // --------------------------------------------------------- Public methods /** * Determines whether or not the data for this output stream has been * retained in memory. * * @return {@code true} if the data is available in memory; * {@code false} otherwise. */ public boolean isInMemory() { return !isThresholdExceeded(); } /** * Returns the data for this output stream as an array of bytes, assuming * that the data has been retained in memory. If the data was written to * disk, this method returns {@code null}. * * @return The data for this output stream, or {@code null} if no such * data is available. */ public byte[] getData() { if (memoryOutputStream != null) { return memoryOutputStream.toByteArray(); } return null; } /** * Returns either the output file specified in the constructor or * the temporary file created or null. *

* If the constructor specifying the file is used then it returns that * same output file, even when threshold has not been reached. *

* If constructor specifying a temporary file prefix/suffix is used * then the temporary file created once the threshold is reached is returned * If the threshold was not reached then {@code null} is returned. * * @return The file for this output stream, or {@code null} if no such * file exists. */ public File getFile() { return outputFile; } /** * Closes underlying output stream, and mark this as closed * * @exception IOException if an error occurs. */ @Override public void close() throws IOException { super.close(); closed = true; } /** * Writes the data from this output stream to the specified output stream, * after it has been closed. * * @param out output stream to write to. * @exception IOException if this stream is not yet closed or an error occurs. */ public void writeTo(OutputStream out) throws IOException { // we may only need to check if this is closed if we are working with a file // but we should force the habit of closing wether we are working with // a file or memory. if (!closed) { throw new IOException("Stream not closed"); } if(isInMemory()) { memoryOutputStream.writeTo(out); } else { FileInputStream fis = new FileInputStream(outputFile); try { IOUtils.copy(fis, out); } finally { IOUtils.closeQuietly(fis); } } } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/output/ClosedOutputStream.java0000644000175000017500000000342212125050425032070 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.output; import java.io.IOException; import java.io.OutputStream; /** * Closed output stream. This stream throws an exception on all attempts to * write something to the stream. *

* Typically uses of this class include testing for corner cases in methods * that accept an output stream and acting as a sentinel value instead of * a {@code null} output stream. * * @version $Id: ClosedOutputStream.java 1307459 2012-03-30 15:11:44Z ggregory $ * @since 1.4 */ public class ClosedOutputStream extends OutputStream { /** * A singleton. */ public static final ClosedOutputStream CLOSED_OUTPUT_STREAM = new ClosedOutputStream(); /** * Throws an {@link IOException} to indicate that the stream is closed. * * @param b ignored * @throws IOException always thrown */ @Override public void write(int b) throws IOException { throw new IOException("write(" + b + ") failed: stream is closed"); } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/output/WriterOutputStream.java0000644000175000017500000003051112125050425032132 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.output; import java.io.IOException; import java.io.OutputStream; import java.io.Writer; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CoderResult; import java.nio.charset.CodingErrorAction; /** * {@link OutputStream} implementation that transforms a byte stream to a * character stream using a specified charset encoding and writes the resulting * stream to a {@link Writer}. The stream is transformed using a * {@link CharsetDecoder} object, guaranteeing that all charset * encodings supported by the JRE are handled correctly. *

* The output of the {@link CharsetDecoder} is buffered using a fixed size buffer. * This implies that the data is written to the underlying {@link Writer} in chunks * that are no larger than the size of this buffer. By default, the buffer is * flushed only when it overflows or when {@link #flush()} or {@link #close()} * is called. In general there is therefore no need to wrap the underlying {@link Writer} * in a {@link java.io.BufferedWriter}. {@link WriterOutputStream} can also * be instructed to flush the buffer after each write operation. In this case, all * available data is written immediately to the underlying {@link Writer}, implying that * the current position of the {@link Writer} is correlated to the current position * of the {@link WriterOutputStream}. *

* {@link WriterOutputStream} implements the inverse transformation of {@link java.io.OutputStreamWriter}; * in the following example, writing to out2 would have the same result as writing to * out directly (provided that the byte sequence is legal with respect to the * charset encoding): *

 * OutputStream out = ...
 * Charset cs = ...
 * OutputStreamWriter writer = new OutputStreamWriter(out, cs);
 * WriterOutputStream out2 = new WriterOutputStream(writer, cs);
* {@link WriterOutputStream} implements the same transformation as {@link java.io.InputStreamReader}, * except that the control flow is reversed: both classes transform a byte stream * into a character stream, but {@link java.io.InputStreamReader} pulls data from the underlying stream, * while {@link WriterOutputStream} pushes it to the underlying stream. *

* Note that while there are use cases where there is no alternative to using * this class, very often the need to use this class is an indication of a flaw * in the design of the code. This class is typically used in situations where an existing * API only accepts an {@link OutputStream} object, but where the stream is known to represent * character data that must be decoded for further use. *

* Instances of {@link WriterOutputStream} are not thread safe. * * @see org.apache.commons.io.input.ReaderInputStream * * @since 2.0 */ public class WriterOutputStream extends OutputStream { private static final int DEFAULT_BUFFER_SIZE = 1024; private final Writer writer; private final CharsetDecoder decoder; private final boolean writeImmediately; /** * ByteBuffer used as input for the decoder. This buffer can be small * as it is used only to transfer the received data to the * decoder. */ private final ByteBuffer decoderIn = ByteBuffer.allocate(128); /** * CharBuffer used as output for the decoder. It should be * somewhat larger as we write from this buffer to the * underlying Writer. */ private final CharBuffer decoderOut; /** * Constructs a new {@link WriterOutputStream} with a default output buffer size of * 1024 characters. The output buffer will only be flushed when it overflows or when * {@link #flush()} or {@link #close()} is called. * * @param writer the target {@link Writer} * @param decoder the charset decoder * @since 2.1 */ public WriterOutputStream(Writer writer, CharsetDecoder decoder) { this(writer, decoder, DEFAULT_BUFFER_SIZE, false); } /** * Constructs a new {@link WriterOutputStream}. * * @param writer the target {@link Writer} * @param decoder the charset decoder * @param bufferSize the size of the output buffer in number of characters * @param writeImmediately If true the output buffer will be flushed after each * write operation, i.e. all available data will be written to the * underlying {@link Writer} immediately. If false, the * output buffer will only be flushed when it overflows or when * {@link #flush()} or {@link #close()} is called. * @since 2.1 */ public WriterOutputStream(Writer writer, CharsetDecoder decoder, int bufferSize, boolean writeImmediately) { this.writer = writer; this.decoder = decoder; this.writeImmediately = writeImmediately; decoderOut = CharBuffer.allocate(bufferSize); } /** * Constructs a new {@link WriterOutputStream}. * * @param writer the target {@link Writer} * @param charset the charset encoding * @param bufferSize the size of the output buffer in number of characters * @param writeImmediately If true the output buffer will be flushed after each * write operation, i.e. all available data will be written to the * underlying {@link Writer} immediately. If false, the * output buffer will only be flushed when it overflows or when * {@link #flush()} or {@link #close()} is called. */ public WriterOutputStream(Writer writer, Charset charset, int bufferSize, boolean writeImmediately) { this(writer, charset.newDecoder() .onMalformedInput(CodingErrorAction.REPLACE) .onUnmappableCharacter(CodingErrorAction.REPLACE) .replaceWith("?"), bufferSize, writeImmediately); } /** * Constructs a new {@link WriterOutputStream} with a default output buffer size of * 1024 characters. The output buffer will only be flushed when it overflows or when * {@link #flush()} or {@link #close()} is called. * * @param writer the target {@link Writer} * @param charset the charset encoding */ public WriterOutputStream(Writer writer, Charset charset) { this(writer, charset, DEFAULT_BUFFER_SIZE, false); } /** * Constructs a new {@link WriterOutputStream}. * * @param writer the target {@link Writer} * @param charsetName the name of the charset encoding * @param bufferSize the size of the output buffer in number of characters * @param writeImmediately If true the output buffer will be flushed after each * write operation, i.e. all available data will be written to the * underlying {@link Writer} immediately. If false, the * output buffer will only be flushed when it overflows or when * {@link #flush()} or {@link #close()} is called. */ public WriterOutputStream(Writer writer, String charsetName, int bufferSize, boolean writeImmediately) { this(writer, Charset.forName(charsetName), bufferSize, writeImmediately); } /** * Constructs a new {@link WriterOutputStream} with a default output buffer size of * 1024 characters. The output buffer will only be flushed when it overflows or when * {@link #flush()} or {@link #close()} is called. * * @param writer the target {@link Writer} * @param charsetName the name of the charset encoding */ public WriterOutputStream(Writer writer, String charsetName) { this(writer, charsetName, DEFAULT_BUFFER_SIZE, false); } /** * Constructs a new {@link WriterOutputStream} that uses the default character encoding * and with a default output buffer size of 1024 characters. The output buffer will only * be flushed when it overflows or when {@link #flush()} or {@link #close()} is called. * * @param writer the target {@link Writer} */ public WriterOutputStream(Writer writer) { this(writer, Charset.defaultCharset(), DEFAULT_BUFFER_SIZE, false); } /** * Write bytes from the specified byte array to the stream. * * @param b the byte array containing the bytes to write * @param off the start offset in the byte array * @param len the number of bytes to write * @throws IOException if an I/O error occurs */ @Override public void write(byte[] b, int off, int len) throws IOException { while (len > 0) { int c = Math.min(len, decoderIn.remaining()); decoderIn.put(b, off, c); processInput(false); len -= c; off += c; } if (writeImmediately) { flushOutput(); } } /** * Write bytes from the specified byte array to the stream. * * @param b the byte array containing the bytes to write * @throws IOException if an I/O error occurs */ @Override public void write(byte[] b) throws IOException { write(b, 0, b.length); } /** * Write a single byte to the stream. * * @param b the byte to write * @throws IOException if an I/O error occurs */ @Override public void write(int b) throws IOException { write(new byte[] { (byte)b }, 0, 1); } /** * Flush the stream. Any remaining content accumulated in the output buffer * will be written to the underlying {@link Writer}. After that * {@link Writer#flush()} will be called. * @throws IOException if an I/O error occurs */ @Override public void flush() throws IOException { flushOutput(); writer.flush(); } /** * Close the stream. Any remaining content accumulated in the output buffer * will be written to the underlying {@link Writer}. After that * {@link Writer#close()} will be called. * @throws IOException if an I/O error occurs */ @Override public void close() throws IOException { processInput(true); flushOutput(); writer.close(); } /** * Decode the contents of the input ByteBuffer into a CharBuffer. * * @param endOfInput indicates end of input * @throws IOException if an I/O error occurs */ private void processInput(boolean endOfInput) throws IOException { // Prepare decoderIn for reading decoderIn.flip(); CoderResult coderResult; while (true) { coderResult = decoder.decode(decoderIn, decoderOut, endOfInput); if (coderResult.isOverflow()) { flushOutput(); } else if (coderResult.isUnderflow()) { break; } else { // The decoder is configured to replace malformed input and unmappable characters, // so we should not get here. throw new IOException("Unexpected coder result"); } } // Discard the bytes that have been read decoderIn.compact(); } /** * Flush the output. * * @throws IOException if an I/O error occurs */ private void flushOutput() throws IOException { if (decoderOut.position() > 0) { writer.write(decoderOut.array(), 0, decoderOut.position()); decoderOut.rewind(); } } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/output/CloseShieldOutputStream.java0000644000175000017500000000351412125050425033057 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.output; import java.io.OutputStream; /** * Proxy stream that prevents the underlying output stream from being closed. *

* This class is typically used in cases where an output stream needs to be * passed to a component that wants to explicitly close the stream even if * other components would still use the stream for output. * * @version $Id: CloseShieldOutputStream.java 1304052 2012-03-22 20:55:29Z ggregory $ * @since 1.4 */ public class CloseShieldOutputStream extends ProxyOutputStream { /** * Creates a proxy that shields the given output stream from being * closed. * * @param out underlying output stream */ public CloseShieldOutputStream(OutputStream out) { super(out); } /** * Replaces the underlying output stream with a {@link ClosedOutputStream} * sentinel. The original output stream will remain open, but this proxy * will appear closed. */ @Override public void close() { out = new ClosedOutputStream(); } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/output/DemuxOutputStream.java0000644000175000017500000000514012125050425031740 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.output; import java.io.IOException; import java.io.OutputStream; /** * Data written to this stream is forwarded to a stream that has been associated * with this thread. * * @version $Id: DemuxOutputStream.java 1302056 2012-03-18 03:03:38Z ggregory $ */ public class DemuxOutputStream extends OutputStream { private final InheritableThreadLocal m_streams = new InheritableThreadLocal(); /** * Bind the specified stream to the current thread. * * @param output the stream to bind * @return the OutputStream that was previously active */ public OutputStream bindStream( OutputStream output ) { OutputStream stream = m_streams.get(); m_streams.set( output ); return stream; } /** * Closes stream associated with current thread. * * @throws IOException if an error occurs */ @Override public void close() throws IOException { OutputStream output = m_streams.get(); if( null != output ) { output.close(); } } /** * Flushes stream associated with current thread. * * @throws IOException if an error occurs */ @Override public void flush() throws IOException { OutputStream output = m_streams.get(); if( null != output ) { output.flush(); } } /** * Writes byte to stream associated with current thread. * * @param ch the byte to write to stream * @throws IOException if an error occurs */ @Override public void write( int ch ) throws IOException { OutputStream output = m_streams.get(); if( null != output ) { output.write( ch ); } } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/output/TeeOutputStream.java0000644000175000017500000000637012125050425031401 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.output; import java.io.IOException; import java.io.OutputStream; /** * Classic splitter of OutputStream. Named after the unix 'tee' * command. It allows a stream to be branched off so there * are now two streams. * * @version $Id: TeeOutputStream.java 1302056 2012-03-18 03:03:38Z ggregory $ */ public class TeeOutputStream extends ProxyOutputStream { /** the second OutputStream to write to */ protected OutputStream branch; /** * Constructs a TeeOutputStream. * @param out the main OutputStream * @param branch the second OutputStream */ public TeeOutputStream(OutputStream out, OutputStream branch) { super(out); this.branch = branch; } /** * Write the bytes to both streams. * @param b the bytes to write * @throws IOException if an I/O error occurs */ @Override public synchronized void write(byte[] b) throws IOException { super.write(b); this.branch.write(b); } /** * Write the specified bytes to both streams. * @param b the bytes to write * @param off The start offset * @param len The number of bytes to write * @throws IOException if an I/O error occurs */ @Override public synchronized void write(byte[] b, int off, int len) throws IOException { super.write(b, off, len); this.branch.write(b, off, len); } /** * Write a byte to both streams. * @param b the byte to write * @throws IOException if an I/O error occurs */ @Override public synchronized void write(int b) throws IOException { super.write(b); this.branch.write(b); } /** * Flushes both streams. * @throws IOException if an I/O error occurs */ @Override public void flush() throws IOException { super.flush(); this.branch.flush(); } /** * Closes both output streams. * * If closing the main output stream throws an exception, attempt to close the branch output stream. * * If closing the main and branch output streams both throw exceptions, which exceptions is thrown by this method is * currently unspecified and subject to change. * * @throws IOException * if an I/O error occurs */ @Override public void close() throws IOException { try { super.close(); } finally { this.branch.close(); } } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/output/CountingOutputStream.java0000644000175000017500000001021112125050425032437 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.output; import java.io.OutputStream; /** * A decorating output stream that counts the number of bytes that have passed * through the stream so far. *

* A typical use case would be during debugging, to ensure that data is being * written as expected. * * @version $Id: CountingOutputStream.java 1304052 2012-03-22 20:55:29Z ggregory $ */ public class CountingOutputStream extends ProxyOutputStream { /** The count of bytes that have passed. */ private long count = 0; /** * Constructs a new CountingOutputStream. * * @param out the OutputStream to write to */ public CountingOutputStream( OutputStream out ) { super(out); } //----------------------------------------------------------------------- /** * Updates the count with the number of bytes that are being written. * * @param n number of bytes to be written to the stream * @since 2.0 */ @Override protected synchronized void beforeWrite(int n) { count += n; } //----------------------------------------------------------------------- /** * The number of bytes that have passed through this stream. *

* NOTE: From v1.3 this method throws an ArithmeticException if the * count is greater than can be expressed by an int. * See {@link #getByteCount()} for a method using a long. * * @return the number of bytes accumulated * @throws ArithmeticException if the byte count is too large */ public int getCount() { long result = getByteCount(); if (result > Integer.MAX_VALUE) { throw new ArithmeticException("The byte count " + result + " is too large to be converted to an int"); } return (int) result; } /** * Set the byte count back to 0. *

* NOTE: From v1.3 this method throws an ArithmeticException if the * count is greater than can be expressed by an int. * See {@link #resetByteCount()} for a method using a long. * * @return the count previous to resetting * @throws ArithmeticException if the byte count is too large */ public int resetCount() { long result = resetByteCount(); if (result > Integer.MAX_VALUE) { throw new ArithmeticException("The byte count " + result + " is too large to be converted to an int"); } return (int) result; } /** * The number of bytes that have passed through this stream. *

* NOTE: This method is an alternative for getCount(). * It was added because that method returns an integer which will * result in incorrect count for files over 2GB. * * @return the number of bytes accumulated * @since 1.3 */ public synchronized long getByteCount() { return this.count; } /** * Set the byte count back to 0. *

* NOTE: This method is an alternative for resetCount(). * It was added because that method returns an integer which will * result in incorrect count for files over 2GB. * * @return the count previous to resetting * @since 1.3 */ public synchronized long resetByteCount() { long tmp = this.count; this.count = 0; return tmp; } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/output/ProxyWriter.java0000644000175000017500000002032612125050425030602 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.output; import java.io.FilterWriter; import java.io.IOException; import java.io.Writer; /** * A Proxy stream which acts as expected, that is it passes the method * calls on to the proxied stream and doesn't change which methods are * being called. It is an alternative base class to FilterWriter * to increase reusability, because FilterWriter changes the * methods being called, such as write(char[]) to write(char[], int, int) * and write(String) to write(String, int, int). * * @version $Id: ProxyWriter.java 1304052 2012-03-22 20:55:29Z ggregory $ */ public class ProxyWriter extends FilterWriter { /** * Constructs a new ProxyWriter. * * @param proxy the Writer to delegate to */ public ProxyWriter(Writer proxy) { super(proxy); // the proxy is stored in a protected superclass variable named 'out' } /** * Invokes the delegate's append(char) method. * @param c The character to write * @return this writer * @throws IOException if an I/O error occurs * @since 2.0 */ @Override public Writer append(char c) throws IOException { try { beforeWrite(1); out.append(c); afterWrite(1); } catch (IOException e) { handleIOException(e); } return this; } /** * Invokes the delegate's append(CharSequence, int, int) method. * @param csq The character sequence to write * @param start The index of the first character to write * @param end The index of the first character to write (exclusive) * @return this writer * @throws IOException if an I/O error occurs * @since 2.0 */ @Override public Writer append(CharSequence csq, int start, int end) throws IOException { try { beforeWrite(end - start); out.append(csq, start, end); afterWrite(end - start); } catch (IOException e) { handleIOException(e); } return this; } /** * Invokes the delegate's append(CharSequence) method. * @param csq The character sequence to write * @return this writer * @throws IOException if an I/O error occurs * @since 2.0 */ @Override public Writer append(CharSequence csq) throws IOException { try { int len = 0; if (csq != null) { len = csq.length(); } beforeWrite(len); out.append(csq); afterWrite(len); } catch (IOException e) { handleIOException(e); } return this; } /** * Invokes the delegate's write(int) method. * @param idx the character to write * @throws IOException if an I/O error occurs */ @Override public void write(int idx) throws IOException { try { beforeWrite(1); out.write(idx); afterWrite(1); } catch (IOException e) { handleIOException(e); } } /** * Invokes the delegate's write(char[]) method. * @param chr the characters to write * @throws IOException if an I/O error occurs */ @Override public void write(char[] chr) throws IOException { try { int len = 0; if (chr != null) { len = chr.length; } beforeWrite(len); out.write(chr); afterWrite(len); } catch (IOException e) { handleIOException(e); } } /** * Invokes the delegate's write(char[], int, int) method. * @param chr the characters to write * @param st The start offset * @param len The number of characters to write * @throws IOException if an I/O error occurs */ @Override public void write(char[] chr, int st, int len) throws IOException { try { beforeWrite(len); out.write(chr, st, len); afterWrite(len); } catch (IOException e) { handleIOException(e); } } /** * Invokes the delegate's write(String) method. * @param str the string to write * @throws IOException if an I/O error occurs */ @Override public void write(String str) throws IOException { try { int len = 0; if (str != null) { len = str.length(); } beforeWrite(len); out.write(str); afterWrite(len); } catch (IOException e) { handleIOException(e); } } /** * Invokes the delegate's write(String) method. * @param str the string to write * @param st The start offset * @param len The number of characters to write * @throws IOException if an I/O error occurs */ @Override public void write(String str, int st, int len) throws IOException { try { beforeWrite(len); out.write(str, st, len); afterWrite(len); } catch (IOException e) { handleIOException(e); } } /** * Invokes the delegate's flush() method. * @throws IOException if an I/O error occurs */ @Override public void flush() throws IOException { try { out.flush(); } catch (IOException e) { handleIOException(e); } } /** * Invokes the delegate's close() method. * @throws IOException if an I/O error occurs */ @Override public void close() throws IOException { try { out.close(); } catch (IOException e) { handleIOException(e); } } /** * Invoked by the write methods before the call is proxied. The number * of chars to be written (1 for the {@link #write(int)} method, buffer * length for {@link #write(char[])}, etc.) is given as an argument. *

* Subclasses can override this method to add common pre-processing * functionality without having to override all the write methods. * The default implementation does nothing. * * @since 2.0 * @param n number of chars to be written * @throws IOException if the pre-processing fails */ protected void beforeWrite(int n) throws IOException { } /** * Invoked by the write methods after the proxied call has returned * successfully. The number of chars written (1 for the * {@link #write(int)} method, buffer length for {@link #write(char[])}, * etc.) is given as an argument. *

* Subclasses can override this method to add common post-processing * functionality without having to override all the write methods. * The default implementation does nothing. * * @since 2.0 * @param n number of chars written * @throws IOException if the post-processing fails */ protected void afterWrite(int n) throws IOException { } /** * Handle any IOExceptions thrown. *

* This method provides a point to implement custom exception * handling. The default behaviour is to re-throw the exception. * @param e The IOException thrown * @throws IOException if an I/O error occurs * @since 2.0 */ protected void handleIOException(IOException e) throws IOException { throw e; } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/output/XmlStreamWriter.java0000644000175000017500000001625412125050425031402 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.output; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.StringWriter; import java.io.Writer; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.io.input.XmlStreamReader; /** * Character stream that handles all the necessary Voodo to figure out the * charset encoding of the XML document written to the stream. * * @version $Id: XmlStreamWriter.java 1304052 2012-03-22 20:55:29Z ggregory $ * @see XmlStreamReader * @since 2.0 */ public class XmlStreamWriter extends Writer { private static final int BUFFER_SIZE = 4096; private final OutputStream out; private final String defaultEncoding; private StringWriter xmlPrologWriter = new StringWriter(BUFFER_SIZE); private Writer writer; private String encoding; /** * Construct an new XML stream writer for the specified output stream * with a default encoding of UTF-8. * * @param out The output stream */ public XmlStreamWriter(OutputStream out) { this(out, null); } /** * Construct an new XML stream writer for the specified output stream * with the specified default encoding. * * @param out The output stream * @param defaultEncoding The default encoding if not encoding could be detected */ public XmlStreamWriter(OutputStream out, String defaultEncoding) { this.out = out; this.defaultEncoding = defaultEncoding != null ? defaultEncoding : "UTF-8"; } /** * Construct an new XML stream writer for the specified file * with a default encoding of UTF-8. * * @param file The file to write to * @throws FileNotFoundException if there is an error creating or * opening the file */ public XmlStreamWriter(File file) throws FileNotFoundException { this(file, null); } /** * Construct an new XML stream writer for the specified file * with the specified default encoding. * * @param file The file to write to * @param defaultEncoding The default encoding if not encoding could be detected * @throws FileNotFoundException if there is an error creating or * opening the file */ public XmlStreamWriter(File file, String defaultEncoding) throws FileNotFoundException { this(new FileOutputStream(file), defaultEncoding); } /** * Return the detected encoding. * * @return the detected encoding */ public String getEncoding() { return encoding; } /** * Return the default encoding. * * @return the default encoding */ public String getDefaultEncoding() { return defaultEncoding; } /** * Close the underlying writer. * * @throws IOException if an error occurs closing the underlying writer */ @Override public void close() throws IOException { if (writer == null) { encoding = defaultEncoding; writer = new OutputStreamWriter(out, encoding); writer.write(xmlPrologWriter.toString()); } writer.close(); } /** * Flush the underlying writer. * * @throws IOException if an error occurs flushing the underlying writer */ @Override public void flush() throws IOException { if (writer != null) { writer.flush(); } } /** * Detect the encoding. * * @param cbuf the buffer to write the characters from * @param off The start offset * @param len The number of characters to write * @throws IOException if an error occurs detecting the encoding */ private void detectEncoding(char[] cbuf, int off, int len) throws IOException { int size = len; StringBuffer xmlProlog = xmlPrologWriter.getBuffer(); if (xmlProlog.length() + len > BUFFER_SIZE) { size = BUFFER_SIZE - xmlProlog.length(); } xmlPrologWriter.write(cbuf, off, size); // try to determine encoding if (xmlProlog.length() >= 5) { if (xmlProlog.substring(0, 5).equals(""); if (xmlPrologEnd > 0) { // ok, full XML prolog written: let's extract encoding Matcher m = ENCODING_PATTERN.matcher(xmlProlog.substring(0, xmlPrologEnd)); if (m.find()) { encoding = m.group(1).toUpperCase(); encoding = encoding.substring(1, encoding.length() - 1); } else { // no encoding found in XML prolog: using default // encoding encoding = defaultEncoding; } } else { if (xmlProlog.length() >= BUFFER_SIZE) { // no encoding found in first characters: using default // encoding encoding = defaultEncoding; } } } else { // no XML prolog: using default encoding encoding = defaultEncoding; } if (encoding != null) { // encoding has been chosen: let's do it xmlPrologWriter = null; writer = new OutputStreamWriter(out, encoding); writer.write(xmlProlog.toString()); if (len > size) { writer.write(cbuf, off + size, len - size); } } } } /** * Write the characters to the underlying writer, detecing encoding. * * @param cbuf the buffer to write the characters from * @param off The start offset * @param len The number of characters to write * @throws IOException if an error occurs detecting the encoding */ @Override public void write(char[] cbuf, int off, int len) throws IOException { if (xmlPrologWriter != null) { detectEncoding(cbuf, off, len); } else { writer.write(cbuf, off, len); } } static final Pattern ENCODING_PATTERN = XmlStreamReader.ENCODING_PATTERN; } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/output/NullOutputStream.java0000644000175000017500000000402512125050425031571 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.output; import java.io.IOException; import java.io.OutputStream; /** * This OutputStream writes all data to the famous /dev/null. *

* This output stream has no destination (file/socket etc.) and all * bytes written to it are ignored and lost. * * @version $Id: NullOutputStream.java 1302056 2012-03-18 03:03:38Z ggregory $ */ public class NullOutputStream extends OutputStream { /** * A singleton. */ public static final NullOutputStream NULL_OUTPUT_STREAM = new NullOutputStream(); /** * Does nothing - output to /dev/null. * @param b The bytes to write * @param off The start offset * @param len The number of bytes to write */ @Override public void write(byte[] b, int off, int len) { //to /dev/null } /** * Does nothing - output to /dev/null. * @param b The byte to write */ @Override public void write(int b) { //to /dev/null } /** * Does nothing - output to /dev/null. * @param b The bytes to write * @throws IOException never */ @Override public void write(byte[] b) throws IOException { //to /dev/null } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/output/ByteArrayOutputStream.java0000644000175000017500000003036712125050425032571 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.output; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.SequenceInputStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.commons.io.input.ClosedInputStream; /** * This class implements an output stream in which the data is * written into a byte array. The buffer automatically grows as data * is written to it. *

* The data can be retrieved using toByteArray() and * toString(). *

* Closing a ByteArrayOutputStream has no effect. The methods in * this class can be called after the stream has been closed without * generating an IOException. *

* This is an alternative implementation of the {@link java.io.ByteArrayOutputStream} * class. The original implementation only allocates 32 bytes at the beginning. * As this class is designed for heavy duty it starts at 1024 bytes. In contrast * to the original it doesn't reallocate the whole memory block but allocates * additional buffers. This way no buffers need to be garbage collected and * the contents don't have to be copied to the new buffer. This class is * designed to behave exactly like the original. The only exception is the * deprecated toString(int) method that has been ignored. * * @version $Id: ByteArrayOutputStream.java 1304052 2012-03-22 20:55:29Z ggregory $ */ public class ByteArrayOutputStream extends OutputStream { /** A singleton empty byte array. */ private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; /** The list of buffers, which grows and never reduces. */ private final List buffers = new ArrayList(); /** The index of the current buffer. */ private int currentBufferIndex; /** The total count of bytes in all the filled buffers. */ private int filledBufferSum; /** The current buffer. */ private byte[] currentBuffer; /** The total count of bytes written. */ private int count; /** * Creates a new byte array output stream. The buffer capacity is * initially 1024 bytes, though its size increases if necessary. */ public ByteArrayOutputStream() { this(1024); } /** * Creates a new byte array output stream, with a buffer capacity of * the specified size, in bytes. * * @param size the initial size * @throws IllegalArgumentException if size is negative */ public ByteArrayOutputStream(int size) { if (size < 0) { throw new IllegalArgumentException( "Negative initial size: " + size); } synchronized (this) { needNewBuffer(size); } } /** * Makes a new buffer available either by allocating * a new one or re-cycling an existing one. * * @param newcount the size of the buffer if one is created */ private void needNewBuffer(int newcount) { if (currentBufferIndex < buffers.size() - 1) { //Recycling old buffer filledBufferSum += currentBuffer.length; currentBufferIndex++; currentBuffer = buffers.get(currentBufferIndex); } else { //Creating new buffer int newBufferSize; if (currentBuffer == null) { newBufferSize = newcount; filledBufferSum = 0; } else { newBufferSize = Math.max( currentBuffer.length << 1, newcount - filledBufferSum); filledBufferSum += currentBuffer.length; } currentBufferIndex++; currentBuffer = new byte[newBufferSize]; buffers.add(currentBuffer); } } /** * Write the bytes to byte array. * @param b the bytes to write * @param off The start offset * @param len The number of bytes to write */ @Override public void write(byte[] b, int off, int len) { if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return; } synchronized (this) { int newcount = count + len; int remaining = len; int inBufferPos = count - filledBufferSum; while (remaining > 0) { int part = Math.min(remaining, currentBuffer.length - inBufferPos); System.arraycopy(b, off + len - remaining, currentBuffer, inBufferPos, part); remaining -= part; if (remaining > 0) { needNewBuffer(newcount); inBufferPos = 0; } } count = newcount; } } /** * Write a byte to byte array. * @param b the byte to write */ @Override public synchronized void write(int b) { int inBufferPos = count - filledBufferSum; if (inBufferPos == currentBuffer.length) { needNewBuffer(count + 1); inBufferPos = 0; } currentBuffer[inBufferPos] = (byte) b; count++; } /** * Writes the entire contents of the specified input stream to this * byte stream. Bytes from the input stream are read directly into the * internal buffers of this streams. * * @param in the input stream to read from * @return total number of bytes read from the input stream * (and written to this stream) * @throws IOException if an I/O error occurs while reading the input stream * @since 1.4 */ public synchronized int write(InputStream in) throws IOException { int readCount = 0; int inBufferPos = count - filledBufferSum; int n = in.read(currentBuffer, inBufferPos, currentBuffer.length - inBufferPos); while (n != -1) { readCount += n; inBufferPos += n; count += n; if (inBufferPos == currentBuffer.length) { needNewBuffer(currentBuffer.length); inBufferPos = 0; } n = in.read(currentBuffer, inBufferPos, currentBuffer.length - inBufferPos); } return readCount; } /** * Return the current size of the byte array. * @return the current size of the byte array */ public synchronized int size() { return count; } /** * Closing a ByteArrayOutputStream has no effect. The methods in * this class can be called after the stream has been closed without * generating an IOException. * * @throws IOException never (this method should not declare this exception * but it has to now due to backwards compatability) */ @Override public void close() throws IOException { //nop } /** * @see java.io.ByteArrayOutputStream#reset() */ public synchronized void reset() { count = 0; filledBufferSum = 0; currentBufferIndex = 0; currentBuffer = buffers.get(currentBufferIndex); } /** * Writes the entire contents of this byte stream to the * specified output stream. * * @param out the output stream to write to * @throws IOException if an I/O error occurs, such as if the stream is closed * @see java.io.ByteArrayOutputStream#writeTo(OutputStream) */ public synchronized void writeTo(OutputStream out) throws IOException { int remaining = count; for (byte[] buf : buffers) { int c = Math.min(buf.length, remaining); out.write(buf, 0, c); remaining -= c; if (remaining == 0) { break; } } } /** * Fetches entire contents of an InputStream and represent * same data as result InputStream. *

* This method is useful where, *

    *
  • Source InputStream is slow.
  • *
  • It has network resources associated, so we cannot keep it open for * long time.
  • *
  • It has network timeout associated.
  • *
* It can be used in favor of {@link #toByteArray()}, since it * avoids unnecessary allocation and copy of byte[].
* This method buffers the input internally, so there is no need to use a * BufferedInputStream. * * @param input Stream to be fully buffered. * @return A fully buffered stream. * @throws IOException if an I/O error occurs * @since 2.0 */ public static InputStream toBufferedInputStream(InputStream input) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); output.write(input); return output.toBufferedInputStream(); } /** * Gets the current contents of this byte stream as a Input Stream. The * returned stream is backed by buffers of this stream, * avoiding memory allocation and copy, thus saving space and time.
* * @return the current contents of this output stream. * @see java.io.ByteArrayOutputStream#toByteArray() * @see #reset() * @since 2.0 */ private InputStream toBufferedInputStream() { int remaining = count; if (remaining == 0) { return new ClosedInputStream(); } List list = new ArrayList(buffers.size()); for (byte[] buf : buffers) { int c = Math.min(buf.length, remaining); list.add(new ByteArrayInputStream(buf, 0, c)); remaining -= c; if (remaining == 0) { break; } } return new SequenceInputStream(Collections.enumeration(list)); } /** * Gets the curent contents of this byte stream as a byte array. * The result is independent of this stream. * * @return the current contents of this output stream, as a byte array * @see java.io.ByteArrayOutputStream#toByteArray() */ public synchronized byte[] toByteArray() { int remaining = count; if (remaining == 0) { return EMPTY_BYTE_ARRAY; } byte newbuf[] = new byte[remaining]; int pos = 0; for (byte[] buf : buffers) { int c = Math.min(buf.length, remaining); System.arraycopy(buf, 0, newbuf, pos, c); pos += c; remaining -= c; if (remaining == 0) { break; } } return newbuf; } /** * Gets the curent contents of this byte stream as a string. * @return the contents of the byte array as a String * @see java.io.ByteArrayOutputStream#toString() */ @Override public String toString() { return new String(toByteArray()); } /** * Gets the curent contents of this byte stream as a string * using the specified encoding. * * @param enc the name of the character encoding * @return the string converted from the byte array * @throws UnsupportedEncodingException if the encoding is not supported * @see java.io.ByteArrayOutputStream#toString(String) */ public String toString(String enc) throws UnsupportedEncodingException { return new String(toByteArray(), enc); } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/output/BrokenOutputStream.java0000644000175000017500000000447512125050425032110 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.output; import java.io.IOException; import java.io.OutputStream; /** * Broken output stream. This stream always throws an {@link IOException} from * all {@link OutputStream} methods. *

* This class is mostly useful for testing error handling in code that uses an * output stream. * * @since 2.0 */ public class BrokenOutputStream extends OutputStream { /** * The exception that is thrown by all methods of this class. */ private final IOException exception; /** * Creates a new stream that always throws the given exception. * * @param exception the exception to be thrown */ public BrokenOutputStream(IOException exception) { this.exception = exception; } /** * Creates a new stream that always throws an {@link IOException} */ public BrokenOutputStream() { this(new IOException("Broken output stream")); } /** * Throws the configured exception. * * @param b ignored * @throws IOException always thrown */ @Override public void write(int b) throws IOException { throw exception; } /** * Throws the configured exception. * * @throws IOException always thrown */ @Override public void flush() throws IOException { throw exception; } /** * Throws the configured exception. * * @throws IOException always thrown */ @Override public void close() throws IOException { throw exception; } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/output/package.html0000644000175000017500000000173012125050425027700 0ustar ebourgebourg

This package provides implementations of output classes, such as OutputStream and Writer.

libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/monitor/0000755000175000017500000000000012125050425025545 5ustar ebourgebourglibcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/monitor/FileAlterationObserver.java0000644000175000017500000003766612125050425033044 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.monitor; import java.io.File; import java.io.FileFilter; import java.io.Serializable; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOCase; import org.apache.commons.io.comparator.NameFileComparator; /** * FileAlterationObserver represents the state of files below a root directory, * checking the filesystem and notifying listeners of create, change or * delete events. *

* To use this implementation: *

    *
  • Create {@link FileAlterationListener} implementation(s) that process * the file/directory create, change and delete events
  • *
  • Register the listener(s) with a {@link FileAlterationObserver} for * the appropriate directory.
  • *
  • Either register the observer(s) with a {@link FileAlterationMonitor} or * run manually.
  • *
* *

Basic Usage

* Create a {@link FileAlterationObserver} for the directory and register the listeners: *
 *      File directory = new File(new File("."), "src");
 *      FileAlterationObserver observer = new FileAlterationObserver(directory);
 *      observer.addListener(...);
 *      observer.addListener(...);
 * 
* To manually observe a directory, initialize the observer and invoked the * {@link #checkAndNotify()} method as required: *
 *      // intialize
 *      observer.init();
 *      ...
 *      // invoke as required
 *      observer.checkAndNotify();
 *      ...
 *      observer.checkAndNotify();
 *      ...
 *      // finished
 *      observer.finish();
 * 
* Alternatively, register the oberver(s) with a {@link FileAlterationMonitor}, * which creates a new thread, invoking the observer at the specified interval: *
 *      long interval = ...
 *      FileAlterationMonitor monitor = new FileAlterationMonitor(interval);
 *      monitor.addObserver(observer);
 *      monitor.start();
 *      ...
 *      monitor.stop();
 * 
* *

File Filters

* This implementation can monitor portions of the file system * by using {@link FileFilter}s to observe only the files and/or directories * that are of interest. This makes it more efficient and reduces the * noise from unwanted file system events. *

* Commons IO has a good range of * useful, ready made * File Filter * implementations for this purpose. *

* For example, to only observe 1) visible directories and 2) files with a ".java" suffix * in a root directory called "src" you could set up a {@link FileAlterationObserver} in the following * way: *

 *      // Create a FileFilter
 *      IOFileFilter directories = FileFilterUtils.and(
 *                                      FileFilterUtils.directoryFileFilter(),
 *                                      HiddenFileFilter.VISIBLE);
 *      IOFileFilter files       = FileFilterUtils.and(
 *                                      FileFilterUtils.fileFileFilter(),
 *                                      FileFilterUtils.suffixFileFilter(".java"));
 *      IOFileFilter filter = FileFilterUtils.or(directories, files);
 *
 *      // Create the File system observer and register File Listeners
 *      FileAlterationObserver observer = new FileAlterationObserver(new File("src"), filter);
 *      observer.addListener(...);
 *      observer.addListener(...);
 * 
* *

FileEntry

* {@link FileEntry} represents the state of a file or directory, capturing * {@link File} attributes at a point in time. Custom implementations of * {@link FileEntry} can be used to capture additional properties that the * basic implementation does not support. The {@link FileEntry#refresh(File)} * method is used to determine if a file or directory has changed since the last * check and stores the current state of the {@link File}'s properties. * * @see FileAlterationListener * @see FileAlterationMonitor * @version $Id: FileAlterationObserver.java 1304052 2012-03-22 20:55:29Z ggregory $ * @since 2.0 */ public class FileAlterationObserver implements Serializable { private final List listeners = new CopyOnWriteArrayList(); private final FileEntry rootEntry; private final FileFilter fileFilter; private final Comparator comparator; /** * Construct an observer for the specified directory. * * @param directoryName the name of the directory to observe */ public FileAlterationObserver(String directoryName) { this(new File(directoryName)); } /** * Construct an observer for the specified directory and file filter. * * @param directoryName the name of the directory to observe * @param fileFilter The file filter or null if none */ public FileAlterationObserver(String directoryName, FileFilter fileFilter) { this(new File(directoryName), fileFilter); } /** * Construct an observer for the specified directory, file filter and * file comparator. * * @param directoryName the name of the directory to observe * @param fileFilter The file filter or null if none * @param caseSensitivity what case sensitivity to use comparing file names, null means system sensitive */ public FileAlterationObserver(String directoryName, FileFilter fileFilter, IOCase caseSensitivity) { this(new File(directoryName), fileFilter, caseSensitivity); } /** * Construct an observer for the specified directory. * * @param directory the directory to observe */ public FileAlterationObserver(File directory) { this(directory, (FileFilter)null); } /** * Construct an observer for the specified directory and file filter. * * @param directory the directory to observe * @param fileFilter The file filter or null if none */ public FileAlterationObserver(File directory, FileFilter fileFilter) { this(directory, fileFilter, (IOCase)null); } /** * Construct an observer for the specified directory, file filter and * file comparator. * * @param directory the directory to observe * @param fileFilter The file filter or null if none * @param caseSensitivity what case sensitivity to use comparing file names, null means system sensitive */ public FileAlterationObserver(File directory, FileFilter fileFilter, IOCase caseSensitivity) { this(new FileEntry(directory), fileFilter, caseSensitivity); } /** * Construct an observer for the specified directory, file filter and * file comparator. * * @param rootEntry the root directory to observe * @param fileFilter The file filter or null if none * @param caseSensitivity what case sensitivity to use comparing file names, null means system sensitive */ protected FileAlterationObserver(FileEntry rootEntry, FileFilter fileFilter, IOCase caseSensitivity) { if (rootEntry == null) { throw new IllegalArgumentException("Root entry is missing"); } if (rootEntry.getFile() == null) { throw new IllegalArgumentException("Root directory is missing"); } this.rootEntry = rootEntry; this.fileFilter = fileFilter; if (caseSensitivity == null || caseSensitivity.equals(IOCase.SYSTEM)) { this.comparator = NameFileComparator.NAME_SYSTEM_COMPARATOR; } else if (caseSensitivity.equals(IOCase.INSENSITIVE)) { this.comparator = NameFileComparator.NAME_INSENSITIVE_COMPARATOR; } else { this.comparator = NameFileComparator.NAME_COMPARATOR; } } /** * Return the directory being observed. * * @return the directory being observed */ public File getDirectory() { return rootEntry.getFile(); } /** * Return the fileFilter. * * @return the fileFilter * @since 2.1 */ public FileFilter getFileFilter() { return fileFilter; } /** * Add a file system listener. * * @param listener The file system listener */ public void addListener(final FileAlterationListener listener) { if (listener != null) { listeners.add(listener); } } /** * Remove a file system listener. * * @param listener The file system listener */ public void removeListener(final FileAlterationListener listener) { if (listener != null) { while (listeners.remove(listener)) { } } } /** * Returns the set of registered file system listeners. * * @return The file system listeners */ public Iterable getListeners() { return listeners; } /** * Initialize the observer. * * @throws Exception if an error occurs */ public void initialize() throws Exception { rootEntry.refresh(rootEntry.getFile()); File[] files = listFiles(rootEntry.getFile()); FileEntry[] children = files.length > 0 ? new FileEntry[files.length] : FileEntry.EMPTY_ENTRIES; for (int i = 0; i < files.length; i++) { children[i] = createFileEntry(rootEntry, files[i]); } rootEntry.setChildren(children); } /** * Final processing. * * @throws Exception if an error occurs */ public void destroy() throws Exception { } /** * Check whether the file and its chlidren have been created, modified or deleted. */ public void checkAndNotify() { /* fire onStart() */ for (FileAlterationListener listener : listeners) { listener.onStart(this); } /* fire directory/file events */ File rootFile = rootEntry.getFile(); if (rootFile.exists()) { checkAndNotify(rootEntry, rootEntry.getChildren(), listFiles(rootFile)); } else if (rootEntry.isExists()) { checkAndNotify(rootEntry, rootEntry.getChildren(), FileUtils.EMPTY_FILE_ARRAY); } else { // Didn't exist and still doesn't } /* fire onStop() */ for (FileAlterationListener listener : listeners) { listener.onStop(this); } } /** * Compare two file lists for files which have been created, modified or deleted. * * @param parent The parent entry * @param previous The original list of files * @param files The current list of files */ private void checkAndNotify(FileEntry parent, FileEntry[] previous, File[] files) { int c = 0; FileEntry[] current = files.length > 0 ? new FileEntry[files.length] : FileEntry.EMPTY_ENTRIES; for (FileEntry entry : previous) { while (c < files.length && comparator.compare(entry.getFile(), files[c]) > 0) { current[c] = createFileEntry(parent, files[c]); doCreate(current[c]); c++; } if (c < files.length && comparator.compare(entry.getFile(), files[c]) == 0) { doMatch(entry, files[c]); checkAndNotify(entry, entry.getChildren(), listFiles(files[c])); current[c] = entry; c++; } else { checkAndNotify(entry, entry.getChildren(), FileUtils.EMPTY_FILE_ARRAY); doDelete(entry); } } for (; c < files.length; c++) { current[c] = createFileEntry(parent, files[c]); doCreate(current[c]); } parent.setChildren(current); } /** * Create a new file entry for the specified file. * * @param parent The parent file entry * @param file The file to create an entry for * @return A new file entry */ private FileEntry createFileEntry(FileEntry parent, File file) { FileEntry entry = parent.newChildInstance(file); entry.refresh(file); File[] files = listFiles(file); FileEntry[] children = files.length > 0 ? new FileEntry[files.length] : FileEntry.EMPTY_ENTRIES; for (int i = 0; i < files.length; i++) { children[i] = createFileEntry(entry, files[i]); } entry.setChildren(children); return entry; } /** * Fire directory/file created events to the registered listeners. * * @param entry The file entry */ private void doCreate(FileEntry entry) { for (FileAlterationListener listener : listeners) { if (entry.isDirectory()) { listener.onDirectoryCreate(entry.getFile()); } else { listener.onFileCreate(entry.getFile()); } } FileEntry[] children = entry.getChildren(); for (FileEntry aChildren : children) { doCreate(aChildren); } } /** * Fire directory/file change events to the registered listeners. * * @param entry The previous file system entry * @param file The current file */ private void doMatch(FileEntry entry, File file) { if (entry.refresh(file)) { for (FileAlterationListener listener : listeners) { if (entry.isDirectory()) { listener.onDirectoryChange(file); } else { listener.onFileChange(file); } } } } /** * Fire directory/file delete events to the registered listeners. * * @param entry The file entry */ private void doDelete(FileEntry entry) { for (FileAlterationListener listener : listeners) { if (entry.isDirectory()) { listener.onDirectoryDelete(entry.getFile()); } else { listener.onFileDelete(entry.getFile()); } } } /** * List the contents of a directory * * @param file The file to list the contents of * @return the directory contents or a zero length array if * the empty or the file is not a directory */ private File[] listFiles(File file) { File[] children = null; if (file.isDirectory()) { children = fileFilter == null ? file.listFiles() : file.listFiles(fileFilter); } if (children == null) { children = FileUtils.EMPTY_FILE_ARRAY; } if (comparator != null && children.length > 1) { Arrays.sort(children, comparator); } return children; } /** * Provide a String representation of this observer. * * @return a String representation of this observer */ @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append(getClass().getSimpleName()); builder.append("[file='"); builder.append(getDirectory().getPath()); builder.append('\''); if (fileFilter != null) { builder.append(", "); builder.append(fileFilter.toString()); } builder.append(", listeners="); builder.append(listeners.size()); builder.append("]"); return builder.toString(); } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/monitor/FileAlterationMonitor.java0000644000175000017500000001324312125050425032665 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.monitor; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ThreadFactory; /** * A runnable that spawns a monitoring thread triggering any * registered {@link FileAlterationObserver} at a specified interval. * * @see FileAlterationObserver * @version $Id: FileAlterationMonitor.java 1304052 2012-03-22 20:55:29Z ggregory $ * @since 2.0 */ public final class FileAlterationMonitor implements Runnable { private final long interval; private final List observers = new CopyOnWriteArrayList(); private Thread thread = null; private ThreadFactory threadFactory; private volatile boolean running = false; /** * Construct a monitor with a default interval of 10 seconds. */ public FileAlterationMonitor() { this(10000); } /** * Construct a monitor with the specified interval. * * @param interval The amount of time in miliseconds to wait between * checks of the file system */ public FileAlterationMonitor(long interval) { this.interval = interval; } /** * Construct a monitor with the specified interval and set of observers. * * @param interval The amount of time in miliseconds to wait between * checks of the file system * @param observers The set of observers to add to the monitor. */ public FileAlterationMonitor(long interval, FileAlterationObserver... observers) { this(interval); if (observers != null) { for (FileAlterationObserver observer : observers) { addObserver(observer); } } } /** * Return the interval. * * @return the interval */ public long getInterval() { return interval; } /** * Set the thread factory. * * @param threadFactory the thread factory */ public synchronized void setThreadFactory(ThreadFactory threadFactory) { this.threadFactory = threadFactory; } /** * Add a file system observer to this monitor. * * @param observer The file system observer to add */ public void addObserver(final FileAlterationObserver observer) { if (observer != null) { observers.add(observer); } } /** * Remove a file system observer from this monitor. * * @param observer The file system observer to remove */ public void removeObserver(final FileAlterationObserver observer) { if (observer != null) { while (observers.remove(observer)) { } } } /** * Returns the set of {@link FileAlterationObserver} registered with * this monitor. * * @return The set of {@link FileAlterationObserver} */ public Iterable getObservers() { return observers; } /** * Start monitoring. * * @throws Exception if an error occurs initializing the observer */ public synchronized void start() throws Exception { if (running) { throw new IllegalStateException("Monitor is already running"); } for (FileAlterationObserver observer : observers) { observer.initialize(); } running = true; if (threadFactory != null) { thread = threadFactory.newThread(this); } else { thread = new Thread(this); } thread.start(); } /** * Stop monitoring. * * @throws Exception if an error occurs initializing the observer */ public synchronized void stop() throws Exception { stop(interval); } /** * Stop monitoring. * * @param stopInterval the amount of time in milliseconds to wait for the thread to finish. * A value of zero will wait until the thread is finished (see {@link Thread#join(long)}). * @throws Exception if an error occurs initializing the observer * @since 2.1 */ public synchronized void stop(long stopInterval) throws Exception { if (running == false) { throw new IllegalStateException("Monitor is not running"); } running = false; try { thread.join(stopInterval); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } for (FileAlterationObserver observer : observers) { observer.destroy(); } } /** * Run. */ public void run() { while (running) { for (FileAlterationObserver observer : observers) { observer.checkAndNotify(); } if (!running) { break; } try { Thread.sleep(interval); } catch (final InterruptedException ignored) { } } } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/monitor/FileAlterationListener.java0000644000175000017500000000455212125050425033026 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.monitor; import java.io.File; /** * A listener that receives events of file system modifications. *

* Register {@link FileAlterationListener}s with a {@link FileAlterationObserver}. * * @see FileAlterationObserver * @version $Id: FileAlterationListener.java 1304052 2012-03-22 20:55:29Z ggregory $ * @since 2.0 */ public interface FileAlterationListener { /** * File system observer started checking event. * * @param observer The file system observer */ void onStart(final FileAlterationObserver observer); /** * Directory created Event. * * @param directory The directory created */ void onDirectoryCreate(final File directory); /** * Directory changed Event. * * @param directory The directory changed */ void onDirectoryChange(final File directory); /** * Directory deleted Event. * * @param directory The directory deleted */ void onDirectoryDelete(final File directory); /** * File created Event. * * @param file The file created */ void onFileCreate(final File file); /** * File changed Event. * * @param file The file changed */ void onFileChange(final File file); /** * File deleted Event. * * @param file The file deleted */ void onFileDelete(final File file); /** * File system observer finished checking event. * * @param observer The file system observer */ void onStop(final FileAlterationObserver observer); } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/monitor/FileAlterationListenerAdaptor.javalibcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/monitor/FileAlterationListenerAdapto0000644000175000017500000000501112125050425033226 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.monitor; import java.io.File; /** * Convenience {@link FileAlterationListener} implementation that does nothing. * * @see FileAlterationObserver * @version $Id: FileAlterationListenerAdaptor.java 1304062 2012-03-22 21:10:46Z sebb $ * @since 2.0 */ public class FileAlterationListenerAdaptor implements FileAlterationListener { /** * File system observer started checking event. * * @param observer The file system observer (ignored) */ public void onStart(final FileAlterationObserver observer) { } /** * Directory created Event. * * @param directory The directory created (ignored) */ public void onDirectoryCreate(final File directory) { } /** * Directory changed Event. * * @param directory The directory changed (ignored) */ public void onDirectoryChange(final File directory) { } /** * Directory deleted Event. * * @param directory The directory deleted (ignored) */ public void onDirectoryDelete(final File directory) { } /** * File created Event. * * @param file The file created (ignored) */ public void onFileCreate(final File file) { } /** * File changed Event. * * @param file The file changed (ignored) */ public void onFileChange(final File file) { } /** * File deleted Event. * * @param file The file deleted (ignored) */ public void onFileDelete(final File file) { } /** * File system observer finished checking event. * * @param observer The file system observer (ignored) */ public void onStop(final FileAlterationObserver observer) { } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/monitor/FileEntry.java0000644000175000017500000001655412125050425030324 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.monitor; import java.io.File; import java.io.Serializable; /** * {@link FileEntry} represents the state of a file or directory, capturing * the following {@link File} attributes at a point in time. *

    *
  • File Name (see {@link File#getName()})
  • *
  • Exists - whether the file exists or not (see {@link File#exists()})
  • *
  • Directory - whether the file is a directory or not (see {@link File#isDirectory()})
  • *
  • Last Modified Date/Time (see {@link File#lastModified()})
  • *
  • Length (see {@link File#length()}) - directories treated as zero
  • *
  • Children - contents of a directory (see {@link File#listFiles(java.io.FileFilter)})
  • *
*

*

Custom Implementations

* If the state of additional {@link File} attributes is required then create a custom * {@link FileEntry} with properties for those attributes. Override the * {@link #newChildInstance(File)} to return a new instance of the appropriate type. * You may also want to override the {@link #refresh(File)} method. * @see FileAlterationObserver * @since 2.0 */ public class FileEntry implements Serializable { static final FileEntry[] EMPTY_ENTRIES = new FileEntry[0]; private final FileEntry parent; private FileEntry[] children; private final File file; private String name; private boolean exists; private boolean directory; private long lastModified; private long length; /** * Construct a new monitor for a specified {@link File}. * * @param file The file being monitored */ public FileEntry(File file) { this((FileEntry)null, file); } /** * Construct a new monitor for a specified {@link File}. * * @param parent The parent * @param file The file being monitored */ public FileEntry(FileEntry parent, File file) { if (file == null) { throw new IllegalArgumentException("File is missing"); } this.file = file; this.parent = parent; this.name = file.getName(); } /** * Refresh the attributes from the {@link File}, indicating * whether the file has changed. *

* This implementation refreshes the name, exists, * directory, lastModified and length * properties. *

* The exists, directory, lastModified * and length properties are compared for changes * * @param file the file instance to compare to * @return {@code true} if the file has changed, otherwise {@code false} */ public boolean refresh(File file) { // cache original values boolean origExists = exists; long origLastModified = lastModified; boolean origDirectory = directory; long origLength = length; // refresh the values name = file.getName(); exists = file.exists(); directory = exists ? file.isDirectory() : false; lastModified = exists ? file.lastModified() : 0; length = exists && !directory ? file.length() : 0; // Return if there are changes return exists != origExists || lastModified != origLastModified || directory != origDirectory || length != origLength; } /** * Create a new child instance. *

* Custom implementations should override this method to return * a new instance of the appropriate type. * * @param file The child file * @return a new child instance */ public FileEntry newChildInstance(File file) { return new FileEntry(this, file); } /** * Return the parent entry. * * @return the parent entry */ public FileEntry getParent() { return parent; } /** * Return the level * * @return the level */ public int getLevel() { return parent == null ? 0 : parent.getLevel() + 1; } /** * Return the directory's files. * * @return This directory's files or an empty * array if the file is not a directory or the * directory is empty */ public FileEntry[] getChildren() { return children != null ? children : EMPTY_ENTRIES; } /** * Set the directory's files. * * @param children This directory's files, may be null */ public void setChildren(FileEntry[] children) { this.children = children; } /** * Return the file being monitored. * * @return the file being monitored */ public File getFile() { return file; } /** * Return the file name. * * @return the file name */ public String getName() { return name; } /** * Set the file name. * * @param name the file name */ public void setName(String name) { this.name = name; } /** * Return the last modified time from the last time it * was checked. * * @return the last modified time */ public long getLastModified() { return lastModified; } /** * Return the last modified time from the last time it * was checked. * * @param lastModified The last modified time */ public void setLastModified(long lastModified) { this.lastModified = lastModified; } /** * Return the length. * * @return the length */ public long getLength() { return length; } /** * Set the length. * * @param length the length */ public void setLength(long length) { this.length = length; } /** * Indicate whether the file existed the last time it * was checked. * * @return whether the file existed */ public boolean isExists() { return exists; } /** * Set whether the file existed the last time it * was checked. * * @param exists whether the file exists or not */ public void setExists(boolean exists) { this.exists = exists; } /** * Indicate whether the file is a directory or not. * * @return whether the file is a directory or not */ public boolean isDirectory() { return directory; } /** * Set whether the file is a directory or not. * * @param directory whether the file is a directory or not */ public void setDirectory(boolean directory) { this.directory = directory; } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/monitor/package.html0000644000175000017500000000173712125050425030036 0ustar ebourgebourg

This package provides a component for monitoring file system events (directory and file create, update and delete events).

libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/EndianUtils.java0000644000175000017500000004260012125050425027142 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * Utility code for dealing with different endian systems. *

* Different computer architectures adopt different conventions for * byte ordering. In so-called "Little Endian" architectures (eg Intel), * the low-order byte is stored in memory at the lowest address, and * subsequent bytes at higher addresses. For "Big Endian" architectures * (eg Motorola), the situation is reversed. * This class helps you solve this incompatability. *

* Origin of code: Excalibur * * @version $Id: EndianUtils.java 1302056 2012-03-18 03:03:38Z ggregory $ * @see org.apache.commons.io.input.SwappedDataInputStream */ public class EndianUtils { /** * Instances should NOT be constructed in standard programming. */ public EndianUtils() { super(); } // ========================================== Swapping routines /** * Converts a "short" value between endian systems. * @param value value to convert * @return the converted value */ public static short swapShort(short value) { return (short) ( ( ( ( value >> 0 ) & 0xff ) << 8 ) + ( ( ( value >> 8 ) & 0xff ) << 0 ) ); } /** * Converts a "int" value between endian systems. * @param value value to convert * @return the converted value */ public static int swapInteger(int value) { return ( ( ( value >> 0 ) & 0xff ) << 24 ) + ( ( ( value >> 8 ) & 0xff ) << 16 ) + ( ( ( value >> 16 ) & 0xff ) << 8 ) + ( ( ( value >> 24 ) & 0xff ) << 0 ); } /** * Converts a "long" value between endian systems. * @param value value to convert * @return the converted value */ public static long swapLong(long value) { return ( ( ( value >> 0 ) & 0xff ) << 56 ) + ( ( ( value >> 8 ) & 0xff ) << 48 ) + ( ( ( value >> 16 ) & 0xff ) << 40 ) + ( ( ( value >> 24 ) & 0xff ) << 32 ) + ( ( ( value >> 32 ) & 0xff ) << 24 ) + ( ( ( value >> 40 ) & 0xff ) << 16 ) + ( ( ( value >> 48 ) & 0xff ) << 8 ) + ( ( ( value >> 56 ) & 0xff ) << 0 ); } /** * Converts a "float" value between endian systems. * @param value value to convert * @return the converted value */ public static float swapFloat(float value) { return Float.intBitsToFloat( swapInteger( Float.floatToIntBits( value ) ) ); } /** * Converts a "double" value between endian systems. * @param value value to convert * @return the converted value */ public static double swapDouble(double value) { return Double.longBitsToDouble( swapLong( Double.doubleToLongBits( value ) ) ); } // ========================================== Swapping read/write routines /** * Writes a "short" value to a byte array at a given offset. The value is * converted to the opposed endian system while writing. * @param data target byte array * @param offset starting offset in the byte array * @param value value to write */ public static void writeSwappedShort(byte[] data, int offset, short value) { data[ offset + 0 ] = (byte)( ( value >> 0 ) & 0xff ); data[ offset + 1 ] = (byte)( ( value >> 8 ) & 0xff ); } /** * Reads a "short" value from a byte array at a given offset. The value is * converted to the opposed endian system while reading. * @param data source byte array * @param offset starting offset in the byte array * @return the value read */ public static short readSwappedShort(byte[] data, int offset) { return (short)( ( ( data[ offset + 0 ] & 0xff ) << 0 ) + ( ( data[ offset + 1 ] & 0xff ) << 8 ) ); } /** * Reads an unsigned short (16-bit) value from a byte array at a given * offset. The value is converted to the opposed endian system while * reading. * @param data source byte array * @param offset starting offset in the byte array * @return the value read */ public static int readSwappedUnsignedShort(byte[] data, int offset) { return ( ( ( data[ offset + 0 ] & 0xff ) << 0 ) + ( ( data[ offset + 1 ] & 0xff ) << 8 ) ); } /** * Writes a "int" value to a byte array at a given offset. The value is * converted to the opposed endian system while writing. * @param data target byte array * @param offset starting offset in the byte array * @param value value to write */ public static void writeSwappedInteger(byte[] data, int offset, int value) { data[ offset + 0 ] = (byte)( ( value >> 0 ) & 0xff ); data[ offset + 1 ] = (byte)( ( value >> 8 ) & 0xff ); data[ offset + 2 ] = (byte)( ( value >> 16 ) & 0xff ); data[ offset + 3 ] = (byte)( ( value >> 24 ) & 0xff ); } /** * Reads a "int" value from a byte array at a given offset. The value is * converted to the opposed endian system while reading. * @param data source byte array * @param offset starting offset in the byte array * @return the value read */ public static int readSwappedInteger(byte[] data, int offset) { return ( ( ( data[ offset + 0 ] & 0xff ) << 0 ) + ( ( data[ offset + 1 ] & 0xff ) << 8 ) + ( ( data[ offset + 2 ] & 0xff ) << 16 ) + ( ( data[ offset + 3 ] & 0xff ) << 24 ) ); } /** * Reads an unsigned integer (32-bit) value from a byte array at a given * offset. The value is converted to the opposed endian system while * reading. * @param data source byte array * @param offset starting offset in the byte array * @return the value read */ public static long readSwappedUnsignedInteger(byte[] data, int offset) { long low = ( ( ( data[ offset + 0 ] & 0xff ) << 0 ) + ( ( data[ offset + 1 ] & 0xff ) << 8 ) + ( ( data[ offset + 2 ] & 0xff ) << 16 ) ); long high = data[ offset + 3 ] & 0xff; return (high << 24) + (0xffffffffL & low); } /** * Writes a "long" value to a byte array at a given offset. The value is * converted to the opposed endian system while writing. * @param data target byte array * @param offset starting offset in the byte array * @param value value to write */ public static void writeSwappedLong(byte[] data, int offset, long value) { data[ offset + 0 ] = (byte)( ( value >> 0 ) & 0xff ); data[ offset + 1 ] = (byte)( ( value >> 8 ) & 0xff ); data[ offset + 2 ] = (byte)( ( value >> 16 ) & 0xff ); data[ offset + 3 ] = (byte)( ( value >> 24 ) & 0xff ); data[ offset + 4 ] = (byte)( ( value >> 32 ) & 0xff ); data[ offset + 5 ] = (byte)( ( value >> 40 ) & 0xff ); data[ offset + 6 ] = (byte)( ( value >> 48 ) & 0xff ); data[ offset + 7 ] = (byte)( ( value >> 56 ) & 0xff ); } /** * Reads a "long" value from a byte array at a given offset. The value is * converted to the opposed endian system while reading. * @param data source byte array * @param offset starting offset in the byte array * @return the value read */ public static long readSwappedLong(byte[] data, int offset) { long low = ( ( data[ offset + 0 ] & 0xff ) << 0 ) + ( ( data[ offset + 1 ] & 0xff ) << 8 ) + ( ( data[ offset + 2 ] & 0xff ) << 16 ) + ( ( data[ offset + 3 ] & 0xff ) << 24 ); long high = ( ( data[ offset + 4 ] & 0xff ) << 0 ) + ( ( data[ offset + 5 ] & 0xff ) << 8 ) + ( ( data[ offset + 6 ] & 0xff ) << 16 ) + ( ( data[ offset + 7 ] & 0xff ) << 24 ); return (high << 32) + (0xffffffffL & low); } /** * Writes a "float" value to a byte array at a given offset. The value is * converted to the opposed endian system while writing. * @param data target byte array * @param offset starting offset in the byte array * @param value value to write */ public static void writeSwappedFloat(byte[] data, int offset, float value) { writeSwappedInteger( data, offset, Float.floatToIntBits( value ) ); } /** * Reads a "float" value from a byte array at a given offset. The value is * converted to the opposed endian system while reading. * @param data source byte array * @param offset starting offset in the byte array * @return the value read */ public static float readSwappedFloat(byte[] data, int offset) { return Float.intBitsToFloat( readSwappedInteger( data, offset ) ); } /** * Writes a "double" value to a byte array at a given offset. The value is * converted to the opposed endian system while writing. * @param data target byte array * @param offset starting offset in the byte array * @param value value to write */ public static void writeSwappedDouble(byte[] data, int offset, double value) { writeSwappedLong( data, offset, Double.doubleToLongBits( value ) ); } /** * Reads a "double" value from a byte array at a given offset. The value is * converted to the opposed endian system while reading. * @param data source byte array * @param offset starting offset in the byte array * @return the value read */ public static double readSwappedDouble(byte[] data, int offset) { return Double.longBitsToDouble( readSwappedLong( data, offset ) ); } /** * Writes a "short" value to an OutputStream. The value is * converted to the opposed endian system while writing. * @param output target OutputStream * @param value value to write * @throws IOException in case of an I/O problem */ public static void writeSwappedShort(OutputStream output, short value) throws IOException { output.write( (byte)( ( value >> 0 ) & 0xff ) ); output.write( (byte)( ( value >> 8 ) & 0xff ) ); } /** * Reads a "short" value from an InputStream. The value is * converted to the opposed endian system while reading. * @param input source InputStream * @return the value just read * @throws IOException in case of an I/O problem */ public static short readSwappedShort(InputStream input) throws IOException { return (short)( ( ( read( input ) & 0xff ) << 0 ) + ( ( read( input ) & 0xff ) << 8 ) ); } /** * Reads a unsigned short (16-bit) from an InputStream. The value is * converted to the opposed endian system while reading. * @param input source InputStream * @return the value just read * @throws IOException in case of an I/O problem */ public static int readSwappedUnsignedShort(InputStream input) throws IOException { int value1 = read( input ); int value2 = read( input ); return ( ( ( value1 & 0xff ) << 0 ) + ( ( value2 & 0xff ) << 8 ) ); } /** * Writes a "int" value to an OutputStream. The value is * converted to the opposed endian system while writing. * @param output target OutputStream * @param value value to write * @throws IOException in case of an I/O problem */ public static void writeSwappedInteger(OutputStream output, int value) throws IOException { output.write( (byte)( ( value >> 0 ) & 0xff ) ); output.write( (byte)( ( value >> 8 ) & 0xff ) ); output.write( (byte)( ( value >> 16 ) & 0xff ) ); output.write( (byte)( ( value >> 24 ) & 0xff ) ); } /** * Reads a "int" value from an InputStream. The value is * converted to the opposed endian system while reading. * @param input source InputStream * @return the value just read * @throws IOException in case of an I/O problem */ public static int readSwappedInteger(InputStream input) throws IOException { int value1 = read( input ); int value2 = read( input ); int value3 = read( input ); int value4 = read( input ); return ( ( value1 & 0xff ) << 0 ) + ( ( value2 & 0xff ) << 8 ) + ( ( value3 & 0xff ) << 16 ) + ( ( value4 & 0xff ) << 24 ); } /** * Reads a unsigned integer (32-bit) from an InputStream. The value is * converted to the opposed endian system while reading. * @param input source InputStream * @return the value just read * @throws IOException in case of an I/O problem */ public static long readSwappedUnsignedInteger(InputStream input) throws IOException { int value1 = read( input ); int value2 = read( input ); int value3 = read( input ); int value4 = read( input ); long low = ( ( ( value1 & 0xff ) << 0 ) + ( ( value2 & 0xff ) << 8 ) + ( ( value3 & 0xff ) << 16 ) ); long high = value4 & 0xff; return (high << 24) + (0xffffffffL & low); } /** * Writes a "long" value to an OutputStream. The value is * converted to the opposed endian system while writing. * @param output target OutputStream * @param value value to write * @throws IOException in case of an I/O problem */ public static void writeSwappedLong(OutputStream output, long value) throws IOException { output.write( (byte)( ( value >> 0 ) & 0xff ) ); output.write( (byte)( ( value >> 8 ) & 0xff ) ); output.write( (byte)( ( value >> 16 ) & 0xff ) ); output.write( (byte)( ( value >> 24 ) & 0xff ) ); output.write( (byte)( ( value >> 32 ) & 0xff ) ); output.write( (byte)( ( value >> 40 ) & 0xff ) ); output.write( (byte)( ( value >> 48 ) & 0xff ) ); output.write( (byte)( ( value >> 56 ) & 0xff ) ); } /** * Reads a "long" value from an InputStream. The value is * converted to the opposed endian system while reading. * @param input source InputStream * @return the value just read * @throws IOException in case of an I/O problem */ public static long readSwappedLong(InputStream input) throws IOException { byte[] bytes = new byte[8]; for ( int i=0; i<8; i++ ) { bytes[i] = (byte) read( input ); } return readSwappedLong( bytes, 0 ); } /** * Writes a "float" value to an OutputStream. The value is * converted to the opposed endian system while writing. * @param output target OutputStream * @param value value to write * @throws IOException in case of an I/O problem */ public static void writeSwappedFloat(OutputStream output, float value) throws IOException { writeSwappedInteger( output, Float.floatToIntBits( value ) ); } /** * Reads a "float" value from an InputStream. The value is * converted to the opposed endian system while reading. * @param input source InputStream * @return the value just read * @throws IOException in case of an I/O problem */ public static float readSwappedFloat(InputStream input) throws IOException { return Float.intBitsToFloat( readSwappedInteger( input ) ); } /** * Writes a "double" value to an OutputStream. The value is * converted to the opposed endian system while writing. * @param output target OutputStream * @param value value to write * @throws IOException in case of an I/O problem */ public static void writeSwappedDouble(OutputStream output, double value) throws IOException { writeSwappedLong( output, Double.doubleToLongBits( value ) ); } /** * Reads a "double" value from an InputStream. The value is * converted to the opposed endian system while reading. * @param input source InputStream * @return the value just read * @throws IOException in case of an I/O problem */ public static double readSwappedDouble(InputStream input) throws IOException { return Double.longBitsToDouble( readSwappedLong( input ) ); } /** * Reads the next byte from the input stream. * @param input the stream * @return the byte * @throws IOException if the end of file is reached */ private static int read(InputStream input) throws IOException { int value = input.read(); if( -1 == value ) { throw new EOFException( "Unexpected EOF reached" ); } return value; } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/LineIterator.java0000644000175000017500000001350212125050425027323 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.util.Iterator; import java.util.NoSuchElementException; /** * An Iterator over the lines in a Reader. *

* LineIterator holds a reference to an open Reader. * When you have finished with the iterator you should close the reader * to free internal resources. This can be done by closing the reader directly, * or by calling the {@link #close()} or {@link #closeQuietly(LineIterator)} * method on the iterator. *

* The recommended usage pattern is: *

 * LineIterator it = FileUtils.lineIterator(file, "UTF-8");
 * try {
 *   while (it.hasNext()) {
 *     String line = it.nextLine();
 *     // do something with line
 *   }
 * } finally {
 *   it.close();
 * }
 * 
* * @version $Id: LineIterator.java 1307461 2012-03-30 15:12:29Z ggregory $ * @since 1.2 */ public class LineIterator implements Iterator { // N.B. This class deliberately does not implement Iterable, see https://issues.apache.org/jira/browse/IO-181 /** The reader that is being read. */ private final BufferedReader bufferedReader; /** The current line. */ private String cachedLine; /** A flag indicating if the iterator has been fully read. */ private boolean finished = false; /** * Constructs an iterator of the lines for a Reader. * * @param reader the Reader to read from, not null * @throws IllegalArgumentException if the reader is null */ public LineIterator(final Reader reader) throws IllegalArgumentException { if (reader == null) { throw new IllegalArgumentException("Reader must not be null"); } if (reader instanceof BufferedReader) { bufferedReader = (BufferedReader) reader; } else { bufferedReader = new BufferedReader(reader); } } //----------------------------------------------------------------------- /** * Indicates whether the Reader has more lines. * If there is an IOException then {@link #close()} will * be called on this instance. * * @return {@code true} if the Reader has more lines * @throws IllegalStateException if an IO exception occurs */ public boolean hasNext() { if (cachedLine != null) { return true; } else if (finished) { return false; } else { try { while (true) { String line = bufferedReader.readLine(); if (line == null) { finished = true; return false; } else if (isValidLine(line)) { cachedLine = line; return true; } } } catch(IOException ioe) { close(); throw new IllegalStateException(ioe); } } } /** * Overridable method to validate each line that is returned. * This implementation always returns true. * @param line the line that is to be validated * @return true if valid, false to remove from the iterator */ protected boolean isValidLine(String line) { return true; } /** * Returns the next line in the wrapped Reader. * * @return the next line from the input * @throws NoSuchElementException if there is no line to return */ public String next() { return nextLine(); } /** * Returns the next line in the wrapped Reader. * * @return the next line from the input * @throws NoSuchElementException if there is no line to return */ public String nextLine() { if (!hasNext()) { throw new NoSuchElementException("No more lines"); } String currentLine = cachedLine; cachedLine = null; return currentLine; } /** * Closes the underlying Reader quietly. * This method is useful if you only want to process the first few * lines of a larger file. If you do not close the iterator * then the Reader remains open. * This method can safely be called multiple times. */ public void close() { finished = true; IOUtils.closeQuietly(bufferedReader); cachedLine = null; } /** * Unsupported. * * @throws UnsupportedOperationException always */ public void remove() { throw new UnsupportedOperationException("Remove unsupported on LineIterator"); } //----------------------------------------------------------------------- /** * Closes the iterator, handling null and ignoring exceptions. * * @param iterator the iterator to close */ public static void closeQuietly(LineIterator iterator) { if (iterator != null) { iterator.close(); } } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/DirectoryWalker.java0000644000175000017500000006202112125050425030034 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.util.Collection; import org.apache.commons.io.filefilter.FileFilterUtils; import org.apache.commons.io.filefilter.IOFileFilter; import org.apache.commons.io.filefilter.TrueFileFilter; /** * Abstract class that walks through a directory hierarchy and provides * subclasses with convenient hooks to add specific behaviour. *

* This class operates with a {@link FileFilter} and maximum depth to * limit the files and direcories visited. * Commons IO supplies many common filter implementations in the * filefilter package. *

* The following sections describe: *

* * *

1. Example Implementation

* * There are many possible extensions, for example, to delete all * files and '.svn' directories, and return a list of deleted files: *
 *  public class FileCleaner extends DirectoryWalker {
 *
 *    public FileCleaner() {
 *      super();
 *    }
 *
 *    public List clean(File startDirectory) {
 *      List results = new ArrayList();
 *      walk(startDirectory, results);
 *      return results;
 *    }
 *
 *    protected boolean handleDirectory(File directory, int depth, Collection results) {
 *      // delete svn directories and then skip
 *      if (".svn".equals(directory.getName())) {
 *        directory.delete();
 *        return false;
 *      } else {
 *        return true;
 *      }
 *
 *    }
 *
 *    protected void handleFile(File file, int depth, Collection results) {
 *      // delete file and add to list of deleted
 *      file.delete();
 *      results.add(file);
 *    }
 *  }
 * 
* * *

2. Filter Example

* * Choosing which directories and files to process can be a key aspect * of using this class. This information can be setup in three ways, * via three different constructors. *

* The first option is to visit all directories and files. * This is achieved via the no-args constructor. *

* The second constructor option is to supply a single {@link FileFilter} * that describes the files and directories to visit. Care must be taken * with this option as the same filter is used for both directories * and files. *

* For example, if you wanted all directories which are not hidden * and files which end in ".txt": *

 *  public class FooDirectoryWalker extends DirectoryWalker {
 *    public FooDirectoryWalker(FileFilter filter) {
 *      super(filter, -1);
 *    }
 *  }
 *  
 *  // Build up the filters and create the walker
 *    // Create a filter for Non-hidden directories
 *    IOFileFilter fooDirFilter = 
 *        FileFilterUtils.andFileFilter(FileFilterUtils.directoryFileFilter,
 *                                      HiddenFileFilter.VISIBLE);
 *
 *    // Create a filter for Files ending in ".txt"
 *    IOFileFilter fooFileFilter = 
 *        FileFilterUtils.andFileFilter(FileFilterUtils.fileFileFilter,
 *                                      FileFilterUtils.suffixFileFilter(".txt"));
 *
 *    // Combine the directory and file filters using an OR condition
 *    java.io.FileFilter fooFilter = 
 *        FileFilterUtils.orFileFilter(fooDirFilter, fooFileFilter);
 *
 *    // Use the filter to construct a DirectoryWalker implementation
 *    FooDirectoryWalker walker = new FooDirectoryWalker(fooFilter);
 * 
*

* The third constructor option is to specify separate filters, one for * directories and one for files. These are combined internally to form * the correct FileFilter, something which is very easy to * get wrong when attempted manually, particularly when trying to * express constructs like 'any file in directories named docs'. *

* For example, if you wanted all directories which are not hidden * and files which end in ".txt": *

 *  public class FooDirectoryWalker extends DirectoryWalker {
 *    public FooDirectoryWalker(IOFileFilter dirFilter, IOFileFilter fileFilter) {
 *      super(dirFilter, fileFilter, -1);
 *    }
 *  }
 *  
 *  // Use the filters to construct the walker
 *  FooDirectoryWalker walker = new FooDirectoryWalker(
 *    HiddenFileFilter.VISIBLE,
 *    FileFilterUtils.suffixFileFilter(".txt"),
 *  );
 * 
* This is much simpler than the previous example, and is why it is the preferred * option for filtering. * * *

3. Cancellation

* * The DirectoryWalker contains some of the logic required for cancel processing. * Subclasses must complete the implementation. *

* What DirectoryWalker does provide for cancellation is: *

    *
  • {@link CancelException} which can be thrown in any of the * lifecycle methods to stop processing.
  • *
  • The walk() method traps thrown {@link CancelException} * and calls the handleCancelled() method, providing * a place for custom cancel processing.
  • *
*

* Implementations need to provide: *

    *
  • The decision logic on whether to cancel processing or not.
  • *
  • Constructing and throwing a {@link CancelException}.
  • *
  • Custom cancel processing in the handleCancelled() method. *
*

* Two possible scenarios are envisaged for cancellation: *

    *
  • 3.1 External / Mult-threaded - cancellation being * decided/initiated by an external process.
  • *
  • 3.2 Internal - cancellation being decided/initiated * from within a DirectoryWalker implementation.
  • *
*

* The following sections provide example implementations for these two different * scenarios. * * *

3.1 External / Multi-threaded

* * This example provides a public cancel() method that can be * called by another thread to stop the processing. A typical example use-case * would be a cancel button on a GUI. Calling this method sets a * * volatile flag to ensure it will work properly in a multi-threaded environment. * The flag is returned by the handleIsCancelled() method, which * will cause the walk to stop immediately. The handleCancelled() * method will be the next, and last, callback method received once cancellation * has occurred. * *
 *  public class FooDirectoryWalker extends DirectoryWalker {
 *
 *    private volatile boolean cancelled = false;
 *
 *    public void cancel() {
 *        cancelled = true;
 *    }
 *
 *    private void handleIsCancelled(File file, int depth, Collection results) {
 *        return cancelled;
 *    }
 *
 *    protected void handleCancelled(File startDirectory, Collection results, CancelException cancel) {
 *        // implement processing required when a cancellation occurs
 *    }
 *  }
 * 
* * *

3.2 Internal

* * This shows an example of how internal cancellation processing could be implemented. * Note the decision logic and throwing a {@link CancelException} could be implemented * in any of the lifecycle methods. * *
 *  public class BarDirectoryWalker extends DirectoryWalker {
 *
 *    protected boolean handleDirectory(File directory, int depth, Collection results) throws IOException {
 *        // cancel if hidden directory
 *        if (directory.isHidden()) {
 *            throw new CancelException(file, depth);
 *        }
 *        return true;
 *    }
 *
 *    protected void handleFile(File file, int depth, Collection results) throws IOException {
 *        // cancel if read-only file
 *        if (!file.canWrite()) {
 *            throw new CancelException(file, depth);
 *        }
 *        results.add(file);
 *    }
 *
 *    protected void handleCancelled(File startDirectory, Collection results, CancelException cancel) {
 *        // implement processing required when a cancellation occurs
 *    }
 *  }
 * 
* * @since 1.3 * @version $Id: DirectoryWalker.java 1307459 2012-03-30 15:11:44Z ggregory $ */ public abstract class DirectoryWalker { /** * The file filter to use to filter files and directories. */ private final FileFilter filter; /** * The limit on the directory depth to walk. */ private final int depthLimit; /** * Construct an instance with no filtering and unlimited depth. */ protected DirectoryWalker() { this(null, -1); } /** * Construct an instance with a filter and limit the depth navigated to. *

* The filter controls which files and directories will be navigated to as * part of the walk. The {@link FileFilterUtils} class is useful for combining * various filters together. A {@code null} filter means that no * filtering should occur and all files and directories will be visited. * * @param filter the filter to apply, null means visit all files * @param depthLimit controls how deep the hierarchy is * navigated to (less than 0 means unlimited) */ protected DirectoryWalker(FileFilter filter, int depthLimit) { this.filter = filter; this.depthLimit = depthLimit; } /** * Construct an instance with a directory and a file filter and an optional * limit on the depth navigated to. *

* The filters control which files and directories will be navigated to as part * of the walk. This constructor uses {@link FileFilterUtils#makeDirectoryOnly(IOFileFilter)} * and {@link FileFilterUtils#makeFileOnly(IOFileFilter)} internally to combine the filters. * A {@code null} filter means that no filtering should occur. * * @param directoryFilter the filter to apply to directories, null means visit all directories * @param fileFilter the filter to apply to files, null means visit all files * @param depthLimit controls how deep the hierarchy is * navigated to (less than 0 means unlimited) */ protected DirectoryWalker(IOFileFilter directoryFilter, IOFileFilter fileFilter, int depthLimit) { if (directoryFilter == null && fileFilter == null) { this.filter = null; } else { directoryFilter = directoryFilter != null ? directoryFilter : TrueFileFilter.TRUE; fileFilter = fileFilter != null ? fileFilter : TrueFileFilter.TRUE; directoryFilter = FileFilterUtils.makeDirectoryOnly(directoryFilter); fileFilter = FileFilterUtils.makeFileOnly(fileFilter); this.filter = FileFilterUtils.or(directoryFilter, fileFilter); } this.depthLimit = depthLimit; } //----------------------------------------------------------------------- /** * Internal method that walks the directory hierarchy in a depth-first manner. *

* Users of this class do not need to call this method. This method will * be called automatically by another (public) method on the specific subclass. *

* Writers of subclasses should call this method to start the directory walk. * Once called, this method will emit events as it walks the hierarchy. * The event methods have the prefix handle. * * @param startDirectory the directory to start from, not null * @param results the collection of result objects, may be updated * @throws NullPointerException if the start directory is null * @throws IOException if an I/O Error occurs */ protected final void walk(File startDirectory, Collection results) throws IOException { if (startDirectory == null) { throw new NullPointerException("Start Directory is null"); } try { handleStart(startDirectory, results); walk(startDirectory, 0, results); handleEnd(results); } catch(CancelException cancel) { handleCancelled(startDirectory, results, cancel); } } /** * Main recursive method to examine the directory hierarchy. * * @param directory the directory to examine, not null * @param depth the directory level (starting directory = 0) * @param results the collection of result objects, may be updated * @throws IOException if an I/O Error occurs */ private void walk(File directory, int depth, Collection results) throws IOException { checkIfCancelled(directory, depth, results); if (handleDirectory(directory, depth, results)) { handleDirectoryStart(directory, depth, results); int childDepth = depth + 1; if (depthLimit < 0 || childDepth <= depthLimit) { checkIfCancelled(directory, depth, results); File[] childFiles = filter == null ? directory.listFiles() : directory.listFiles(filter); childFiles = filterDirectoryContents(directory, depth, childFiles); if (childFiles == null) { handleRestricted(directory, childDepth, results); } else { for (File childFile : childFiles) { if (childFile.isDirectory()) { walk(childFile, childDepth, results); } else { checkIfCancelled(childFile, childDepth, results); handleFile(childFile, childDepth, results); checkIfCancelled(childFile, childDepth, results); } } } } handleDirectoryEnd(directory, depth, results); } checkIfCancelled(directory, depth, results); } //----------------------------------------------------------------------- /** * Checks whether the walk has been cancelled by calling {@link #handleIsCancelled}, * throwing a CancelException if it has. *

* Writers of subclasses should not normally call this method as it is called * automatically by the walk of the tree. However, sometimes a single method, * typically {@link #handleFile}, may take a long time to run. In that case, * you may wish to check for cancellation by calling this method. * * @param file the current file being processed * @param depth the current file level (starting directory = 0) * @param results the collection of result objects, may be updated * @throws IOException if an I/O Error occurs */ protected final void checkIfCancelled(File file, int depth, Collection results) throws IOException { if (handleIsCancelled(file, depth, results)) { throw new CancelException(file, depth); } } /** * Overridable callback method invoked to determine if the entire walk * operation should be immediately cancelled. *

* This method should be implemented by those subclasses that want to * provide a public cancel() method available from another * thread. The design pattern for the subclass should be as follows: *

     *  public class FooDirectoryWalker extends DirectoryWalker {
     *    private volatile boolean cancelled = false;
     *
     *    public void cancel() {
     *        cancelled = true;
     *    }
     *    private void handleIsCancelled(File file, int depth, Collection results) {
     *        return cancelled;
     *    }
     *    protected void handleCancelled(File startDirectory,
     *              Collection results, CancelException cancel) {
     *        // implement processing required when a cancellation occurs
     *    }
     *  }
     * 
*

* If this method returns true, then the directory walk is immediately * cancelled. The next callback method will be {@link #handleCancelled}. *

* This implementation returns false. * * @param file the file or directory being processed * @param depth the current directory level (starting directory = 0) * @param results the collection of result objects, may be updated * @return true if the walk has been cancelled * @throws IOException if an I/O Error occurs */ protected boolean handleIsCancelled( File file, int depth, Collection results) throws IOException { // do nothing - overridable by subclass return false; // not cancelled } /** * Overridable callback method invoked when the operation is cancelled. * The file being processed when the cancellation occurred can be * obtained from the exception. *

* This implementation just re-throws the {@link CancelException}. * * @param startDirectory the directory that the walk started from * @param results the collection of result objects, may be updated * @param cancel the exception throw to cancel further processing * containing details at the point of cancellation. * @throws IOException if an I/O Error occurs */ protected void handleCancelled(File startDirectory, Collection results, CancelException cancel) throws IOException { // re-throw exception - overridable by subclass throw cancel; } //----------------------------------------------------------------------- /** * Overridable callback method invoked at the start of processing. *

* This implementation does nothing. * * @param startDirectory the directory to start from * @param results the collection of result objects, may be updated * @throws IOException if an I/O Error occurs */ protected void handleStart(File startDirectory, Collection results) throws IOException { // do nothing - overridable by subclass } /** * Overridable callback method invoked to determine if a directory should be processed. *

* This method returns a boolean to indicate if the directory should be examined or not. * If you return false, the entire directory and any subdirectories will be skipped. * Note that this functionality is in addition to the filtering by file filter. *

* This implementation does nothing and returns true. * * @param directory the current directory being processed * @param depth the current directory level (starting directory = 0) * @param results the collection of result objects, may be updated * @return true to process this directory, false to skip this directory * @throws IOException if an I/O Error occurs */ protected boolean handleDirectory(File directory, int depth, Collection results) throws IOException { // do nothing - overridable by subclass return true; // process directory } /** * Overridable callback method invoked at the start of processing each directory. *

* This implementation does nothing. * * @param directory the current directory being processed * @param depth the current directory level (starting directory = 0) * @param results the collection of result objects, may be updated * @throws IOException if an I/O Error occurs */ protected void handleDirectoryStart(File directory, int depth, Collection results) throws IOException { // do nothing - overridable by subclass } /** * Overridable callback method invoked with the contents of each directory. *

* This implementation returns the files unchanged * * @param directory the current directory being processed * @param depth the current directory level (starting directory = 0) * @param files the files (possibly filtered) in the directory * @return the filtered list of files * @throws IOException if an I/O Error occurs * @since 2.0 */ protected File[] filterDirectoryContents(File directory, int depth, File[] files) throws IOException { return files; } /** * Overridable callback method invoked for each (non-directory) file. *

* This implementation does nothing. * * @param file the current file being processed * @param depth the current directory level (starting directory = 0) * @param results the collection of result objects, may be updated * @throws IOException if an I/O Error occurs */ protected void handleFile(File file, int depth, Collection results) throws IOException { // do nothing - overridable by subclass } /** * Overridable callback method invoked for each restricted directory. *

* This implementation does nothing. * * @param directory the restricted directory * @param depth the current directory level (starting directory = 0) * @param results the collection of result objects, may be updated * @throws IOException if an I/O Error occurs */ protected void handleRestricted(File directory, int depth, Collection results) throws IOException { // do nothing - overridable by subclass } /** * Overridable callback method invoked at the end of processing each directory. *

* This implementation does nothing. * * @param directory the directory being processed * @param depth the current directory level (starting directory = 0) * @param results the collection of result objects, may be updated * @throws IOException if an I/O Error occurs */ protected void handleDirectoryEnd(File directory, int depth, Collection results) throws IOException { // do nothing - overridable by subclass } /** * Overridable callback method invoked at the end of processing. *

* This implementation does nothing. * * @param results the collection of result objects, may be updated * @throws IOException if an I/O Error occurs */ protected void handleEnd(Collection results) throws IOException { // do nothing - overridable by subclass } //----------------------------------------------------------------------- /** * CancelException is thrown in DirectoryWalker to cancel the current * processing. */ public static class CancelException extends IOException { /** Serialization id. */ private static final long serialVersionUID = 1347339620135041008L; /** The file being processed when the exception was thrown. */ private final File file; /** The file depth when the exception was thrown. */ private final int depth; /** * Constructs a CancelException with * the file and depth when cancellation occurred. * * @param file the file when the operation was cancelled, may be null * @param depth the depth when the operation was cancelled, may be null */ public CancelException(File file, int depth) { this("Operation Cancelled", file, depth); } /** * Constructs a CancelException with * an appropriate message and the file and depth when * cancellation occurred. * * @param message the detail message * @param file the file when the operation was cancelled * @param depth the depth when the operation was cancelled */ public CancelException(String message, File file, int depth) { super(message); this.file = file; this.depth = depth; } /** * Return the file when the operation was cancelled. * * @return the file when the operation was cancelled */ public File getFile() { return file; } /** * Return the depth when the operation was cancelled. * * @return the depth when the operation was cancelled */ public int getDepth() { return depth; } } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/filefilter/0000755000175000017500000000000012125050425026203 5ustar ebourgebourglibcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/filefilter/SuffixFileFilter.java0000644000175000017500000001557312125050425032273 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.filefilter; import java.io.File; import java.io.Serializable; import java.util.List; import org.apache.commons.io.IOCase; /** * Filters files based on the suffix (what the filename ends with). * This is used in retrieving all the files of a particular type. *

* For example, to retrieve and print all *.java files * in the current directory: * *

 * File dir = new File(".");
 * String[] files = dir.list( new SuffixFileFilter(".java") );
 * for (int i = 0; i < files.length; i++) {
 *     System.out.println(files[i]);
 * }
 * 
* * @since 1.0 * @version $Id: SuffixFileFilter.java 1304052 2012-03-22 20:55:29Z ggregory $ * @see FileFilterUtils#suffixFileFilter(String) * @see FileFilterUtils#suffixFileFilter(String, IOCase) */ public class SuffixFileFilter extends AbstractFileFilter implements Serializable { /** The filename suffixes to search for */ private final String[] suffixes; /** Whether the comparison is case sensitive. */ private final IOCase caseSensitivity; /** * Constructs a new Suffix file filter for a single extension. * * @param suffix the suffix to allow, must not be null * @throws IllegalArgumentException if the suffix is null */ public SuffixFileFilter(String suffix) { this(suffix, IOCase.SENSITIVE); } /** * Constructs a new Suffix file filter for a single extension * specifying case-sensitivity. * * @param suffix the suffix to allow, must not be null * @param caseSensitivity how to handle case sensitivity, null means case-sensitive * @throws IllegalArgumentException if the suffix is null * @since 1.4 */ public SuffixFileFilter(String suffix, IOCase caseSensitivity) { if (suffix == null) { throw new IllegalArgumentException("The suffix must not be null"); } this.suffixes = new String[] {suffix}; this.caseSensitivity = caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity; } /** * Constructs a new Suffix file filter for an array of suffixs. *

* The array is not cloned, so could be changed after constructing the * instance. This would be inadvisable however. * * @param suffixes the suffixes to allow, must not be null * @throws IllegalArgumentException if the suffix array is null */ public SuffixFileFilter(String[] suffixes) { this(suffixes, IOCase.SENSITIVE); } /** * Constructs a new Suffix file filter for an array of suffixs * specifying case-sensitivity. *

* The array is not cloned, so could be changed after constructing the * instance. This would be inadvisable however. * * @param suffixes the suffixes to allow, must not be null * @param caseSensitivity how to handle case sensitivity, null means case-sensitive * @throws IllegalArgumentException if the suffix array is null * @since 1.4 */ public SuffixFileFilter(String[] suffixes, IOCase caseSensitivity) { if (suffixes == null) { throw new IllegalArgumentException("The array of suffixes must not be null"); } this.suffixes = new String[suffixes.length]; System.arraycopy(suffixes, 0, this.suffixes, 0, suffixes.length); this.caseSensitivity = caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity; } /** * Constructs a new Suffix file filter for a list of suffixes. * * @param suffixes the suffixes to allow, must not be null * @throws IllegalArgumentException if the suffix list is null * @throws ClassCastException if the list does not contain Strings */ public SuffixFileFilter(List suffixes) { this(suffixes, IOCase.SENSITIVE); } /** * Constructs a new Suffix file filter for a list of suffixes * specifying case-sensitivity. * * @param suffixes the suffixes to allow, must not be null * @param caseSensitivity how to handle case sensitivity, null means case-sensitive * @throws IllegalArgumentException if the suffix list is null * @throws ClassCastException if the list does not contain Strings * @since 1.4 */ public SuffixFileFilter(List suffixes, IOCase caseSensitivity) { if (suffixes == null) { throw new IllegalArgumentException("The list of suffixes must not be null"); } this.suffixes = suffixes.toArray(new String[suffixes.size()]); this.caseSensitivity = caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity; } /** * Checks to see if the filename ends with the suffix. * * @param file the File to check * @return true if the filename ends with one of our suffixes */ @Override public boolean accept(File file) { String name = file.getName(); for (String suffix : this.suffixes) { if (caseSensitivity.checkEndsWith(name, suffix)) { return true; } } return false; } /** * Checks to see if the filename ends with the suffix. * * @param file the File directory * @param name the filename * @return true if the filename ends with one of our suffixes */ @Override public boolean accept(File file, String name) { for (String suffix : this.suffixes) { if (caseSensitivity.checkEndsWith(name, suffix)) { return true; } } return false; } /** * Provide a String representaion of this file filter. * * @return a String representaion */ @Override public String toString() { StringBuilder buffer = new StringBuilder(); buffer.append(super.toString()); buffer.append("("); if (suffixes != null) { for (int i = 0; i < suffixes.length; i++) { if (i > 0) { buffer.append(","); } buffer.append(suffixes[i]); } } buffer.append(")"); return buffer.toString(); } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/filefilter/FileFileFilter.java0000644000175000017500000000362312125050425031677 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.filefilter; import java.io.File; import java.io.Serializable; /** * This filter accepts Files that are files (not directories). *

* For example, here is how to print out a list of the real files * within the current directory: * *

 * File dir = new File(".");
 * String[] files = dir.list( FileFileFilter.FILE );
 * for ( int i = 0; i < files.length; i++ ) {
 *     System.out.println(files[i]);
 * }
 * 
* * @since 1.3 * @version $Id: FileFileFilter.java 1304052 2012-03-22 20:55:29Z ggregory $ * @see FileFilterUtils#fileFileFilter() */ public class FileFileFilter extends AbstractFileFilter implements Serializable { /** Singleton instance of file filter */ public static final IOFileFilter FILE = new FileFileFilter(); /** * Restrictive consructor. */ protected FileFileFilter() { } /** * Checks to see if the file is a file. * * @param file the File to check * @return true if the file is a file */ @Override public boolean accept(File file) { return file.isFile(); } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/filefilter/DirectoryFileFilter.java0000644000175000017500000000442712125050425032767 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.filefilter; import java.io.File; import java.io.Serializable; /** * This filter accepts Files that are directories. *

* For example, here is how to print out a list of the * current directory's subdirectories: * *

 * File dir = new File(".");
 * String[] files = dir.list( DirectoryFileFilter.INSTANCE );
 * for ( int i = 0; i < files.length; i++ ) {
 *     System.out.println(files[i]);
 * }
 * 
* * @since 1.0 * @version $Id: DirectoryFileFilter.java 1304052 2012-03-22 20:55:29Z ggregory $ * * @see FileFilterUtils#directoryFileFilter() */ public class DirectoryFileFilter extends AbstractFileFilter implements Serializable { /** * Singleton instance of directory filter. * @since 1.3 */ public static final IOFileFilter DIRECTORY = new DirectoryFileFilter(); /** * Singleton instance of directory filter. * Please use the identical DirectoryFileFilter.DIRECTORY constant. * The new name is more JDK 1.5 friendly as it doesn't clash with other * values when using static imports. */ public static final IOFileFilter INSTANCE = DIRECTORY; /** * Restrictive consructor. */ protected DirectoryFileFilter() { } /** * Checks to see if the file is a directory. * * @param file the File to check * @return true if the file is a directory */ @Override public boolean accept(File file) { return file.isDirectory(); } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/filefilter/NameFileFilter.java0000644000175000017500000001502412125050425031676 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.filefilter; import java.io.File; import java.io.Serializable; import java.util.List; import org.apache.commons.io.IOCase; /** * Filters filenames for a certain name. *

* For example, to print all files and directories in the * current directory whose name is Test: * *

 * File dir = new File(".");
 * String[] files = dir.list( new NameFileFilter("Test") );
 * for ( int i = 0; i < files.length; i++ ) {
 *     System.out.println(files[i]);
 * }
 * 
* * @since 1.0 * @version $Id: NameFileFilter.java 1304058 2012-03-22 21:02:43Z sebb $ * @see FileFilterUtils#nameFileFilter(String) * @see FileFilterUtils#nameFileFilter(String, IOCase) */ public class NameFileFilter extends AbstractFileFilter implements Serializable { /** The filenames to search for */ private final String[] names; /** Whether the comparison is case sensitive. */ private final IOCase caseSensitivity; /** * Constructs a new case-sensitive name file filter for a single name. * * @param name the name to allow, must not be null * @throws IllegalArgumentException if the name is null */ public NameFileFilter(String name) { this(name, null); } /** * Construct a new name file filter specifying case-sensitivity. * * @param name the name to allow, must not be null * @param caseSensitivity how to handle case sensitivity, null means case-sensitive * @throws IllegalArgumentException if the name is null */ public NameFileFilter(String name, IOCase caseSensitivity) { if (name == null) { throw new IllegalArgumentException("The wildcard must not be null"); } this.names = new String[] {name}; this.caseSensitivity = caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity; } /** * Constructs a new case-sensitive name file filter for an array of names. *

* The array is not cloned, so could be changed after constructing the * instance. This would be inadvisable however. * * @param names the names to allow, must not be null * @throws IllegalArgumentException if the names array is null */ public NameFileFilter(String[] names) { this(names, null); } /** * Constructs a new name file filter for an array of names specifying case-sensitivity. *

* The array is not cloned, so could be changed after constructing the * instance. This would be inadvisable however. * * @param names the names to allow, must not be null * @param caseSensitivity how to handle case sensitivity, null means case-sensitive * @throws IllegalArgumentException if the names array is null */ public NameFileFilter(String[] names, IOCase caseSensitivity) { if (names == null) { throw new IllegalArgumentException("The array of names must not be null"); } this.names = new String[names.length]; System.arraycopy(names, 0, this.names, 0, names.length); this.caseSensitivity = caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity; } /** * Constructs a new case-sensitive name file filter for a list of names. * * @param names the names to allow, must not be null * @throws IllegalArgumentException if the name list is null * @throws ClassCastException if the list does not contain Strings */ public NameFileFilter(List names) { this(names, null); } /** * Constructs a new name file filter for a list of names specifying case-sensitivity. * * @param names the names to allow, must not be null * @param caseSensitivity how to handle case sensitivity, null means case-sensitive * @throws IllegalArgumentException if the name list is null * @throws ClassCastException if the list does not contain Strings */ public NameFileFilter(List names, IOCase caseSensitivity) { if (names == null) { throw new IllegalArgumentException("The list of names must not be null"); } this.names = names.toArray(new String[names.size()]); this.caseSensitivity = caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity; } //----------------------------------------------------------------------- /** * Checks to see if the filename matches. * * @param file the File to check * @return true if the filename matches */ @Override public boolean accept(File file) { String name = file.getName(); for (String name2 : this.names) { if (caseSensitivity.checkEquals(name, name2)) { return true; } } return false; } /** * Checks to see if the filename matches. * * @param dir the File directory (ignored) * @param name the filename * @return true if the filename matches */ @Override public boolean accept(File dir, String name) { for (String name2 : names) { if (caseSensitivity.checkEquals(name, name2)) { return true; } } return false; } /** * Provide a String representaion of this file filter. * * @return a String representaion */ @Override public String toString() { StringBuilder buffer = new StringBuilder(); buffer.append(super.toString()); buffer.append("("); if (names != null) { for (int i = 0; i < names.length; i++) { if (i > 0) { buffer.append(","); } buffer.append(names[i]); } } buffer.append(")"); return buffer.toString(); } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/filefilter/CanReadFileFilter.java0000644000175000017500000000563212125050425032317 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.filefilter; import java.io.File; import java.io.Serializable; /** * This filter accepts Files that can be read. *

* Example, showing how to print out a list of the * current directory's readable files: * *

 * File dir = new File(".");
 * String[] files = dir.list( CanReadFileFilter.CAN_READ );
 * for ( int i = 0; i < files.length; i++ ) {
 *     System.out.println(files[i]);
 * }
 * 
* *

* Example, showing how to print out a list of the * current directory's un-readable files: * *

 * File dir = new File(".");
 * String[] files = dir.list( CanReadFileFilter.CANNOT_READ );
 * for ( int i = 0; i < files.length; i++ ) {
 *     System.out.println(files[i]);
 * }
 * 
* *

* Example, showing how to print out a list of the * current directory's read-only files: * *

 * File dir = new File(".");
 * String[] files = dir.list( CanReadFileFilter.READ_ONLY );
 * for ( int i = 0; i < files.length; i++ ) {
 *     System.out.println(files[i]);
 * }
 * 
* * @since 1.3 * @version $Id: CanReadFileFilter.java 1307462 2012-03-30 15:13:11Z ggregory $ */ public class CanReadFileFilter extends AbstractFileFilter implements Serializable { /** Singleton instance of readable filter */ public static final IOFileFilter CAN_READ = new CanReadFileFilter(); /** Singleton instance of not readable filter */ public static final IOFileFilter CANNOT_READ = new NotFileFilter(CAN_READ); /** Singleton instance of read-only filter */ public static final IOFileFilter READ_ONLY = new AndFileFilter(CAN_READ, CanWriteFileFilter.CANNOT_WRITE); /** * Restrictive consructor. */ protected CanReadFileFilter() { } /** * Checks to see if the file can be read. * * @param file the File to check. * @return {@code true} if the file can be * read, otherwise {@code false}. */ @Override public boolean accept(File file) { return file.canRead(); } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/filefilter/CanWriteFileFilter.java0000644000175000017500000000477712125050425032547 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.filefilter; import java.io.File; import java.io.Serializable; /** * This filter accepts Files that can be written to. *

* Example, showing how to print out a list of the * current directory's writable files: * *

 * File dir = new File(".");
 * String[] files = dir.list( CanWriteFileFilter.CAN_WRITE );
 * for ( int i = 0; i < files.length; i++ ) {
 *     System.out.println(files[i]);
 * }
 * 
* *

* Example, showing how to print out a list of the * current directory's un-writable files: * *

 * File dir = new File(".");
 * String[] files = dir.list( CanWriteFileFilter.CANNOT_WRITE );
 * for ( int i = 0; i < files.length; i++ ) {
 *     System.out.println(files[i]);
 * }
 * 
* *

* N.B. For read-only files, use * CanReadFileFilter.READ_ONLY. * * @since 1.3 * @version $Id: CanWriteFileFilter.java 1307462 2012-03-30 15:13:11Z ggregory $ */ public class CanWriteFileFilter extends AbstractFileFilter implements Serializable { /** Singleton instance of writable filter */ public static final IOFileFilter CAN_WRITE = new CanWriteFileFilter(); /** Singleton instance of not writable filter */ public static final IOFileFilter CANNOT_WRITE = new NotFileFilter(CAN_WRITE); /** * Restrictive consructor. */ protected CanWriteFileFilter() { } /** * Checks to see if the file can be written to. * * @param file the File to check * @return {@code true} if the file can be * written to, otherwise {@code false}. */ @Override public boolean accept(File file) { return file.canWrite(); } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/filefilter/HiddenFileFilter.java0000644000175000017500000000457312125050425032220 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.filefilter; import java.io.File; import java.io.Serializable; /** * This filter accepts Files that are hidden. *

* Example, showing how to print out a list of the * current directory's hidden files: * *

 * File dir = new File(".");
 * String[] files = dir.list( HiddenFileFilter.HIDDEN );
 * for ( int i = 0; i < files.length; i++ ) {
 *     System.out.println(files[i]);
 * }
 * 
* *

* Example, showing how to print out a list of the * current directory's visible (i.e. not hidden) files: * *

 * File dir = new File(".");
 * String[] files = dir.list( HiddenFileFilter.VISIBLE );
 * for ( int i = 0; i < files.length; i++ ) {
 *     System.out.println(files[i]);
 * }
 * 
* * @since 1.3 * @version $Id: HiddenFileFilter.java 1307462 2012-03-30 15:13:11Z ggregory $ */ public class HiddenFileFilter extends AbstractFileFilter implements Serializable { /** Singleton instance of hidden filter */ public static final IOFileFilter HIDDEN = new HiddenFileFilter(); /** Singleton instance of visible filter */ public static final IOFileFilter VISIBLE = new NotFileFilter(HIDDEN); /** * Restrictive consructor. */ protected HiddenFileFilter() { } /** * Checks to see if the file is hidden. * * @param file the File to check * @return {@code true} if the file is * hidden, otherwise {@code false}. */ @Override public boolean accept(File file) { return file.isHidden(); } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/filefilter/TrueFileFilter.java0000644000175000017500000000405212125050425031734 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.filefilter; import java.io.File; import java.io.Serializable; /** * A file filter that always returns true. * * @since 1.0 * @version $Id: TrueFileFilter.java 1304058 2012-03-22 21:02:43Z sebb $ * @see FileFilterUtils#trueFileFilter() */ public class TrueFileFilter implements IOFileFilter, Serializable { /** * Singleton instance of true filter. * @since 1.3 */ public static final IOFileFilter TRUE = new TrueFileFilter(); /** * Singleton instance of true filter. * Please use the identical TrueFileFilter.TRUE constant. * The new name is more JDK 1.5 friendly as it doesn't clash with other * values when using static imports. */ public static final IOFileFilter INSTANCE = TRUE; /** * Restrictive consructor. */ protected TrueFileFilter() { } /** * Returns true. * * @param file the file to check (ignored) * @return true */ public boolean accept(File file) { return true; } /** * Returns true. * * @param dir the directory to check (ignored) * @param name the filename (ignored) * @return true */ public boolean accept(File dir, String name) { return true; } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/filefilter/AbstractFileFilter.java0000644000175000017500000000414712125050425032565 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.filefilter; import java.io.File; /** * An abstract class which implements the Java FileFilter and FilenameFilter * interfaces via the IOFileFilter interface. *

* Note that a subclass must override one of the accept methods, * otherwise your class will infinitely loop. * * @since 1.0 * @version $Id: AbstractFileFilter.java 1304052 2012-03-22 20:55:29Z ggregory $ */ public abstract class AbstractFileFilter implements IOFileFilter { /** * Checks to see if the File should be accepted by this filter. * * @param file the File to check * @return true if this file matches the test */ public boolean accept(File file) { return accept(file.getParentFile(), file.getName()); } /** * Checks to see if the File should be accepted by this filter. * * @param dir the directory File to check * @param name the filename within the directory to check * @return true if this file matches the test */ public boolean accept(File dir, String name) { return accept(new File(dir, name)); } /** * Provide a String representaion of this file filter. * * @return a String representaion */ @Override public String toString() { return getClass().getSimpleName(); } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/filefilter/DelegateFileFilter.java0000644000175000017500000000643412125050425032535 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.filefilter; import java.io.File; import java.io.FileFilter; import java.io.FilenameFilter; import java.io.Serializable; /** * This class turns a Java FileFilter or FilenameFilter into an IO FileFilter. * * @since 1.0 * @version $Id: DelegateFileFilter.java 1304052 2012-03-22 20:55:29Z ggregory $ * * @see FileFilterUtils#asFileFilter(FileFilter) * @see FileFilterUtils#asFileFilter(FilenameFilter) */ public class DelegateFileFilter extends AbstractFileFilter implements Serializable { /** The Filename filter */ private final FilenameFilter filenameFilter; /** The File filter */ private final FileFilter fileFilter; /** * Constructs a delegate file filter around an existing FilenameFilter. * * @param filter the filter to decorate */ public DelegateFileFilter(FilenameFilter filter) { if (filter == null) { throw new IllegalArgumentException("The FilenameFilter must not be null"); } this.filenameFilter = filter; this.fileFilter = null; } /** * Constructs a delegate file filter around an existing FileFilter. * * @param filter the filter to decorate */ public DelegateFileFilter(FileFilter filter) { if (filter == null) { throw new IllegalArgumentException("The FileFilter must not be null"); } this.fileFilter = filter; this.filenameFilter = null; } /** * Checks the filter. * * @param file the file to check * @return true if the filter matches */ @Override public boolean accept(File file) { if (fileFilter != null) { return fileFilter.accept(file); } else { return super.accept(file); } } /** * Checks the filter. * * @param dir the directory * @param name the filename in the directory * @return true if the filter matches */ @Override public boolean accept(File dir, String name) { if (filenameFilter != null) { return filenameFilter.accept(dir, name); } else { return super.accept(dir, name); } } /** * Provide a String representaion of this file filter. * * @return a String representaion */ @Override public String toString() { String delegate = fileFilter != null ? fileFilter.toString() : filenameFilter.toString(); return super.toString() + "(" + delegate + ")"; } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/filefilter/RegexFileFilter.java0000644000175000017500000001002112125050425032060 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.filefilter; import java.io.File; import java.io.Serializable; import java.util.regex.Pattern; import org.apache.commons.io.IOCase; /** * Filters files using supplied regular expression(s). *

* See java.util.regex.Pattern for regex matching rules *

* *

* e.g. *

 * File dir = new File(".");
 * FileFilter fileFilter = new RegexFileFilter("^.*[tT]est(-\\d+)?\\.java$");
 * File[] files = dir.listFiles(fileFilter);
 * for (int i = 0; i < files.length; i++) {
 *   System.out.println(files[i]);
 * }
 * 
* * @version $Id: RegexFileFilter.java 1304058 2012-03-22 21:02:43Z sebb $ * @since 1.4 */ public class RegexFileFilter extends AbstractFileFilter implements Serializable { /** The regular expression pattern that will be used to match filenames */ private final Pattern pattern; /** * Construct a new regular expression filter. * * @param pattern regular string expression to match * @throws IllegalArgumentException if the pattern is null */ public RegexFileFilter(String pattern) { if (pattern == null) { throw new IllegalArgumentException("Pattern is missing"); } this.pattern = Pattern.compile(pattern); } /** * Construct a new regular expression filter with the specified flags case sensitivity. * * @param pattern regular string expression to match * @param caseSensitivity how to handle case sensitivity, null means case-sensitive * @throws IllegalArgumentException if the pattern is null */ public RegexFileFilter(String pattern, IOCase caseSensitivity) { if (pattern == null) { throw new IllegalArgumentException("Pattern is missing"); } int flags = 0; if (caseSensitivity != null && !caseSensitivity.isCaseSensitive()) { flags = Pattern.CASE_INSENSITIVE; } this.pattern = Pattern.compile(pattern, flags); } /** * Construct a new regular expression filter with the specified flags. * * @param pattern regular string expression to match * @param flags pattern flags - e.g. {@link Pattern#CASE_INSENSITIVE} * @throws IllegalArgumentException if the pattern is null */ public RegexFileFilter(String pattern, int flags) { if (pattern == null) { throw new IllegalArgumentException("Pattern is missing"); } this.pattern = Pattern.compile(pattern, flags); } /** * Construct a new regular expression filter for a compiled regular expression * * @param pattern regular expression to match * @throws IllegalArgumentException if the pattern is null */ public RegexFileFilter(Pattern pattern) { if (pattern == null) { throw new IllegalArgumentException("Pattern is missing"); } this.pattern = pattern; } /** * Checks to see if the filename matches one of the regular expressions. * * @param dir the file directory (ignored) * @param name the filename * @return true if the filename matches one of the regular expressions */ @Override public boolean accept(File dir, String name) { return pattern.matcher(name).matches(); } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/filefilter/NotFileFilter.java0000644000175000017500000000502612125050425031557 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.filefilter; import java.io.File; import java.io.Serializable; /** * This filter produces a logical NOT of the filters specified. * * @since 1.0 * @version $Id: NotFileFilter.java 1304052 2012-03-22 20:55:29Z ggregory $ * @see FileFilterUtils#notFileFilter(IOFileFilter) */ public class NotFileFilter extends AbstractFileFilter implements Serializable { /** The filter */ private final IOFileFilter filter; /** * Constructs a new file filter that NOTs the result of another filter. * * @param filter the filter, must not be null * @throws IllegalArgumentException if the filter is null */ public NotFileFilter(IOFileFilter filter) { if (filter == null) { throw new IllegalArgumentException("The filter must not be null"); } this.filter = filter; } /** * Returns the logical NOT of the underlying filter's return value for the same File. * * @param file the File to check * @return true if the filter returns false */ @Override public boolean accept(File file) { return ! filter.accept(file); } /** * Returns the logical NOT of the underlying filter's return value for the same arguments. * * @param file the File directory * @param name the filename * @return true if the filter returns false */ @Override public boolean accept(File file, String name) { return ! filter.accept(file, name); } /** * Provide a String representaion of this file filter. * * @return a String representaion */ @Override public String toString() { return super.toString() + "(" + filter.toString() + ")"; } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/filefilter/FalseFileFilter.java0000644000175000017500000000407712125050425032056 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.filefilter; import java.io.File; import java.io.Serializable; /** * A file filter that always returns false. * * @since 1.0 * @version $Id: FalseFileFilter.java 1304058 2012-03-22 21:02:43Z sebb $ * * @see FileFilterUtils#falseFileFilter() */ public class FalseFileFilter implements IOFileFilter, Serializable { /** * Singleton instance of false filter. * @since 1.3 */ public static final IOFileFilter FALSE = new FalseFileFilter(); /** * Singleton instance of false filter. * Please use the identical FalseFileFilter.FALSE constant. * The new name is more JDK 1.5 friendly as it doesn't clash with other * values when using static imports. */ public static final IOFileFilter INSTANCE = FALSE; /** * Restrictive consructor. */ protected FalseFileFilter() { } /** * Returns false. * * @param file the file to check (ignored) * @return false */ public boolean accept(File file) { return false; } /** * Returns false. * * @param dir the directory to check (ignored) * @param name the filename (ignored) * @return false */ public boolean accept(File dir, String name) { return false; } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/filefilter/WildcardFileFilter.java0000644000175000017500000001631312125050425032551 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.filefilter; import java.io.File; import java.io.Serializable; import java.util.List; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOCase; /** * Filters files using the supplied wildcards. *

* This filter selects files and directories based on one or more wildcards. * Testing is case-sensitive by default, but this can be configured. *

* The wildcard matcher uses the characters '?' and '*' to represent a * single or multiple wildcard characters. * This is the same as often found on Dos/Unix command lines. * The extension check is case-sensitive by . * See {@link FilenameUtils#wildcardMatchOnSystem} for more information. *

* For example: *

 * File dir = new File(".");
 * FileFilter fileFilter = new WildcardFileFilter("*test*.java~*~");
 * File[] files = dir.listFiles(fileFilter);
 * for (int i = 0; i < files.length; i++) {
 *   System.out.println(files[i]);
 * }
 * 
* * @version $Id: WildcardFileFilter.java 1304058 2012-03-22 21:02:43Z sebb $ * @since 1.3 */ public class WildcardFileFilter extends AbstractFileFilter implements Serializable { /** The wildcards that will be used to match filenames. */ private final String[] wildcards; /** Whether the comparison is case sensitive. */ private final IOCase caseSensitivity; /** * Construct a new case-sensitive wildcard filter for a single wildcard. * * @param wildcard the wildcard to match * @throws IllegalArgumentException if the pattern is null */ public WildcardFileFilter(String wildcard) { this(wildcard, null); } /** * Construct a new wildcard filter for a single wildcard specifying case-sensitivity. * * @param wildcard the wildcard to match, not null * @param caseSensitivity how to handle case sensitivity, null means case-sensitive * @throws IllegalArgumentException if the pattern is null */ public WildcardFileFilter(String wildcard, IOCase caseSensitivity) { if (wildcard == null) { throw new IllegalArgumentException("The wildcard must not be null"); } this.wildcards = new String[] { wildcard }; this.caseSensitivity = caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity; } /** * Construct a new case-sensitive wildcard filter for an array of wildcards. *

* The array is not cloned, so could be changed after constructing the * instance. This would be inadvisable however. * * @param wildcards the array of wildcards to match * @throws IllegalArgumentException if the pattern array is null */ public WildcardFileFilter(String[] wildcards) { this(wildcards, null); } /** * Construct a new wildcard filter for an array of wildcards specifying case-sensitivity. *

* The array is not cloned, so could be changed after constructing the * instance. This would be inadvisable however. * * @param wildcards the array of wildcards to match, not null * @param caseSensitivity how to handle case sensitivity, null means case-sensitive * @throws IllegalArgumentException if the pattern array is null */ public WildcardFileFilter(String[] wildcards, IOCase caseSensitivity) { if (wildcards == null) { throw new IllegalArgumentException("The wildcard array must not be null"); } this.wildcards = new String[wildcards.length]; System.arraycopy(wildcards, 0, this.wildcards, 0, wildcards.length); this.caseSensitivity = caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity; } /** * Construct a new case-sensitive wildcard filter for a list of wildcards. * * @param wildcards the list of wildcards to match, not null * @throws IllegalArgumentException if the pattern list is null * @throws ClassCastException if the list does not contain Strings */ public WildcardFileFilter(List wildcards) { this(wildcards, null); } /** * Construct a new wildcard filter for a list of wildcards specifying case-sensitivity. * * @param wildcards the list of wildcards to match, not null * @param caseSensitivity how to handle case sensitivity, null means case-sensitive * @throws IllegalArgumentException if the pattern list is null * @throws ClassCastException if the list does not contain Strings */ public WildcardFileFilter(List wildcards, IOCase caseSensitivity) { if (wildcards == null) { throw new IllegalArgumentException("The wildcard list must not be null"); } this.wildcards = wildcards.toArray(new String[wildcards.size()]); this.caseSensitivity = caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity; } //----------------------------------------------------------------------- /** * Checks to see if the filename matches one of the wildcards. * * @param dir the file directory (ignored) * @param name the filename * @return true if the filename matches one of the wildcards */ @Override public boolean accept(File dir, String name) { for (String wildcard : wildcards) { if (FilenameUtils.wildcardMatch(name, wildcard, caseSensitivity)) { return true; } } return false; } /** * Checks to see if the filename matches one of the wildcards. * * @param file the file to check * @return true if the filename matches one of the wildcards */ @Override public boolean accept(File file) { String name = file.getName(); for (String wildcard : wildcards) { if (FilenameUtils.wildcardMatch(name, wildcard, caseSensitivity)) { return true; } } return false; } /** * Provide a String representaion of this file filter. * * @return a String representaion */ @Override public String toString() { StringBuilder buffer = new StringBuilder(); buffer.append(super.toString()); buffer.append("("); if (wildcards != null) { for (int i = 0; i < wildcards.length; i++) { if (i > 0) { buffer.append(","); } buffer.append(wildcards[i]); } } buffer.append(")"); return buffer.toString(); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/filefilter/MagicNumberFileFilter.javalibcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/filefilter/MagicNumberFileFilter.jav0000644000175000017500000002316412125050425033052 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.filefilter; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.io.Serializable; import java.util.Arrays; import org.apache.commons.io.IOUtils; /** *

* File filter for matching files containing a "magic number". A magic number * is a unique series of bytes common to all files of a specific file format. * For instance, all Java class files begin with the bytes * 0xCAFEBABE. *

* *
 * File dir = new File(".");
 * MagicNumberFileFilter javaClassFileFilter =
 *     MagicNumberFileFilter(new byte[] {(byte) 0xCA, (byte) 0xFE, 
 *       (byte) 0xBA, (byte) 0xBE}); 
 * String[] javaClassFiles = dir.list(javaClassFileFilter);
 * for (String javaClassFile : javaClassFiles) {
 *     System.out.println(javaClassFile);
 * }
 * 
* *

* Sometimes, such as in the case of TAR files, the * magic number will be offset by a certain number of bytes in the file. In the * case of TAR archive files, this offset is 257 bytes. *

* *
 * File dir = new File(".");
 * MagicNumberFileFilter tarFileFilter = 
 *     MagicNumberFileFilter("ustar", 257); 
 * String[] tarFiles = dir.list(tarFileFilter);
 * for (String tarFile : tarFiles) {
 *     System.out.println(tarFile);
 * }
 * 
* @since 2.0 * @see FileFilterUtils#magicNumberFileFilter(byte[]) * @see FileFilterUtils#magicNumberFileFilter(String) * @see FileFilterUtils#magicNumberFileFilter(byte[], long) * @see FileFilterUtils#magicNumberFileFilter(String, long) */ public class MagicNumberFileFilter extends AbstractFileFilter implements Serializable { /** * The serialization version unique identifier. */ private static final long serialVersionUID = -547733176983104172L; /** * The magic number to compare against the file's bytes at the provided * offset. */ private final byte[] magicNumbers; /** * The offset (in bytes) within the files that the magic number's bytes * should appear. */ private final long byteOffset; /** *

* Constructs a new MagicNumberFileFilter and associates it with the magic * number to test for in files. This constructor assumes a starting offset * of 0. *

* *

* It is important to note that the array is not cloned and that * any changes to the magic number array after construction will affect the * behavior of this file filter. *

* *
     * MagicNumberFileFilter javaClassFileFilter =
     *     MagicNumberFileFilter(new byte[] {(byte) 0xCA, (byte) 0xFE, 
     *       (byte) 0xBA, (byte) 0xBE}); 
     * 
* * @param magicNumber the magic number to look for in the file. * * @throws IllegalArgumentException if magicNumber is * {@code null}, or contains no bytes. */ public MagicNumberFileFilter(byte[] magicNumber) { this(magicNumber, 0); } /** *

* Constructs a new MagicNumberFileFilter and associates it with the magic * number to test for in files. This constructor assumes a starting offset * of 0. *

* * Example usage: *
     * {@code
     * MagicNumberFileFilter xmlFileFilter = 
     *     MagicNumberFileFilter("
     * 
     * @param magicNumber the magic number to look for in the file.
     *        The string is converted to bytes using the platform default charset.
     *
     * @throws IllegalArgumentException if magicNumber is 
     *         {@code null} or the empty String.
     */
    public MagicNumberFileFilter(String magicNumber) {
        this(magicNumber, 0);
    }
    
    /**
     * 

* Constructs a new MagicNumberFileFilter and associates it with the magic * number to test for in files and the byte offset location in the file to * to look for that magic number. *

* *
     * MagicNumberFileFilter tarFileFilter = 
     *     MagicNumberFileFilter("ustar", 257); 
     * 
* * @param magicNumber the magic number to look for in the file. * The string is converted to bytes using the platform default charset. * @param offset the byte offset in the file to start comparing bytes. * * @throws IllegalArgumentException if magicNumber is * {@code null} or the empty String, or offset is * a negative number. */ public MagicNumberFileFilter(String magicNumber, long offset) { if (magicNumber == null) { throw new IllegalArgumentException("The magic number cannot be null"); } if (magicNumber.length() == 0) { throw new IllegalArgumentException("The magic number must contain at least one byte"); } if (offset < 0) { throw new IllegalArgumentException("The offset cannot be negative"); } this.magicNumbers = magicNumber.getBytes(); // uses the platform default charset this.byteOffset = offset; } /** *

* Constructs a new MagicNumberFileFilter and associates it with the magic * number to test for in files and the byte offset location in the file to * to look for that magic number. *

* *

* It is important to note that the array is not cloned and that * any changes to the magic number array after construction will affect the * behavior of this file filter. *

* *
     * MagicNumberFileFilter tarFileFilter =
     *     MagicNumberFileFilter(new byte[] {0x75, 0x73, 0x74, 0x61, 0x72}, 257); 
     * 
* *
     * MagicNumberFileFilter javaClassFileFilter =
     *     MagicNumberFileFilter(new byte[] {0xCA, 0xFE, 0xBA, 0xBE}, 0); 
     * 
* * @param magicNumber the magic number to look for in the file. * @param offset the byte offset in the file to start comparing bytes. * * @throws IllegalArgumentException if magicNumber is * {@code null}, or contains no bytes, or offset * is a negative number. */ public MagicNumberFileFilter(byte[] magicNumber, long offset) { if (magicNumber == null) { throw new IllegalArgumentException("The magic number cannot be null"); } if (magicNumber.length == 0) { throw new IllegalArgumentException("The magic number must contain at least one byte"); } if (offset < 0) { throw new IllegalArgumentException("The offset cannot be negative"); } this.magicNumbers = new byte[magicNumber.length]; System.arraycopy(magicNumber, 0, this.magicNumbers, 0, magicNumber.length); this.byteOffset = offset; } /** *

* Accepts the provided file if the file contains the file filter's magic * number at the specified offset. *

* *

* If any {@link IOException}s occur while reading the file, the file will * be rejected. *

* * @param file the file to accept or reject. * * @return {@code true} if the file contains the filter's magic number * at the specified offset, {@code false} otherwise. */ @Override public boolean accept(File file) { if (file != null && file.isFile() && file.canRead()) { RandomAccessFile randomAccessFile = null; try { byte[] fileBytes = new byte[this.magicNumbers.length]; randomAccessFile = new RandomAccessFile(file, "r"); randomAccessFile.seek(byteOffset); int read = randomAccessFile.read(fileBytes); if (read != magicNumbers.length) { return false; } return Arrays.equals(this.magicNumbers, fileBytes); } catch (IOException ioe) { // Do nothing, fall through and do not accept file } finally { IOUtils.closeQuietly(randomAccessFile); } } return false; } /** * Returns a String representation of the file filter, which includes the * magic number bytes and byte offset. * * @return a String representation of the file filter. */ @Override public String toString() { StringBuilder builder = new StringBuilder(super.toString()); builder.append("("); builder.append(new String(magicNumbers));// TODO perhaps use hex if value is not printable builder.append(","); builder.append(this.byteOffset); builder.append(")"); return builder.toString(); } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/filefilter/IOFileFilter.java0000644000175000017500000000343112125050425031324 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.filefilter; import java.io.File; import java.io.FileFilter; import java.io.FilenameFilter; /** * An interface which brings the FileFilter and FilenameFilter * interfaces together. * * @since 1.0 * @version $Id: IOFileFilter.java 1304052 2012-03-22 20:55:29Z ggregory $ */ public interface IOFileFilter extends FileFilter, FilenameFilter { /** * Checks to see if the File should be accepted by this filter. *

* Defined in {@link java.io.FileFilter}. * * @param file the File to check * @return true if this file matches the test */ boolean accept(File file); /** * Checks to see if the File should be accepted by this filter. *

* Defined in {@link java.io.FilenameFilter}. * * @param dir the directory File to check * @param name the filename within the directory to check * @return true if this file matches the test */ boolean accept(File dir, String name); } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/filefilter/OrFileFilter.java0000644000175000017500000001141712125050425031400 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.filefilter; import java.io.File; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * A {@link java.io.FileFilter} providing conditional OR logic across a list of * file filters. This filter returns {@code true} if any filters in the * list return {@code true}. Otherwise, it returns {@code false}. * Checking of the file filter list stops when the first filter returns * {@code true}. * * @since 1.0 * @version $Id: OrFileFilter.java 1307462 2012-03-30 15:13:11Z ggregory $ * @see FileFilterUtils#or(IOFileFilter...) */ public class OrFileFilter extends AbstractFileFilter implements ConditionalFileFilter, Serializable { /** The list of file filters. */ private final List fileFilters; /** * Constructs a new instance of OrFileFilter. * * @since 1.1 */ public OrFileFilter() { this.fileFilters = new ArrayList(); } /** * Constructs a new instance of OrFileFilter * with the specified filters. * * @param fileFilters the file filters for this filter, copied, null ignored * @since 1.1 */ public OrFileFilter(final List fileFilters) { if (fileFilters == null) { this.fileFilters = new ArrayList(); } else { this.fileFilters = new ArrayList(fileFilters); } } /** * Constructs a new file filter that ORs the result of two other filters. * * @param filter1 the first filter, must not be null * @param filter2 the second filter, must not be null * @throws IllegalArgumentException if either filter is null */ public OrFileFilter(IOFileFilter filter1, IOFileFilter filter2) { if (filter1 == null || filter2 == null) { throw new IllegalArgumentException("The filters must not be null"); } this.fileFilters = new ArrayList(2); addFileFilter(filter1); addFileFilter(filter2); } /** * {@inheritDoc} */ public void addFileFilter(final IOFileFilter ioFileFilter) { this.fileFilters.add(ioFileFilter); } /** * {@inheritDoc} */ public List getFileFilters() { return Collections.unmodifiableList(this.fileFilters); } /** * {@inheritDoc} */ public boolean removeFileFilter(IOFileFilter ioFileFilter) { return this.fileFilters.remove(ioFileFilter); } /** * {@inheritDoc} */ public void setFileFilters(final List fileFilters) { this.fileFilters.clear(); this.fileFilters.addAll(fileFilters); } /** * {@inheritDoc} */ @Override public boolean accept(final File file) { for (IOFileFilter fileFilter : fileFilters) { if (fileFilter.accept(file)) { return true; } } return false; } /** * {@inheritDoc} */ @Override public boolean accept(final File file, final String name) { for (IOFileFilter fileFilter : fileFilters) { if (fileFilter.accept(file, name)) { return true; } } return false; } /** * Provide a String representaion of this file filter. * * @return a String representaion */ @Override public String toString() { StringBuilder buffer = new StringBuilder(); buffer.append(super.toString()); buffer.append("("); if (fileFilters != null) { for (int i = 0; i < fileFilters.size(); i++) { if (i > 0) { buffer.append(","); } Object filter = fileFilters.get(i); buffer.append(filter == null ? "null" : filter.toString()); } } buffer.append(")"); return buffer.toString(); } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/filefilter/SizeFileFilter.java0000644000175000017500000000712112125050425031727 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.filefilter; import java.io.File; import java.io.Serializable; /** * Filters files based on size, can filter either smaller files or * files equal to or larger than a given threshold. *

* For example, to print all files and directories in the * current directory whose size is greater than 1 MB: * *

 * File dir = new File(".");
 * String[] files = dir.list( new SizeFileFilter(1024 * 1024) );
 * for ( int i = 0; i < files.length; i++ ) {
 *     System.out.println(files[i]);
 * }
 * 
* * @version $Id: SizeFileFilter.java 1304052 2012-03-22 20:55:29Z ggregory $ * @since 1.2 * @see FileFilterUtils#sizeFileFilter(long) * @see FileFilterUtils#sizeFileFilter(long, boolean) * @see FileFilterUtils#sizeRangeFileFilter(long, long) */ public class SizeFileFilter extends AbstractFileFilter implements Serializable { /** The size threshold. */ private final long size; /** Whether the files accepted will be larger or smaller. */ private final boolean acceptLarger; /** * Constructs a new size file filter for files equal to or * larger than a certain size. * * @param size the threshold size of the files * @throws IllegalArgumentException if the size is negative */ public SizeFileFilter(long size) { this(size, true); } /** * Constructs a new size file filter for files based on a certain size * threshold. * * @param size the threshold size of the files * @param acceptLarger if true, files equal to or larger are accepted, * otherwise smaller ones (but not equal to) * @throws IllegalArgumentException if the size is negative */ public SizeFileFilter(long size, boolean acceptLarger) { if (size < 0) { throw new IllegalArgumentException("The size must be non-negative"); } this.size = size; this.acceptLarger = acceptLarger; } //----------------------------------------------------------------------- /** * Checks to see if the size of the file is favorable. *

* If size equals threshold and smaller files are required, * file IS NOT selected. * If size equals threshold and larger files are required, * file IS selected. * * @param file the File to check * @return true if the filename matches */ @Override public boolean accept(File file) { boolean smaller = file.length() < size; return acceptLarger ? !smaller : smaller; } /** * Provide a String representaion of this file filter. * * @return a String representaion */ @Override public String toString() { String condition = acceptLarger ? ">=" : "<"; return super.toString() + "(" + condition + size + ")"; } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/filefilter/AgeFileFilter.java0000644000175000017500000001252312125050425031513 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.filefilter; import java.io.File; import java.io.Serializable; import java.util.Date; import org.apache.commons.io.FileUtils; /** * Filters files based on a cutoff time, can filter either newer * files or files equal to or older. *

* For example, to print all files and directories in the * current directory older than one day: * *

 * File dir = new File(".");
 * // We are interested in files older than one day
 * long cutoff = System.currentTimeMillis() - (24 * 60 * 60 * 1000);
 * String[] files = dir.list( new AgeFileFilter(cutoff) );
 * for ( int i = 0; i < files.length; i++ ) {
 *     System.out.println(files[i]);
 * }
 * 
* * @version $Id: AgeFileFilter.java 1304052 2012-03-22 20:55:29Z ggregory $ * @see FileFilterUtils#ageFileFilter(Date) * @see FileFilterUtils#ageFileFilter(File) * @see FileFilterUtils#ageFileFilter(long) * @see FileFilterUtils#ageFileFilter(Date, boolean) * @see FileFilterUtils#ageFileFilter(File, boolean) * @see FileFilterUtils#ageFileFilter(long, boolean) * @since 1.2 */ public class AgeFileFilter extends AbstractFileFilter implements Serializable { /** The cutoff time threshold. */ private final long cutoff; /** Whether the files accepted will be older or newer. */ private final boolean acceptOlder; /** * Constructs a new age file filter for files equal to or older than * a certain cutoff * * @param cutoff the threshold age of the files */ public AgeFileFilter(long cutoff) { this(cutoff, true); } /** * Constructs a new age file filter for files on any one side * of a certain cutoff. * * @param cutoff the threshold age of the files * @param acceptOlder if true, older files (at or before the cutoff) * are accepted, else newer ones (after the cutoff). */ public AgeFileFilter(long cutoff, boolean acceptOlder) { this.acceptOlder = acceptOlder; this.cutoff = cutoff; } /** * Constructs a new age file filter for files older than (at or before) * a certain cutoff date. * * @param cutoffDate the threshold age of the files */ public AgeFileFilter(Date cutoffDate) { this(cutoffDate, true); } /** * Constructs a new age file filter for files on any one side * of a certain cutoff date. * * @param cutoffDate the threshold age of the files * @param acceptOlder if true, older files (at or before the cutoff) * are accepted, else newer ones (after the cutoff). */ public AgeFileFilter(Date cutoffDate, boolean acceptOlder) { this(cutoffDate.getTime(), acceptOlder); } /** * Constructs a new age file filter for files older than (at or before) * a certain File (whose last modification time will be used as reference). * * @param cutoffReference the file whose last modification * time is usesd as the threshold age of the files */ public AgeFileFilter(File cutoffReference) { this(cutoffReference, true); } /** * Constructs a new age file filter for files on any one side * of a certain File (whose last modification time will be used as * reference). * * @param cutoffReference the file whose last modification * time is usesd as the threshold age of the files * @param acceptOlder if true, older files (at or before the cutoff) * are accepted, else newer ones (after the cutoff). */ public AgeFileFilter(File cutoffReference, boolean acceptOlder) { this(cutoffReference.lastModified(), acceptOlder); } //----------------------------------------------------------------------- /** * Checks to see if the last modification of the file matches cutoff * favorably. *

* If last modification time equals cutoff and newer files are required, * file IS NOT selected. * If last modification time equals cutoff and older files are required, * file IS selected. * * @param file the File to check * @return true if the filename matches */ @Override public boolean accept(File file) { boolean newer = FileUtils.isFileNewer(file, cutoff); return acceptOlder ? !newer : newer; } /** * Provide a String representaion of this file filter. * * @return a String representaion */ @Override public String toString() { String condition = acceptOlder ? "<=" : ">"; return super.toString() + "(" + condition + cutoff + ")"; } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/filefilter/AndFileFilter.java0000644000175000017500000001171012125050425031516 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.filefilter; import java.io.File; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * A {@link java.io.FileFilter} providing conditional AND logic across a list of * file filters. This filter returns {@code true} if all filters in the * list return {@code true}. Otherwise, it returns {@code false}. * Checking of the file filter list stops when the first filter returns * {@code false}. * * @since 1.0 * @version $Id: AndFileFilter.java 1307462 2012-03-30 15:13:11Z ggregory $ * * @see FileFilterUtils#and(IOFileFilter...) */ public class AndFileFilter extends AbstractFileFilter implements ConditionalFileFilter, Serializable { /** The list of file filters. */ private final List fileFilters; /** * Constructs a new instance of AndFileFilter. * * @since 1.1 */ public AndFileFilter() { this.fileFilters = new ArrayList(); } /** * Constructs a new instance of AndFileFilter * with the specified list of filters. * * @param fileFilters a List of IOFileFilter instances, copied, null ignored * @since 1.1 */ public AndFileFilter(final List fileFilters) { if (fileFilters == null) { this.fileFilters = new ArrayList(); } else { this.fileFilters = new ArrayList(fileFilters); } } /** * Constructs a new file filter that ANDs the result of two other filters. * * @param filter1 the first filter, must not be null * @param filter2 the second filter, must not be null * @throws IllegalArgumentException if either filter is null */ public AndFileFilter(IOFileFilter filter1, IOFileFilter filter2) { if (filter1 == null || filter2 == null) { throw new IllegalArgumentException("The filters must not be null"); } this.fileFilters = new ArrayList(2); addFileFilter(filter1); addFileFilter(filter2); } /** * {@inheritDoc} */ public void addFileFilter(final IOFileFilter ioFileFilter) { this.fileFilters.add(ioFileFilter); } /** * {@inheritDoc} */ public List getFileFilters() { return Collections.unmodifiableList(this.fileFilters); } /** * {@inheritDoc} */ public boolean removeFileFilter(final IOFileFilter ioFileFilter) { return this.fileFilters.remove(ioFileFilter); } /** * {@inheritDoc} */ public void setFileFilters(final List fileFilters) { this.fileFilters.clear(); this.fileFilters.addAll(fileFilters); } /** * {@inheritDoc} */ @Override public boolean accept(final File file) { if (this.fileFilters.isEmpty()) { return false; } for (IOFileFilter fileFilter : fileFilters) { if (!fileFilter.accept(file)) { return false; } } return true; } /** * {@inheritDoc} */ @Override public boolean accept(final File file, final String name) { if (this.fileFilters.isEmpty()) { return false; } for (IOFileFilter fileFilter : fileFilters) { if (!fileFilter.accept(file, name)) { return false; } } return true; } /** * Provide a String representaion of this file filter. * * @return a String representaion */ @Override public String toString() { StringBuilder buffer = new StringBuilder(); buffer.append(super.toString()); buffer.append("("); if (fileFilters != null) { for (int i = 0; i < fileFilters.size(); i++) { if (i > 0) { buffer.append(","); } Object filter = fileFilters.get(i); buffer.append(filter == null ? "null" : filter.toString()); } } buffer.append(")"); return buffer.toString(); } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/filefilter/PrefixFileFilter.java0000644000175000017500000001550612125050425032260 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.filefilter; import java.io.File; import java.io.Serializable; import java.util.List; import org.apache.commons.io.IOCase; /** * Filters filenames for a certain prefix. *

* For example, to print all files and directories in the * current directory whose name starts with Test: * *

 * File dir = new File(".");
 * String[] files = dir.list( new PrefixFileFilter("Test") );
 * for ( int i = 0; i < files.length; i++ ) {
 *     System.out.println(files[i]);
 * }
 * 
* * @since 1.0 * @version $Id: PrefixFileFilter.java 1304052 2012-03-22 20:55:29Z ggregory $ * @see FileFilterUtils#prefixFileFilter(String) * @see FileFilterUtils#prefixFileFilter(String, IOCase) */ public class PrefixFileFilter extends AbstractFileFilter implements Serializable { /** The filename prefixes to search for */ private final String[] prefixes; /** Whether the comparison is case sensitive. */ private final IOCase caseSensitivity; /** * Constructs a new Prefix file filter for a single prefix. * * @param prefix the prefix to allow, must not be null * @throws IllegalArgumentException if the prefix is null */ public PrefixFileFilter(String prefix) { this(prefix, IOCase.SENSITIVE); } /** * Constructs a new Prefix file filter for a single prefix * specifying case-sensitivity. * * @param prefix the prefix to allow, must not be null * @param caseSensitivity how to handle case sensitivity, null means case-sensitive * @throws IllegalArgumentException if the prefix is null * @since 1.4 */ public PrefixFileFilter(String prefix, IOCase caseSensitivity) { if (prefix == null) { throw new IllegalArgumentException("The prefix must not be null"); } this.prefixes = new String[] {prefix}; this.caseSensitivity = caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity; } /** * Constructs a new Prefix file filter for any of an array of prefixes. *

* The array is not cloned, so could be changed after constructing the * instance. This would be inadvisable however. * * @param prefixes the prefixes to allow, must not be null * @throws IllegalArgumentException if the prefix array is null */ public PrefixFileFilter(String[] prefixes) { this(prefixes, IOCase.SENSITIVE); } /** * Constructs a new Prefix file filter for any of an array of prefixes * specifying case-sensitivity. *

* The array is not cloned, so could be changed after constructing the * instance. This would be inadvisable however. * * @param prefixes the prefixes to allow, must not be null * @param caseSensitivity how to handle case sensitivity, null means case-sensitive * @throws IllegalArgumentException if the prefix is null * @since 1.4 */ public PrefixFileFilter(String[] prefixes, IOCase caseSensitivity) { if (prefixes == null) { throw new IllegalArgumentException("The array of prefixes must not be null"); } this.prefixes = new String[prefixes.length]; System.arraycopy(prefixes, 0, this.prefixes, 0, prefixes.length); this.caseSensitivity = caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity; } /** * Constructs a new Prefix file filter for a list of prefixes. * * @param prefixes the prefixes to allow, must not be null * @throws IllegalArgumentException if the prefix list is null * @throws ClassCastException if the list does not contain Strings */ public PrefixFileFilter(List prefixes) { this(prefixes, IOCase.SENSITIVE); } /** * Constructs a new Prefix file filter for a list of prefixes * specifying case-sensitivity. * * @param prefixes the prefixes to allow, must not be null * @param caseSensitivity how to handle case sensitivity, null means case-sensitive * @throws IllegalArgumentException if the prefix list is null * @throws ClassCastException if the list does not contain Strings * @since 1.4 */ public PrefixFileFilter(List prefixes, IOCase caseSensitivity) { if (prefixes == null) { throw new IllegalArgumentException("The list of prefixes must not be null"); } this.prefixes = prefixes.toArray(new String[prefixes.size()]); this.caseSensitivity = caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity; } /** * Checks to see if the filename starts with the prefix. * * @param file the File to check * @return true if the filename starts with one of our prefixes */ @Override public boolean accept(File file) { String name = file.getName(); for (String prefix : this.prefixes) { if (caseSensitivity.checkStartsWith(name, prefix)) { return true; } } return false; } /** * Checks to see if the filename starts with the prefix. * * @param file the File directory * @param name the filename * @return true if the filename starts with one of our prefixes */ @Override public boolean accept(File file, String name) { for (String prefix : prefixes) { if (caseSensitivity.checkStartsWith(name, prefix)) { return true; } } return false; } /** * Provide a String representaion of this file filter. * * @return a String representaion */ @Override public String toString() { StringBuilder buffer = new StringBuilder(); buffer.append(super.toString()); buffer.append("("); if (prefixes != null) { for (int i = 0; i < prefixes.length; i++) { if (i > 0) { buffer.append(","); } buffer.append(prefixes[i]); } } buffer.append(")"); return buffer.toString(); } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/filefilter/EmptyFileFilter.java0000644000175000017500000000521412125050425032114 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.filefilter; import java.io.File; import java.io.Serializable; /** * This filter accepts files or directories that are empty. *

* If the File is a directory it checks that * it contains no files. *

* Example, showing how to print out a list of the * current directory's empty files/directories: * *

 * File dir = new File(".");
 * String[] files = dir.list( EmptyFileFilter.EMPTY );
 * for ( int i = 0; i < files.length; i++ ) {
 *     System.out.println(files[i]);
 * }
 * 
* *

* Example, showing how to print out a list of the * current directory's non-empty files/directories: * *

 * File dir = new File(".");
 * String[] files = dir.list( EmptyFileFilter.NOT_EMPTY );
 * for ( int i = 0; i < files.length; i++ ) {
 *     System.out.println(files[i]);
 * }
 * 
* * @since 1.3 * @version $Id: EmptyFileFilter.java 1307462 2012-03-30 15:13:11Z ggregory $ */ public class EmptyFileFilter extends AbstractFileFilter implements Serializable { /** Singleton instance of empty filter */ public static final IOFileFilter EMPTY = new EmptyFileFilter(); /** Singleton instance of not-empty filter */ public static final IOFileFilter NOT_EMPTY = new NotFileFilter(EMPTY); /** * Restrictive consructor. */ protected EmptyFileFilter() { } /** * Checks to see if the file is empty. * * @param file the file or directory to check * @return {@code true} if the file or directory * is empty, otherwise {@code false}. */ @Override public boolean accept(File file) { if (file.isDirectory()) { File[] files = file.listFiles(); return files == null || files.length == 0; } else { return file.length() == 0; } } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/filefilter/ConditionalFileFilter.javalibcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/filefilter/ConditionalFileFilter.jav0000644000175000017500000000377412125050425033131 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.filefilter; import java.util.List; /** * Defines operations for conditional file filters. * * @since 1.1 * @version $Id: ConditionalFileFilter.java 1307462 2012-03-30 15:13:11Z ggregory $ */ public interface ConditionalFileFilter { /** * Adds the specified file filter to the list of file filters at the end of * the list. * * @param ioFileFilter the filter to be added * @since 1.1 */ void addFileFilter(IOFileFilter ioFileFilter); /** * Returns this conditional file filter's list of file filters. * * @return the file filter list * @since 1.1 */ List getFileFilters(); /** * Removes the specified file filter. * * @param ioFileFilter filter to be removed * @return {@code true} if the filter was found in the list, * {@code false} otherwise * @since 1.1 */ boolean removeFileFilter(IOFileFilter ioFileFilter); /** * Sets the list of file filters, replacing any previously configured * file filters on this filter. * * @param fileFilters the list of filters * @since 1.1 */ void setFileFilters(List fileFilters); } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/filefilter/WildcardFilter.java0000644000175000017500000001146212125050425031751 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.filefilter; import java.io.File; import java.io.Serializable; import java.util.List; import org.apache.commons.io.FilenameUtils; /** * Filters files using the supplied wildcards. *

* This filter selects files, but not directories, based on one or more wildcards * and using case-sensitive comparison. *

* The wildcard matcher uses the characters '?' and '*' to represent a * single or multiple wildcard characters. * This is the same as often found on Dos/Unix command lines. * The extension check is case-sensitive. * See {@link FilenameUtils#wildcardMatch(String, String)} for more information. *

* For example: *

 * File dir = new File(".");
 * FileFilter fileFilter = new WildcardFilter("*test*.java~*~");
 * File[] files = dir.listFiles(fileFilter);
 * for (int i = 0; i < files.length; i++) {
 *   System.out.println(files[i]);
 * }
 * 
* * @version $Id: WildcardFilter.java 1303950 2012-03-22 18:16:04Z ggregory $ * @since 1.1 * @deprecated Use WilcardFileFilter. Deprecated as this class performs directory * filtering which it shouldn't do, but that can't be removed due to compatability. */ @Deprecated public class WildcardFilter extends AbstractFileFilter implements Serializable { /** The wildcards that will be used to match filenames. */ private final String[] wildcards; /** * Construct a new case-sensitive wildcard filter for a single wildcard. * * @param wildcard the wildcard to match * @throws IllegalArgumentException if the pattern is null */ public WildcardFilter(String wildcard) { if (wildcard == null) { throw new IllegalArgumentException("The wildcard must not be null"); } this.wildcards = new String[] { wildcard }; } /** * Construct a new case-sensitive wildcard filter for an array of wildcards. * * @param wildcards the array of wildcards to match * @throws IllegalArgumentException if the pattern array is null */ public WildcardFilter(String[] wildcards) { if (wildcards == null) { throw new IllegalArgumentException("The wildcard array must not be null"); } this.wildcards = new String[wildcards.length]; System.arraycopy(wildcards, 0, this.wildcards, 0, wildcards.length); } /** * Construct a new case-sensitive wildcard filter for a list of wildcards. * * @param wildcards the list of wildcards to match * @throws IllegalArgumentException if the pattern list is null * @throws ClassCastException if the list does not contain Strings */ public WildcardFilter(List wildcards) { if (wildcards == null) { throw new IllegalArgumentException("The wildcard list must not be null"); } this.wildcards = wildcards.toArray(new String[wildcards.size()]); } //----------------------------------------------------------------------- /** * Checks to see if the filename matches one of the wildcards. * * @param dir the file directory * @param name the filename * @return true if the filename matches one of the wildcards */ @Override public boolean accept(File dir, String name) { if (dir != null && new File(dir, name).isDirectory()) { return false; } for (String wildcard : wildcards) { if (FilenameUtils.wildcardMatch(name, wildcard)) { return true; } } return false; } /** * Checks to see if the filename matches one of the wildcards. * * @param file the file to check * @return true if the filename matches one of the wildcards */ @Override public boolean accept(File file) { if (file.isDirectory()) { return false; } for (String wildcard : wildcards) { if (FilenameUtils.wildcardMatch(file.getName(), wildcard)) { return true; } } return false; } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/filefilter/package.html0000644000175000017500000001102212125050425030460 0ustar ebourgebourg

This package defines an interface (IOFileFilter) that combines both {@link java.io.FileFilter} and {@link java.io.FilenameFilter}. Besides that the package offers a series of ready-to-use implementations of the IOFileFilter interface including implementation that allow you to combine other such filters.

These filter can be used to list files or in {@link java.awt.FileDialog}, for example.

There are a number of 'primitive' filters:

DirectoryFilter Only accept directories
PrefixFileFilter Filter based on a prefix
SuffixFileFilter Filter based on a suffix
NameFileFilter Filter based on a filename
WildcardFileFilter Filter based on wildcards
AgeFileFilter Filter based on last modified time of file
SizeFileFilter Filter based on file size

And there are five 'boolean' filters:

TrueFileFilter Accept all files
FalseFileFilter Accept no files
NotFileFilter Applies a logical NOT to an existing filter
AndFileFilter Combines two filters using a logical AND
OrFileFilter Combines two filter using a logical OR

These boolean FilenameFilters can be nested, to allow arbitrary expressions. For example, here is how one could print all non-directory files in the current directory, starting with "A", and ending in ".java" or ".class":

  File dir = new File(".");
  String[] files = dir.list( 
    new AndFileFilter(
      new AndFileFilter(
        new PrefixFileFilter("A"),
        new OrFileFilter(
          new SuffixFileFilter(".class"),
          new SuffixFileFilter(".java")
        )
      ),
      new NotFileFilter(
        new DirectoryFileFilter()
      )
    )
  );
  for ( int i=0; i<files.length; i++ ) {
    System.out.println(files[i]);
  }

This package also contains a utility class: FileFilterUtils. It allows you to use all file filters without having to put them in the import section. Here's how the above example will look using FileFilterUtils:

  File dir = new File(".");
  String[] files = dir.list( 
    FileFilterUtils.andFileFilter(
      FileFilterUtils.andFileFilter(
        FileFilterUtils.prefixFileFilter("A"),
        FileFilterUtils.orFileFilter(
          FileFilterUtils.suffixFileFilter(".class"),
          FileFilterUtils.suffixFileFilter(".java")
        )
      ),
      FileFilterUtils.notFileFilter(
        FileFilterUtils.directoryFileFilter()
      )
    )
  );
  for ( int i=0; i<files.length; i++ ) {
    System.out.println(files[i]);
  }

There are a few other goodies in that class so please have a look at the documentation in detail.

libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/filefilter/FileFilterUtils.java0000644000175000017500000006721112125050425032123 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.filefilter; import java.io.File; import java.io.FileFilter; import java.io.FilenameFilter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.commons.io.IOCase; /** * Useful utilities for working with file filters. It provides access to all * file filter implementations in this package so you don't have to import * every class you use. * * @since 1.0 * @version $Id: FileFilterUtils.java 1307459 2012-03-30 15:11:44Z ggregory $ */ public class FileFilterUtils { /** * FileFilterUtils is not normally instantiated. */ public FileFilterUtils() { } //----------------------------------------------------------------------- /** *

* Applies an {@link IOFileFilter} to the provided {@link File} * objects. The resulting array is a subset of the original file list that * matches the provided filter. *

* *

* The {@link Set} returned by this method is not guaranteed to be thread safe. *

* *
     * Set<File> allFiles = ...
     * Set<File> javaFiles = FileFilterUtils.filterSet(allFiles,
     *     FileFilterUtils.suffixFileFilter(".java"));
     * 
* @param filter the filter to apply to the set of files. * @param files the array of files to apply the filter to. * * @return a subset of files that is accepted by the * file filter. * @throws IllegalArgumentException if the filter is {@code null} * or files contains a {@code null} value. * * @since 2.0 */ public static File[] filter(IOFileFilter filter, File... files) { if (filter == null) { throw new IllegalArgumentException("file filter is null"); } if (files == null) { return new File[0]; } List acceptedFiles = new ArrayList(); for (File file : files) { if (file == null) { throw new IllegalArgumentException("file array contains null"); } if (filter.accept(file)) { acceptedFiles.add(file); } } return acceptedFiles.toArray(new File[acceptedFiles.size()]); } /** *

* Applies an {@link IOFileFilter} to the provided {@link File} * objects. The resulting array is a subset of the original file list that * matches the provided filter. *

* *

* The {@link Set} returned by this method is not guaranteed to be thread safe. *

* *
     * Set<File> allFiles = ...
     * Set<File> javaFiles = FileFilterUtils.filterSet(allFiles,
     *     FileFilterUtils.suffixFileFilter(".java"));
     * 
* @param filter the filter to apply to the set of files. * @param files the array of files to apply the filter to. * * @return a subset of files that is accepted by the * file filter. * @throws IllegalArgumentException if the filter is {@code null} * or files contains a {@code null} value. * * @since 2.0 */ public static File[] filter(IOFileFilter filter, Iterable files) { List acceptedFiles = filterList(filter, files); return acceptedFiles.toArray(new File[acceptedFiles.size()]); } /** *

* Applies an {@link IOFileFilter} to the provided {@link File} * objects. The resulting list is a subset of the original files that * matches the provided filter. *

* *

* The {@link List} returned by this method is not guaranteed to be thread safe. *

* *
     * List<File> filesAndDirectories = ...
     * List<File> directories = FileFilterUtils.filterList(filesAndDirectories,
     *     FileFilterUtils.directoryFileFilter());
     * 
* @param filter the filter to apply to each files in the list. * @param files the collection of files to apply the filter to. * * @return a subset of files that is accepted by the * file filter. * @throws IllegalArgumentException if the filter is {@code null} * or files contains a {@code null} value. * @since 2.0 */ public static List filterList(IOFileFilter filter, Iterable files) { return filter(filter, files, new ArrayList()); } /** *

* Applies an {@link IOFileFilter} to the provided {@link File} * objects. The resulting list is a subset of the original files that * matches the provided filter. *

* *

* The {@link List} returned by this method is not guaranteed to be thread safe. *

* *
     * List<File> filesAndDirectories = ...
     * List<File> directories = FileFilterUtils.filterList(filesAndDirectories,
     *     FileFilterUtils.directoryFileFilter());
     * 
* @param filter the filter to apply to each files in the list. * @param files the collection of files to apply the filter to. * * @return a subset of files that is accepted by the * file filter. * @throws IllegalArgumentException if the filter is {@code null} * or files contains a {@code null} value. * @since 2.0 */ public static List filterList(IOFileFilter filter, File... files) { File[] acceptedFiles = filter(filter, files); return Arrays.asList(acceptedFiles); } /** *

* Applies an {@link IOFileFilter} to the provided {@link File} * objects. The resulting set is a subset of the original file list that * matches the provided filter. *

* *

* The {@link Set} returned by this method is not guaranteed to be thread safe. *

* *
     * Set<File> allFiles = ...
     * Set<File> javaFiles = FileFilterUtils.filterSet(allFiles,
     *     FileFilterUtils.suffixFileFilter(".java"));
     * 
* @param filter the filter to apply to the set of files. * @param files the collection of files to apply the filter to. * * @return a subset of files that is accepted by the * file filter. * @throws IllegalArgumentException if the filter is {@code null} * or files contains a {@code null} value. * * @since 2.0 */ public static Set filterSet(IOFileFilter filter, File... files) { File[] acceptedFiles = filter(filter, files); return new HashSet(Arrays.asList(acceptedFiles)); } /** *

* Applies an {@link IOFileFilter} to the provided {@link File} * objects. The resulting set is a subset of the original file list that * matches the provided filter. *

* *

* The {@link Set} returned by this method is not guaranteed to be thread safe. *

* *
     * Set<File> allFiles = ...
     * Set<File> javaFiles = FileFilterUtils.filterSet(allFiles,
     *     FileFilterUtils.suffixFileFilter(".java"));
     * 
* @param filter the filter to apply to the set of files. * @param files the collection of files to apply the filter to. * * @return a subset of files that is accepted by the * file filter. * @throws IllegalArgumentException if the filter is {@code null} * or files contains a {@code null} value. * * @since 2.0 */ public static Set filterSet(IOFileFilter filter, Iterable files) { return filter(filter, files, new HashSet()); } /** *

* Applies an {@link IOFileFilter} to the provided {@link File} * objects and appends the accepted files to the other supplied collection. *

* *
     * List<File> files = ...
     * List<File> directories = FileFilterUtils.filterList(files,
     *     FileFilterUtils.sizeFileFilter(FileUtils.FIFTY_MB), 
     *         new ArrayList<File>());
     * 
* @param filter the filter to apply to the collection of files. * @param files the collection of files to apply the filter to. * @param acceptedFiles the list of files to add accepted files to. * * @param the type of the file collection. * @return a subset of files that is accepted by the * file filter. * @throws IllegalArgumentException if the filter is {@code null} * or files contains a {@code null} value. */ private static > T filter(IOFileFilter filter, Iterable files, T acceptedFiles) { if (filter == null) { throw new IllegalArgumentException("file filter is null"); } if (files != null) { for (File file : files) { if (file == null) { throw new IllegalArgumentException("file collection contains null"); } if (filter.accept(file)) { acceptedFiles.add(file); } } } return acceptedFiles; } /** * Returns a filter that returns true if the filename starts with the specified text. * * @param prefix the filename prefix * @return a prefix checking filter * @see PrefixFileFilter */ public static IOFileFilter prefixFileFilter(String prefix) { return new PrefixFileFilter(prefix); } /** * Returns a filter that returns true if the filename starts with the specified text. * * @param prefix the filename prefix * @param caseSensitivity how to handle case sensitivity, null means case-sensitive * @return a prefix checking filter * @see PrefixFileFilter * @since 2.0 */ public static IOFileFilter prefixFileFilter(String prefix, IOCase caseSensitivity) { return new PrefixFileFilter(prefix, caseSensitivity); } /** * Returns a filter that returns true if the filename ends with the specified text. * * @param suffix the filename suffix * @return a suffix checking filter * @see SuffixFileFilter */ public static IOFileFilter suffixFileFilter(String suffix) { return new SuffixFileFilter(suffix); } /** * Returns a filter that returns true if the filename ends with the specified text. * * @param suffix the filename suffix * @param caseSensitivity how to handle case sensitivity, null means case-sensitive * @return a suffix checking filter * @see SuffixFileFilter * @since 2.0 */ public static IOFileFilter suffixFileFilter(String suffix, IOCase caseSensitivity) { return new SuffixFileFilter(suffix, caseSensitivity); } /** * Returns a filter that returns true if the filename matches the specified text. * * @param name the filename * @return a name checking filter * @see NameFileFilter */ public static IOFileFilter nameFileFilter(String name) { return new NameFileFilter(name); } /** * Returns a filter that returns true if the filename matches the specified text. * * @param name the filename * @param caseSensitivity how to handle case sensitivity, null means case-sensitive * @return a name checking filter * @see NameFileFilter * @since 2.0 */ public static IOFileFilter nameFileFilter(String name, IOCase caseSensitivity) { return new NameFileFilter(name, caseSensitivity); } /** * Returns a filter that checks if the file is a directory. * * @return file filter that accepts only directories and not files * @see DirectoryFileFilter#DIRECTORY */ public static IOFileFilter directoryFileFilter() { return DirectoryFileFilter.DIRECTORY; } /** * Returns a filter that checks if the file is a file (and not a directory). * * @return file filter that accepts only files and not directories * @see FileFileFilter#FILE */ public static IOFileFilter fileFileFilter() { return FileFileFilter.FILE; } //----------------------------------------------------------------------- /** * Returns a filter that ANDs the two specified filters. * * @param filter1 the first filter * @param filter2 the second filter * @return a filter that ANDs the two specified filters * @see #and(IOFileFilter...) * @see AndFileFilter * @deprecated use {@link #and(IOFileFilter...)} */ @Deprecated public static IOFileFilter andFileFilter(IOFileFilter filter1, IOFileFilter filter2) { return new AndFileFilter(filter1, filter2); } /** * Returns a filter that ORs the two specified filters. * * @param filter1 the first filter * @param filter2 the second filter * @return a filter that ORs the two specified filters * @see #or(IOFileFilter...) * @see OrFileFilter * @deprecated use {@link #or(IOFileFilter...)} */ @Deprecated public static IOFileFilter orFileFilter(IOFileFilter filter1, IOFileFilter filter2) { return new OrFileFilter(filter1, filter2); } /** * Returns a filter that ANDs the specified filters. * * @param filters the IOFileFilters that will be ANDed together. * @return a filter that ANDs the specified filters * * @throws IllegalArgumentException if the filters are null or contain a * null value. * @see AndFileFilter * @since 2.0 */ public static IOFileFilter and(IOFileFilter... filters) { return new AndFileFilter(toList(filters)); } /** * Returns a filter that ORs the specified filters. * * @param filters the IOFileFilters that will be ORed together. * @return a filter that ORs the specified filters * * @throws IllegalArgumentException if the filters are null or contain a * null value. * @see OrFileFilter * @since 2.0 */ public static IOFileFilter or(IOFileFilter... filters) { return new OrFileFilter(toList(filters)); } /** * Create a List of file filters. * * @param filters The file filters * @return The list of file filters * @throws IllegalArgumentException if the filters are null or contain a * null value. * @since 2.0 */ public static List toList(IOFileFilter... filters) { if (filters == null) { throw new IllegalArgumentException("The filters must not be null"); } List list = new ArrayList(filters.length); for (int i = 0; i < filters.length; i++) { if (filters[i] == null) { throw new IllegalArgumentException("The filter[" + i + "] is null"); } list.add(filters[i]); } return list; } /** * Returns a filter that NOTs the specified filter. * * @param filter the filter to invert * @return a filter that NOTs the specified filter * @see NotFileFilter */ public static IOFileFilter notFileFilter(IOFileFilter filter) { return new NotFileFilter(filter); } //----------------------------------------------------------------------- /** * Returns a filter that always returns true. * * @return a true filter * @see TrueFileFilter#TRUE */ public static IOFileFilter trueFileFilter() { return TrueFileFilter.TRUE; } /** * Returns a filter that always returns false. * * @return a false filter * @see FalseFileFilter#FALSE */ public static IOFileFilter falseFileFilter() { return FalseFileFilter.FALSE; } //----------------------------------------------------------------------- /** * Returns an IOFileFilter that wraps the * FileFilter instance. * * @param filter the filter to be wrapped * @return a new filter that implements IOFileFilter * @see DelegateFileFilter */ public static IOFileFilter asFileFilter(FileFilter filter) { return new DelegateFileFilter(filter); } /** * Returns an IOFileFilter that wraps the * FilenameFilter instance. * * @param filter the filter to be wrapped * @return a new filter that implements IOFileFilter * @see DelegateFileFilter */ public static IOFileFilter asFileFilter(FilenameFilter filter) { return new DelegateFileFilter(filter); } //----------------------------------------------------------------------- /** * Returns a filter that returns true if the file was last modified after * the specified cutoff time. * * @param cutoff the time threshold * @return an appropriately configured age file filter * @see AgeFileFilter * @since 1.2 */ public static IOFileFilter ageFileFilter(long cutoff) { return new AgeFileFilter(cutoff); } /** * Returns a filter that filters files based on a cutoff time. * * @param cutoff the time threshold * @param acceptOlder if true, older files get accepted, if false, newer * @return an appropriately configured age file filter * @see AgeFileFilter * @since 1.2 */ public static IOFileFilter ageFileFilter(long cutoff, boolean acceptOlder) { return new AgeFileFilter(cutoff, acceptOlder); } /** * Returns a filter that returns true if the file was last modified after * the specified cutoff date. * * @param cutoffDate the time threshold * @return an appropriately configured age file filter * @see AgeFileFilter * @since 1.2 */ public static IOFileFilter ageFileFilter(Date cutoffDate) { return new AgeFileFilter(cutoffDate); } /** * Returns a filter that filters files based on a cutoff date. * * @param cutoffDate the time threshold * @param acceptOlder if true, older files get accepted, if false, newer * @return an appropriately configured age file filter * @see AgeFileFilter * @since 1.2 */ public static IOFileFilter ageFileFilter(Date cutoffDate, boolean acceptOlder) { return new AgeFileFilter(cutoffDate, acceptOlder); } /** * Returns a filter that returns true if the file was last modified after * the specified reference file. * * @param cutoffReference the file whose last modification * time is usesd as the threshold age of the files * @return an appropriately configured age file filter * @see AgeFileFilter * @since 1.2 */ public static IOFileFilter ageFileFilter(File cutoffReference) { return new AgeFileFilter(cutoffReference); } /** * Returns a filter that filters files based on a cutoff reference file. * * @param cutoffReference the file whose last modification * time is usesd as the threshold age of the files * @param acceptOlder if true, older files get accepted, if false, newer * @return an appropriately configured age file filter * @see AgeFileFilter * @since 1.2 */ public static IOFileFilter ageFileFilter(File cutoffReference, boolean acceptOlder) { return new AgeFileFilter(cutoffReference, acceptOlder); } //----------------------------------------------------------------------- /** * Returns a filter that returns true if the file is bigger than a certain size. * * @param threshold the file size threshold * @return an appropriately configured SizeFileFilter * @see SizeFileFilter * @since 1.2 */ public static IOFileFilter sizeFileFilter(long threshold) { return new SizeFileFilter(threshold); } /** * Returns a filter that filters based on file size. * * @param threshold the file size threshold * @param acceptLarger if true, larger files get accepted, if false, smaller * @return an appropriately configured SizeFileFilter * @see SizeFileFilter * @since 1.2 */ public static IOFileFilter sizeFileFilter(long threshold, boolean acceptLarger) { return new SizeFileFilter(threshold, acceptLarger); } /** * Returns a filter that accepts files whose size is >= minimum size * and <= maximum size. * * @param minSizeInclusive the minimum file size (inclusive) * @param maxSizeInclusive the maximum file size (inclusive) * @return an appropriately configured IOFileFilter * @see SizeFileFilter * @since 1.3 */ public static IOFileFilter sizeRangeFileFilter(long minSizeInclusive, long maxSizeInclusive ) { IOFileFilter minimumFilter = new SizeFileFilter(minSizeInclusive, true); IOFileFilter maximumFilter = new SizeFileFilter(maxSizeInclusive + 1L, false); return new AndFileFilter(minimumFilter, maximumFilter); } /** * Returns a filter that accepts files that begin with the provided magic * number. * * @param magicNumber the magic number (byte sequence) to match at the * beginning of each file. * * @return an IOFileFilter that accepts files beginning with the provided * magic number. * * @throws IllegalArgumentException if magicNumber is * {@code null} or the empty String. * @see MagicNumberFileFilter * @since 2.0 */ public static IOFileFilter magicNumberFileFilter(String magicNumber) { return new MagicNumberFileFilter(magicNumber); } /** * Returns a filter that accepts files that contains the provided magic * number at a specified offset within the file. * * @param magicNumber the magic number (byte sequence) to match at the * provided offset in each file. * @param offset the offset within the files to look for the magic number. * * @return an IOFileFilter that accepts files containing the magic number * at the specified offset. * * @throws IllegalArgumentException if magicNumber is * {@code null} or the empty String, or if offset is a * negative number. * @see MagicNumberFileFilter * @since 2.0 */ public static IOFileFilter magicNumberFileFilter(String magicNumber, long offset) { return new MagicNumberFileFilter(magicNumber, offset); } /** * Returns a filter that accepts files that begin with the provided magic * number. * * @param magicNumber the magic number (byte sequence) to match at the * beginning of each file. * * @return an IOFileFilter that accepts files beginning with the provided * magic number. * * @throws IllegalArgumentException if magicNumber is * {@code null} or is of length zero. * @see MagicNumberFileFilter * @since 2.0 */ public static IOFileFilter magicNumberFileFilter(byte[] magicNumber) { return new MagicNumberFileFilter(magicNumber); } /** * Returns a filter that accepts files that contains the provided magic * number at a specified offset within the file. * * @param magicNumber the magic number (byte sequence) to match at the * provided offset in each file. * @param offset the offset within the files to look for the magic number. * * @return an IOFileFilter that accepts files containing the magic number * at the specified offset. * * @throws IllegalArgumentException if magicNumber is * {@code null}, or contains no bytes, or offset * is a negative number. * @see MagicNumberFileFilter * @since 2.0 */ public static IOFileFilter magicNumberFileFilter(byte[] magicNumber, long offset) { return new MagicNumberFileFilter(magicNumber, offset); } //----------------------------------------------------------------------- /* Constructed on demand and then cached */ private static final IOFileFilter cvsFilter = notFileFilter( and(directoryFileFilter(), nameFileFilter("CVS"))); /* Constructed on demand and then cached */ private static final IOFileFilter svnFilter = notFileFilter( and(directoryFileFilter(), nameFileFilter(".svn"))); /** * Decorates a filter to make it ignore CVS directories. * Passing in {@code null} will return a filter that accepts everything * except CVS directories. * * @param filter the filter to decorate, null means an unrestricted filter * @return the decorated filter, never null * @since 1.1 (method existed but had bug in 1.0) */ public static IOFileFilter makeCVSAware(IOFileFilter filter) { if (filter == null) { return cvsFilter; } else { return and(filter, cvsFilter); } } /** * Decorates a filter to make it ignore SVN directories. * Passing in {@code null} will return a filter that accepts everything * except SVN directories. * * @param filter the filter to decorate, null means an unrestricted filter * @return the decorated filter, never null * @since 1.1 */ public static IOFileFilter makeSVNAware(IOFileFilter filter) { if (filter == null) { return svnFilter; } else { return and(filter, svnFilter); } } //----------------------------------------------------------------------- /** * Decorates a filter so that it only applies to directories and not to files. * * @param filter the filter to decorate, null means an unrestricted filter * @return the decorated filter, never null * @see DirectoryFileFilter#DIRECTORY * @since 1.3 */ public static IOFileFilter makeDirectoryOnly(IOFileFilter filter) { if (filter == null) { return DirectoryFileFilter.DIRECTORY; } return new AndFileFilter(DirectoryFileFilter.DIRECTORY, filter); } /** * Decorates a filter so that it only applies to files and not to directories. * * @param filter the filter to decorate, null means an unrestricted filter * @return the decorated filter, never null * @see FileFileFilter#FILE * @since 1.3 */ public static IOFileFilter makeFileOnly(IOFileFilter filter) { if (filter == null) { return FileFileFilter.FILE; } return new AndFileFilter(FileFileFilter.FILE, filter); } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/FileCleaningTracker.java0000644000175000017500000002541712125050425030566 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.io.File; import java.lang.ref.PhantomReference; import java.lang.ref.ReferenceQueue; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; /** * Keeps track of files awaiting deletion, and deletes them when an associated * marker object is reclaimed by the garbage collector. *

* This utility creates a background thread to handle file deletion. * Each file to be deleted is registered with a handler object. * When the handler object is garbage collected, the file is deleted. *

* In an environment with multiple class loaders (a servlet container, for * example), you should consider stopping the background thread if it is no * longer needed. This is done by invoking the method * {@link #exitWhenFinished}, typically in * {@link javax.servlet.ServletContextListener#contextDestroyed} or similar. * * @version $Id: FileCleaningTracker.java 1307462 2012-03-30 15:13:11Z ggregory $ */ public class FileCleaningTracker { /** * Queue of Tracker instances being watched. */ ReferenceQueue q = new ReferenceQueue(); /** * Collection of Tracker instances in existence. */ final Collection trackers = Collections.synchronizedSet(new HashSet()); // synchronized /** * Collection of File paths that failed to delete. */ final List deleteFailures = Collections.synchronizedList(new ArrayList()); /** * Whether to terminate the thread when the tracking is complete. */ volatile boolean exitWhenFinished = false; /** * The thread that will clean up registered files. */ Thread reaper; //----------------------------------------------------------------------- /** * Track the specified file, using the provided marker, deleting the file * when the marker instance is garbage collected. * The {@link FileDeleteStrategy#NORMAL normal} deletion strategy will be used. * * @param file the file to be tracked, not null * @param marker the marker object used to track the file, not null * @throws NullPointerException if the file is null */ public void track(File file, Object marker) { track(file, marker, (FileDeleteStrategy) null); } /** * Track the specified file, using the provided marker, deleting the file * when the marker instance is garbage collected. * The speified deletion strategy is used. * * @param file the file to be tracked, not null * @param marker the marker object used to track the file, not null * @param deleteStrategy the strategy to delete the file, null means normal * @throws NullPointerException if the file is null */ public void track(File file, Object marker, FileDeleteStrategy deleteStrategy) { if (file == null) { throw new NullPointerException("The file must not be null"); } addTracker(file.getPath(), marker, deleteStrategy); } /** * Track the specified file, using the provided marker, deleting the file * when the marker instance is garbage collected. * The {@link FileDeleteStrategy#NORMAL normal} deletion strategy will be used. * * @param path the full path to the file to be tracked, not null * @param marker the marker object used to track the file, not null * @throws NullPointerException if the path is null */ public void track(String path, Object marker) { track(path, marker, (FileDeleteStrategy) null); } /** * Track the specified file, using the provided marker, deleting the file * when the marker instance is garbage collected. * The speified deletion strategy is used. * * @param path the full path to the file to be tracked, not null * @param marker the marker object used to track the file, not null * @param deleteStrategy the strategy to delete the file, null means normal * @throws NullPointerException if the path is null */ public void track(String path, Object marker, FileDeleteStrategy deleteStrategy) { if (path == null) { throw new NullPointerException("The path must not be null"); } addTracker(path, marker, deleteStrategy); } /** * Adds a tracker to the list of trackers. * * @param path the full path to the file to be tracked, not null * @param marker the marker object used to track the file, not null * @param deleteStrategy the strategy to delete the file, null means normal */ private synchronized void addTracker(String path, Object marker, FileDeleteStrategy deleteStrategy) { // synchronized block protects reaper if (exitWhenFinished) { throw new IllegalStateException("No new trackers can be added once exitWhenFinished() is called"); } if (reaper == null) { reaper = new Reaper(); reaper.start(); } trackers.add(new Tracker(path, deleteStrategy, marker, q)); } //----------------------------------------------------------------------- /** * Retrieve the number of files currently being tracked, and therefore * awaiting deletion. * * @return the number of files being tracked */ public int getTrackCount() { return trackers.size(); } /** * Return the file paths that failed to delete. * * @return the file paths that failed to delete * @since 2.0 */ public List getDeleteFailures() { return deleteFailures; } /** * Call this method to cause the file cleaner thread to terminate when * there are no more objects being tracked for deletion. *

* In a simple environment, you don't need this method as the file cleaner * thread will simply exit when the JVM exits. In a more complex environment, * with multiple class loaders (such as an application server), you should be * aware that the file cleaner thread will continue running even if the class * loader it was started from terminates. This can consitute a memory leak. *

* For example, suppose that you have developed a web application, which * contains the commons-io jar file in your WEB-INF/lib directory. In other * words, the FileCleaner class is loaded through the class loader of your * web application. If the web application is terminated, but the servlet * container is still running, then the file cleaner thread will still exist, * posing a memory leak. *

* This method allows the thread to be terminated. Simply call this method * in the resource cleanup code, such as {@link javax.servlet.ServletContextListener#contextDestroyed}. * Once called, no new objects can be tracked by the file cleaner. */ public synchronized void exitWhenFinished() { // synchronized block protects reaper exitWhenFinished = true; if (reaper != null) { synchronized (reaper) { reaper.interrupt(); } } } //----------------------------------------------------------------------- /** * The reaper thread. */ private final class Reaper extends Thread { /** Construct a new Reaper */ Reaper() { super("File Reaper"); setPriority(Thread.MAX_PRIORITY); setDaemon(true); } /** * Run the reaper thread that will delete files as their associated * marker objects are reclaimed by the garbage collector. */ @Override public void run() { // thread exits when exitWhenFinished is true and there are no more tracked objects while (exitWhenFinished == false || trackers.size() > 0) { try { // Wait for a tracker to remove. Tracker tracker = (Tracker) q.remove(); // cannot return null trackers.remove(tracker); if (!tracker.delete()) { deleteFailures.add(tracker.getPath()); } tracker.clear(); } catch (InterruptedException e) { continue; } } } } //----------------------------------------------------------------------- /** * Inner class which acts as the reference for a file pending deletion. */ private static final class Tracker extends PhantomReference { /** * The full path to the file being tracked. */ private final String path; /** * The strategy for deleting files. */ private final FileDeleteStrategy deleteStrategy; /** * Constructs an instance of this class from the supplied parameters. * * @param path the full path to the file to be tracked, not null * @param deleteStrategy the strategy to delete the file, null means normal * @param marker the marker object used to track the file, not null * @param queue the queue on to which the tracker will be pushed, not null */ Tracker(String path, FileDeleteStrategy deleteStrategy, Object marker, ReferenceQueue queue) { super(marker, queue); this.path = path; this.deleteStrategy = deleteStrategy == null ? FileDeleteStrategy.NORMAL : deleteStrategy; } /** * Return the path. * * @return the path */ public String getPath() { return path; } /** * Deletes the file associated with this tracker instance. * * @return {@code true} if the file was deleted successfully; * {@code false} otherwise. */ public boolean delete() { return deleteStrategy.deleteQuietly(new File(path)); } } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/FileUtils.java0000644000175000017500000035114712125050425026634 0ustar ebourgebourg/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.net.URL; import java.net.URLConnection; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.charset.Charset; import java.nio.charset.UnsupportedCharsetException; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.zip.CRC32; import java.util.zip.CheckedInputStream; import java.util.zip.Checksum; import org.apache.commons.io.filefilter.DirectoryFileFilter; import org.apache.commons.io.filefilter.FalseFileFilter; import org.apache.commons.io.filefilter.FileFilterUtils; import org.apache.commons.io.filefilter.IOFileFilter; import org.apache.commons.io.filefilter.SuffixFileFilter; import org.apache.commons.io.filefilter.TrueFileFilter; import org.apache.commons.io.output.NullOutputStream; /** * General file manipulation utilities. *

* Facilities are provided in the following areas: *

    *
  • writing to a file *
  • reading from a file *
  • make a directory including parent directories *
  • copying files and directories *
  • deleting files and directories *
  • converting to and from a URL *
  • listing files and directories by filter and extension *
  • comparing file content *
  • file last changed date *
  • calculating a checksum *
*

* Origin of code: Excalibur, Alexandria, Commons-Utils * * @version $Id: FileUtils.java 1349509 2012-06-12 20:39:23Z ggregory $ */ public class FileUtils { /** * Instances should NOT be constructed in standard programming. */ public FileUtils() { super(); } /** * The number of bytes in a kilobyte. */ public static final long ONE_KB = 1024; /** * The number of bytes in a kilobyte. * * @since 2.4 */ public static final BigInteger ONE_KB_BI = BigInteger.valueOf(ONE_KB); /** * The number of bytes in a megabyte. */ public static final long ONE_MB = ONE_KB * ONE_KB; /** * The number of bytes in a megabyte. * * @since 2.4 */ public static final BigInteger ONE_MB_BI = ONE_KB_BI.multiply(ONE_KB_BI); /** * The file copy buffer size (30 MB) */ private static final long FILE_COPY_BUFFER_SIZE = ONE_MB * 30; /** * The number of bytes in a gigabyte. */ public static final long ONE_GB = ONE_KB * ONE_MB; /** * The number of bytes in a gigabyte. * * @since 2.4 */ public static final BigInteger ONE_GB_BI = ONE_KB_BI.multiply(ONE_MB_BI); /** * The number of bytes in a terabyte. */ public static final long ONE_TB = ONE_KB * ONE_GB; /** * The number of bytes in a terabyte. * * @since 2.4 */ public static final BigInteger ONE_TB_BI = ONE_KB_BI.multiply(ONE_GB_BI); /** * The number of bytes in a petabyte. */ public static final long ONE_PB = ONE_KB * ONE_TB; /** * The number of bytes in a petabyte. * * @since 2.4 */ public static final BigInteger ONE_PB_BI = ONE_KB_BI.multiply(ONE_TB_BI); /** * The number of bytes in an exabyte. */ public static final long ONE_EB = ONE_KB * ONE_PB; /** * The number of bytes in an exabyte. * * @since 2.4 */ public static final BigInteger ONE_EB_BI = ONE_KB_BI.multiply(ONE_PB_BI); /** * The number of bytes in a zettabyte. */ public static final BigInteger ONE_ZB = BigInteger.valueOf(ONE_KB).multiply(BigInteger.valueOf(ONE_EB)); /** * The number of bytes in a yottabyte. */ public static final BigInteger ONE_YB = ONE_KB_BI.multiply(ONE_ZB); /** * An empty array of type File. */ public static final File[] EMPTY_FILE_ARRAY = new File[0]; /** * The UTF-8 character set, used to decode octets in URLs. */ private static final Charset UTF8 = Charset.forName("UTF-8"); //----------------------------------------------------------------------- /** * Construct a file from the set of name elements. * * @param directory the parent directory * @param names the name elements * @return the file * @since 2.1 */ public static File getFile(File directory, String... names) { if (directory == null) { throw new NullPointerException("directorydirectory must not be null"); } if (names == null) { throw new NullPointerException("names must not be null"); } File file = directory; for (String name : names) { file = new File(file, name); } return file; } /** * Construct a file from the set of name elements. * * @param names the name elements * @return the file * @since 2.1 */ public static File getFile(String... names) { if (names == null) { throw new NullPointerException("names must not be null"); } File file = null; for (String name : names) { if (file == null) { file = new File(name); } else { file = new File(file, name); } } return file; } /** * Returns the path to the system temporary directory. * * @return the path to the system temporary directory. * * @since 2.0 */ public static String getTempDirectoryPath() { return System.getProperty("java.io.tmpdir"); } /** * Returns a {@link File} representing the system temporary directory. * * @return the system temporary directory. * * @since 2.0 */ public static File getTempDirectory() { return new File(getTempDirectoryPath()); } /** * Returns the path to the user's home directory. * * @return the path to the user's home directory. * * @since 2.0 */ public static String getUserDirectoryPath() { return System.getProperty("user.home"); } /** * Returns a {@link File} representing the user's home directory. * * @return the user's home directory. * * @since 2.0 */ public static File getUserDirectory() { return new File(getUserDirectoryPath()); } //----------------------------------------------------------------------- /** * Opens a {@link FileInputStream} for the specified file, providing better * error messages than simply calling new FileInputStream(file). *

* At the end of the method either the stream will be successfully opened, * or an exception will have been thrown. *

* An exception is thrown if the file does not exist. * An exception is thrown if the file object exists but is a directory. * An exception is thrown if the file exists but cannot be read. * * @param file the file to open for input, must not be {@code null} * @return a new {@link FileInputStream} for the specified file * @throws FileNotFoundException if the file does not exist * @throws IOException if the file object is a directory * @throws IOException if the file cannot be read * @since 1.3 */ public static FileInputStream openInputStream(File file) throws IOException { if (file.exists()) { if (file.isDirectory()) { throw new IOException("File '" + file + "' exists but is a directory"); } if (file.canRead() == false) { throw new IOException("File '" + file + "' cannot be read"); } } else { throw new FileNotFoundException("File '" + file + "' does not exist"); } return new FileInputStream(file); } //----------------------------------------------------------------------- /** * Opens a {@link FileOutputStream} for the specified file, checking and * creating the parent directory if it does not exist. *

* At the end of the method either the stream will be successfully opened, * or an exception will have been thrown. *

* The parent directory will be created if it does not exist. * The file will be created if it does not exist. * An exception is thrown if the file object exists but is a directory. * An exception is thrown if the file exists but cannot be written to. * An exception is thrown if the parent directory cannot be created. * * @param file the file to open for output, must not be {@code null} * @return a new {@link FileOutputStream} for the specified file * @throws IOException if the file object is a directory * @throws IOException if the file cannot be written to * @throws IOException if a parent directory needs creating but that fails * @since 1.3 */ public static FileOutputStream openOutputStream(File file) throws IOException { return openOutputStream(file, false); } /** * Opens a {@link FileOutputStream} for the specified file, checking and * creating the parent directory if it does not exist. *

* At the end of the method either the stream will be successfully opened, * or an exception will have been thrown. *

* The parent directory will be created if it does not exist. * The file will be created if it does not exist. * An exception is thrown if the file object exists but is a directory. * An exception is thrown if the file exists but cannot be written to. * An exception is thrown if the parent directory cannot be created. * * @param file the file to open for output, must not be {@code null} * @param append if {@code true}, then bytes will be added to the * end of the file rather than overwriting * @return a new {@link FileOutputStream} for the specified file * @throws IOException if the file object is a directory * @throws IOException if the file cannot be written to * @throws IOException if a parent directory needs creating but that fails * @since 2.1 */ public static FileOutputStream openOutputStream(File file, boolean append) throws IOException { if (file.exists()) { if (file.isDirectory()) { throw new IOException("File '" + file + "' exists but is a directory"); } if (file.canWrite() == false) { throw new IOException("File '" + file + "' cannot be written to"); } } else { File parent = file.getParentFile(); if (parent != null) { if (!parent.mkdirs() && !parent.isDirectory()) { throw new IOException("Directory '" + parent + "' could not be created"); } } } return new FileOutputStream(file, append); } //----------------------------------------------------------------------- /** * Returns a human-readable version of the file size, where the input represents a specific number of bytes. *

* If the size is over 1GB, the size is returned as the number of whole GB, i.e. the size is rounded down to the * nearest GB boundary. *

*

* Similarly for the 1MB and 1KB boundaries. *

* * @param size * the number of bytes * @return a human-readable display value (includes units - EB, PB, TB, GB, MB, KB or bytes) * @see IO-226 - should the rounding be changed? * @since 2.4 */ // See https://issues.apache.org/jira/browse/IO-226 - should the rounding be changed? public static String byteCountToDisplaySize(BigInteger size) { String displaySize; if (size.divide(ONE_EB_BI).compareTo(BigInteger.ZERO) > 0) { displaySize = String.valueOf(size.divide(ONE_EB_BI)) + " EB"; } else if (size.divide(ONE_PB_BI).compareTo(BigInteger.ZERO) > 0) { displaySize = String.valueOf(size.divide(ONE_PB_BI)) + " PB"; } else if (size.divide(ONE_TB_BI).compareTo(BigInteger.ZERO) > 0) { displaySize = String.valueOf(size.divide(ONE_TB_BI)) + " TB"; } else if (size.divide(ONE_GB_BI).compareTo(BigInteger.ZERO) > 0) { displaySize = String.valueOf(size.divide(ONE_GB_BI)) + " GB"; } else if (size.divide(ONE_MB_BI).compareTo(BigInteger.ZERO) > 0) { displaySize = String.valueOf(size.divide(ONE_MB_BI)) + " MB"; } else if (size.divide(ONE_KB_BI).compareTo(BigInteger.ZERO) > 0) { displaySize = String.valueOf(size.divide(ONE_KB_BI)) + " KB"; } else { displaySize = String.valueOf(size) + " bytes"; } return displaySize; } /** * Returns a human-readable version of the file size, where the input represents a specific number of bytes. *

* If the size is over 1GB, the size is returned as the number of whole GB, i.e. the size is rounded down to the * nearest GB boundary. *

*

* Similarly for the 1MB and 1KB boundaries. *

* * @param size * the number of bytes * @return a human-readable display value (includes units - EB, PB, TB, GB, MB, KB or bytes) * @see IO-226 - should the rounding be changed? */ // See https://issues.apache.org/jira/browse/IO-226 - should the rounding be changed? public static String byteCountToDisplaySize(long size) { return byteCountToDisplaySize(BigInteger.valueOf(size)); } //----------------------------------------------------------------------- /** * Implements the same behaviour as the "touch" utility on Unix. It creates * a new file with size 0 or, if the file exists already, it is opened and * closed without modifying it, but updating the file date and time. *

* NOTE: As from v1.3, this method throws an IOException if the last * modified date of the file cannot be set. Also, as from v1.3 this method * creates parent directories if they do not exist. * * @param file the File to touch * @throws IOException If an I/O problem occurs */ public static void touch(File file) throws IOException { if (!file.exists()) { OutputStream out = openOutputStream(file); IOUtils.closeQuietly(out); } boolean success = file.setLastModified(System.currentTimeMillis()); if (!success) { throw new IOException("Unable to set the last modification time for " + file); } } //----------------------------------------------------------------------- /** * Converts a Collection containing java.io.File instanced into array * representation. This is to account for the difference between * File.listFiles() and FileUtils.listFiles(). * * @param files a Collection containing java.io.File instances * @return an array of java.io.File */ public static File[] convertFileCollectionToFileArray(Collection files) { return files.toArray(new File[files.size()]); } //----------------------------------------------------------------------- /** * Finds files within a given directory (and optionally its * subdirectories). All files found are filtered by an IOFileFilter. * * @param files the collection of files found. * @param directory the directory to search in. * @param filter the filter to apply to files and directories. * @param includeSubDirectories indicates if will include the subdirectories themselves */ private static void innerListFiles(Collection files, File directory, IOFileFilter filter, boolean includeSubDirectories) { File[] found = directory.listFiles((FileFilter) filter); if (found != null) { for (File file : found) { if (file.isDirectory()) { if (includeSubDirectories) { files.add(file); } innerListFiles(files, file, filter, includeSubDirectories); } else { files.add(file); } } } } /** * Finds files within a given directory (and optionally its * subdirectories). All files found are filtered by an IOFileFilter. *

* If your search should recurse into subdirectories you can pass in * an IOFileFilter for directories. You don't need to bind a * DirectoryFileFilter (via logical AND) to this filter. This method does * that for you. *

* An example: If you want to search through all directories called * "temp" you pass in FileFilterUtils.NameFileFilter("temp") *

* Another common usage of this method is find files in a directory * tree but ignoring the directories generated CVS. You can simply pass * in FileFilterUtils.makeCVSAware(null). * * @param directory the directory to search in * @param fileFilter filter to apply when finding files. * @param dirFilter optional filter to apply when finding subdirectories. * If this parameter is {@code null}, subdirectories will not be included in the * search. Use TrueFileFilter.INSTANCE to match all directories. * @return an collection of java.io.File with the matching files * @see org.apache.commons.io.filefilter.FileFilterUtils * @see org.apache.commons.io.filefilter.NameFileFilter */ public static Collection listFiles( File directory, IOFileFilter fileFilter, IOFileFilter dirFilter) { validateListFilesParameters(directory, fileFilter); IOFileFilter effFileFilter = setUpEffectiveFileFilter(fileFilter); IOFileFilter effDirFilter = setUpEffectiveDirFilter(dirFilter); //Find files Collection files = new java.util.LinkedList(); innerListFiles(files, directory, FileFilterUtils.or(effFileFilter, effDirFilter), false); return files; } /** * Validates the given arguments. *

    *
  • Throws {@link IllegalArgumentException} if {@code directory} is not a directory
  • *
  • Throws {@link NullPointerException} if {@code fileFilter} is null
  • *
* * @param directory The File to test * @param fileFilter The IOFileFilter to test */ private static void validateListFilesParameters(File directory, IOFileFilter fileFilter) { if (!directory.isDirectory()) { throw new IllegalArgumentException("Parameter 'directory' is not a directory"); } if (fileFilter == null) { throw new NullPointerException("Parameter 'fileFilter' is null"); } } /** * Returns a filter that accepts files in addition to the {@link File} objects accepted by the given filter. * * @param fileFilter a base filter to add to * @return a filter that accepts files */ private static IOFileFilter setUpEffectiveFileFilter(IOFileFilter fileFilter) { return FileFilterUtils.and(fileFilter, FileFilterUtils.notFileFilter(DirectoryFileFilter.INSTANCE)); } /** * Returns a filter that accepts directories in addition to the {@link File} objects accepted by the given filter. * * @param dirFilter a base filter to add to * @return a filter that accepts directories */ private static IOFileFilter setUpEffectiveDirFilter(IOFileFilter dirFilter) { return dirFilter == null ? FalseFileFilter.INSTANCE : FileFilterUtils.and(dirFilter, DirectoryFileFilter.INSTANCE); } /** * Finds files within a given directory (and optionally its * subdirectories). All files found are filtered by an IOFileFilter. *

* The resulting collection includes the subdirectories themselves. *

* @see org.apache.commons.io.FileUtils#listFiles * * @param directory the directory to search in * @param fileFilter filter to apply when finding files. * @param dirFilter optional filter to apply when finding subdirectories. * If this parameter is {@code null}, subdirectories will not be included in the * search. Use TrueFileFilter.INSTANCE to match all directories. * @return an collection of java.io.File with the matching files * @see org.apache.commons.io.filefilter.FileFilterUtils * @see org.apache.commons.io.filefilter.NameFileFilter * @since 2.2 */ public static Collection listFilesAndDirs( File directory, IOFileFilter fileFilter, IOFileFilter dirFilter) { validateListFilesParameters(directory, fileFilter); IOFileFilter effFileFilter = setUpEffectiveFileFilter(fileFilter); IOFileFilter effDirFilter = setUpEffectiveDirFilter(dirFilter); //Find files Collection files = new java.util.LinkedList(); if (directory.isDirectory()) { files.add(directory); } innerListFiles(files, directory, FileFilterUtils.or(effFileFilter, effDirFilter), true); return files; } /** * Allows iteration over the files in given directory (and optionally * its subdirectories). *

* All files found are filtered by an IOFileFilter. This method is * based on {@link #listFiles(File, IOFileFilter, IOFileFilter)}, * which supports Iterable ('foreach' loop). *

* @param directory the directory to search in * @param fileFilter filter to apply when finding files. * @param dirFilter optional filter to apply when finding subdirectories. * If this parameter is {@code null}, subdirectories will not be included in the * search. Use TrueFileFilter.INSTANCE to match all directories. * @return an iterator of java.io.File for the matching files * @see org.apache.commons.io.filefilter.FileFilterUtils * @see org.apache.commons.io.filefilter.NameFileFilter * @since 1.2 */ public static Iterator iterateFiles( File directory, IOFileFilter fileFilter, IOFileFilter dirFilter) { return listFiles(directory, fileFilter, dirFilter).iterator(); } /** * Allows iteration over the files in given directory (and optionally * its subdirectories). *

* All files found are filtered by an IOFileFilter. This method is * based on {@link #listFilesAndDirs(File, IOFileFilter, IOFileFilter)}, * which supports Iterable ('foreach' loop). *

* The resulting iterator includes the subdirectories themselves. * * @param directory the directory to search in * @param fileFilter filter to apply when finding files. * @param dirFilter optional filter to apply when finding subdirectories. * If this parameter is {@code null}, subdirectories will not be included in the * search. Use TrueFileFilter.INSTANCE to match all directories. * @return an iterator of java.io.File for the matching files * @see org.apache.commons.io.filefilter.FileFilterUtils * @see org.apache.commons.io.filefilter.NameFileFilter * @since 2.2 */ public static Iterator iterateFilesAndDirs(File directory, IOFileFilter fileFilter, IOFileFilter dirFilter) { return listFilesAndDirs(directory, fileFilter, dirFilter).iterator(); } //----------------------------------------------------------------------- /** * Converts an array of file extensions to suffixes for use * with IOFileFilters. * * @param extensions an array of extensions. Format: {"java", "xml"} * @return an array of suffixes. Format: {".java", ".xml"} */ private static String[] toSuffixes(String[] extensions) { String[] suffixes = new String[extensions.length]; for (int i = 0; i < extensions.length; i++) { suffixes[i] = "." + extensions[i]; } return suffixes; } /** * Finds files within a given directory (and optionally its subdirectories) * which match an array of extensions. * * @param directory the directory to search in * @param extensions an array of extensions, ex. {"java","xml"}. If this * parameter is {@code null}, all files are returned. * @param recursive if true all subdirectories are searched as well * @return an collection of java.io.File with the matching files */ public static Collection listFiles( File directory, String[] extensions, boolean recursive) { IOFileFilter filter; if (extensions == null) { filter = TrueFileFilter.INSTANCE; } else { String[] suffixes = toSuffixes(extensions); filter = new SuffixFileFilter(suffixes); } return listFiles(directory, filter, recursive ? TrueFileFilter.INSTANCE : FalseFileFilter.INSTANCE); } /** * Allows iteration over the files in a given directory (and optionally * its subdirectories) which match an array of extensions. This method * is based on {@link #listFiles(File, String[], boolean)}, * which supports Iterable ('foreach' loop). * * @param directory the directory to search in * @param extensions an array of extensions, ex. {"java","xml"}. If this * parameter is {@code null}, all files are returned. * @param recursive if true all subdirectories are searched as well * @return an iterator of java.io.File with the matching files * @since 1.2 */ public static Iterator iterateFiles( File directory, String[] extensions, boolean recursive) { return listFiles(directory, extensions, recursive).iterator(); } //----------------------------------------------------------------------- /** * Compares the contents of two files to determine if they are equal or not. *

* This method checks to see if the two files are different lengths * or if they point to the same file, before resorting to byte-by-byte * comparison of the contents. *

* Code origin: Avalon * * @param file1 the first file * @param file2 the second file * @return true if the content of the files are equal or they both don't * exist, false otherwise * @throws IOException in case of an I/O error */ public static boolean contentEquals(File file1, File file2) throws IOException { boolean file1Exists = file1.exists(); if (file1Exists != file2.exists()) { return false; } if (!file1Exists) { // two not existing files are equal return true; } if (file1.isDirectory() || file2.isDirectory()) { // don't want to compare directory contents throw new IOException("Can't compare directories, only files"); } if (file1.length() != file2.length()) { // lengths differ, cannot be equal return false; } if (file1.getCanonicalFile().equals(file2.getCanonicalFile())) { // same file return true; } InputStream input1 = null; InputStream input2 = null; try { input1 = new FileInputStream(file1); input2 = new FileInputStream(file2); return IOUtils.contentEquals(input1, input2); } finally { IOUtils.closeQuietly(input1); IOUtils.closeQuietly(input2); } } //----------------------------------------------------------------------- /** * Compares the contents of two files to determine if they are equal or not. *

* This method checks to see if the two files point to the same file, * before resorting to line-by-line comparison of the contents. *

* * @param file1 the first file * @param file2 the second file * @param charsetName the character encoding to be used. * May be null, in which case the platform default is used * @return true if the content of the files are equal or neither exists, * false otherwise * @throws IOException in case of an I/O error * @since 2.2 * @see IOUtils#contentEqualsIgnoreEOL(Reader, Reader) */ public static boolean contentEqualsIgnoreEOL(File file1, File file2, String charsetName) throws IOException { boolean file1Exists = file1.exists(); if (file1Exists != file2.exists()) { return false; } if (!file1Exists) { // two not existing files are equal return true; } if (file1.isDirectory() || file2.isDirectory()) { // don't want to compare directory contents throw new IOException("Can't compare directories, only files"); } if (file1.getCanonicalFile().equals(file2.getCanonicalFile())) { // same file return true; } Reader input1 = null; Reader input2 = null; try { if (charsetName == null) { input1 = new InputStreamReader(new FileInputStream(file1)); input2 = new InputStreamReader(new FileInputStream(file2)); } else { input1 = new InputStreamReader(new FileInputStream(file1), charsetName); input2 = new InputStreamReader(new FileInputStream(file2), charsetName); } return IOUtils.contentEqualsIgnoreEOL(input1, input2); } finally { IOUtils.closeQuietly(input1); IOUtils.closeQuietly(input2); } } //----------------------------------------------------------------------- /** * Convert from a URL to a File. *

* From version 1.1 this method will decode the URL. * Syntax such as file:///my%20docs/file.txt will be * correctly decoded to /my docs/file.txt. Starting with version * 1.5, this method uses UTF-8 to decode percent-encoded octets to characters. * Additionally, malformed percent-encoded octets are handled leniently by * passing them through literally. * * @param url the file URL to convert, {@code null} returns {@code null} * @return the equivalent File object, or {@code null} * if the URL's protocol is not file */ public static File toFile(URL url) { if (url == null || !"file".equalsIgnoreCase(url.getProtocol())) { return null; } else { String filename = url.getFile().replace('/', File.separatorChar); filename = decodeUrl(filename); return new File(filename); } } /** * Decodes the specified URL as per RFC 3986, i.e. transforms * percent-encoded octets to characters by decoding with the UTF-8 character * set. This function is primarily intended for usage with * {@link java.net.URL} which unfortunately does not enforce proper URLs. As * such, this method will leniently accept invalid characters or malformed * percent-encoded octets and simply pass them literally through to the * result string. Except for rare edge cases, this will make unencoded URLs * pass through unaltered. * * @param url The URL to decode, may be {@code null}. * @return The decoded URL or {@code null} if the input was * {@code null}. */ static String decodeUrl(String url) { String decoded = url; if (url != null && url.indexOf('%') >= 0) { int n = url.length(); StringBuffer buffer = new StringBuffer(); ByteBuffer bytes = ByteBuffer.allocate(n); for (int i = 0; i < n;) { if (url.charAt(i) == '%') { try { do { byte octet = (byte) Integer.parseInt(url.substring(i + 1, i + 3), 16); bytes.put(octet); i += 3; } while (i < n && url.charAt(i) == '%'); continue; } catch (RuntimeException e) { // malformed percent-encoded octet, fall through and // append characters literally } finally { if (bytes.position() > 0) { bytes.flip(); buffer.append(UTF8.decode(bytes).toString()); bytes.clear(); } } } buffer.append(url.charAt(i++)); } decoded = buffer.toString(); } return decoded; } /** * Converts each of an array of URL to a File. *

* Returns an array of the same size as the input. * If the input is {@code null}, an empty array is returned. * If the input contains {@code null}, the output array contains {@code null} at the same * index. *

* This method will decode the URL. * Syntax such as file:///my%20docs/file.txt will be * correctly decoded to /my docs/file.txt. * * @param urls the file URLs to convert, {@code null} returns empty array * @return a non-{@code null} array of Files matching the input, with a {@code null} item * if there was a {@code null} at that index in the input array * @throws IllegalArgumentException if any file is not a URL file * @throws IllegalArgumentException if any file is incorrectly encoded * @since 1.1 */ public static File[] toFiles(URL[] urls) { if (urls == null || urls.length == 0) { return EMPTY_FILE_ARRAY; } File[] files = new File[urls.length]; for (int i = 0; i < urls.length; i++) { URL url = urls[i]; if (url != null) { if (url.getProtocol().equals("file") == false) { throw new IllegalArgumentException( "URL could not be converted to a File: " + url); } files[i] = toFile(url); } } return files; } /** * Converts each of an array of File to a URL. *

* Returns an array of the same size as the input. * * @param files the files to convert, must not be {@code null} * @return an array of URLs matching the input * @throws IOException if a file cannot be converted * @throws NullPointerException if the parameter is null */ public static URL[] toURLs(File[] files) throws IOException { URL[] urls = new URL[files.length]; for (int i = 0; i < urls.length; i++) { urls[i] = files[i].toURI().toURL(); } return urls; } //----------------------------------------------------------------------- /** * Copies a file to a directory preserving the file date. *

* This method copies the contents of the specified source file * to a file of the same name in the specified destination directory. * The destination directory is created if it does not exist. * If the destination file exists, then this method will overwrite it. *

* Note: This method tries to preserve the file's last * modified date/times using {@link File#setLastModified(long)}, however * it is not guaranteed that the operation will succeed. * If the modification operation fails, no indication is provided. * * @param srcFile an existing file to copy, must not be {@code null} * @param destDir the directory to place the copy in, must not be {@code null} * * @throws NullPointerException if source or destination is null * @throws IOException if source or destination is invalid * @throws IOException if an IO error occurs during copying * @see #copyFile(File, File, boolean) */ public static void copyFileToDirectory(File srcFile, File destDir) throws IOException { copyFileToDirectory(srcFile, destDir, true); } /** * Copies a file to a directory optionally preserving the file date. *

* This method copies the contents of the specified source file * to a file of the same name in the specified destination directory. * The destination directory is created if it does not exist. * If the destination file exists, then this method will overwrite it. *

* Note: Setting preserveFileDate to * {@code true} tries to preserve the file's last modified * date/times using {@link File#setLastModified(long)}, however it is * not guaranteed that the operation will succeed. * If the modification operation fails, no indication is provided. * * @param srcFile an existing file to copy, must not be {@code null} * @param destDir the directory to place the copy in, must not be {@code null} * @param preserveFileDate true if the file date of the copy * should be the same as the original * * @throws NullPointerException if source or destination is {@code null} * @throws IOException if source or destination is invalid * @throws IOException if an IO error occurs during copying * @see #copyFile(File, File, boolean) * @since 1.3 */ public static void copyFileToDirectory(File srcFile, File destDir, boolean preserveFileDate) throws IOException { if (destDir == null) { throw new NullPointerException("Destination must not be null"); } if (destDir.exists() && destDir.isDirectory() == false) { throw new IllegalArgumentException("Destination '" + destDir + "' is not a directory"); } File destFile = new File(destDir, srcFile.getName()); copyFile(srcFile, destFile, preserveFileDate); } /** * Copies a file to a new location preserving the file date. *

* This method copies the contents of the specified source file to the * specified destination file. The directory holding the destination file is * created if it does not exist. If the destination file exists, then this * method will overwrite it. *

* Note: This method tries to preserve the file's last * modified date/times using {@link File#setLastModified(long)}, however * it is not guaranteed that the operation will succeed. * If the modification operation fails, no indication is provided. * * @param srcFile an existing file to copy, must not be {@code null} * @param destFile the new file, must not be {@code null} * * @throws NullPointerException if source or destination is {@code null} * @throws IOException if source or destination is invalid * @throws IOException if an IO error occurs during copying * @see #copyFileToDirectory(File, File) */ public static void copyFile(File srcFile, File destFile) throws IOException { copyFile(srcFile, destFile, true); } /** * Copies a file to a new location. *

* This method copies the contents of the specified source file * to the specified destination file. * The directory holding the destination file is created if it does not exist. * If the destination file exists, then this method will overwrite it. *

* Note: Setting preserveFileDate to * {@code true} tries to preserve the file's last modified * date/times using {@link File#setLastModified(long)}, however it is * not guaranteed that the operation will succeed. * If the modification operation fails, no indication is provided. * * @param srcFile an existing file to copy, must not be {@code null} * @param destFile the new file, must not be {@code null} * @param preserveFileDate true if the file date of the copy * should be the same as the original * * @throws NullPointerException if source or destination is {@code null} * @throws IOException if source or destination is invalid * @throws IOException if an IO error occurs during copying * @see #copyFileToDirectory(File, File, boolean) */ public static void copyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (srcFile == null) { throw new NullPointerException("Source must not be null"); } if (destFile == null) { throw new NullPointerException("Destination must not be null"); } if (srcFile.exists() == false) { throw new FileNotFoundException("Source '" + srcFile + "' does not exist"); } if (srcFile.isDirectory()) { throw new IOException("Source '" + srcFile + "' exists but is a directory"); } if (srcFile.getCanonicalPath().equals(destFile.getCanonicalPath())) { throw new IOException("Source '" + srcFile + "' and destination '" + destFile + "' are the same"); } File parentFile = destFile.getParentFile(); if (parentFile != null) { if (!parentFile.mkdirs() && !parentFile.isDirectory()) { throw new IOException("Destination '" + parentFile + "' directory cannot be created"); } } if (destFile.exists() && destFile.canWrite() == false) { throw new IOException("Destination '" + destFile + "' exists but is read-only"); } doCopyFile(srcFile, destFile, preserveFileDate); } /** * Copy bytes from a File to an OutputStream. *

* This method buffers the input internally, so there is no need to use a BufferedInputStream. *

* * @param input * the File to read from * @param output * the OutputStream to write to * @return the number of bytes copied * @throws NullPointerException * if the input or output is null * @throws IOException * if an I/O error occurs * @since 2.1 */ public static long copyFile(File input, OutputStream output) throws IOException { final FileInputStream fis = new FileInputStream(input); try { return IOUtils.copyLarge(fis, output); } finally { fis.close(); } } /** * Internal copy file method. * * @param srcFile the validated source file, must not be {@code null} * @param destFile the validated destination file, must not be {@code null} * @param preserveFileDate whether to preserve the file date * @throws IOException if an error occurs */ private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } FileInputStream fis = null; FileOutputStream fos = null; FileChannel input = null; FileChannel output = null; try { fis = new FileInputStream(srcFile); fos = new FileOutputStream(destFile); input = fis.getChannel(); output = fos.getChannel(); long size = input.size(); long pos = 0; long count = 0; while (pos < size) { count = size - pos > FILE_COPY_BUFFER_SIZE ? FILE_COPY_BUFFER_SIZE : size - pos; pos += output.transferFrom(input, pos, count); } } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(fos); IOUtils.closeQuietly(input); IOUtils.closeQuietly(fis); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } } //----------------------------------------------------------------------- /** * Copies a directory to within another directory preserving the file dates. *

* This method copies the source directory and all its contents to a * directory of the same name in the specified destination directory. *

* The destination directory is created if it does not exist. * If the destination directory did exist, then this method merges * the source with the destination, with the source taking precedence. *

* Note: This method tries to preserve the files' last * modified date/times using {@link File#setLastModified(long)}, however * it is not guaranteed that those operations will succeed. * If the modification operation fails, no indication is provided. * * @param srcDir an existing directory to copy, must not be {@code null} * @param destDir the directory to place the copy in, must not be {@code null} * * @throws NullPointerException if source or destination is {@code null} * @throws IOException if source or destination is invalid * @throws IOException if an IO error occurs during copying * @since 1.2 */ public static void copyDirectoryToDirectory(File srcDir, File destDir) throws IOException { if (srcDir == null) { throw new NullPointerException("Source must not be null"); } if (srcDir.exists() && srcDir.isDirectory() == false) { throw new IllegalArgumentException("Source '" + destDir + "' is not a directory"); } if (destDir == null) { throw new NullPointerException("Destination must not be null"); } if (destDir.exists() && destDir.isDirectory() == false) { throw new IllegalArgumentException("Destination '" + destDir + "' is not a directory"); } copyDirectory(srcDir, new File(destDir, srcDir.getName()), true); } /** * Copies a whole directory to a new location preserving the file dates. *

* This method copies the specified directory and all its child * directories and files to the specified destination. * The destination is the new location and name of the directory. *

* The destination directory is created if it does not exist. * If the destination directory did exist, then this method merges * the source with the destination, with the source taking precedence. *

* Note: This method tries to preserve the files' last * modified date/times using {@link File#setLastModified(long)}, however * it is not guaranteed that those operations will succeed. * If the modification operation fails, no indication is provided. * * @param srcDir an existing directory to copy, must not be {@code null} * @param destDir the new directory, must not be {@code null} * * @throws NullPointerException if source or destination is {@code null} * @throws IOException if source or destination is invalid * @throws IOException if an IO error occurs during copying * @since 1.1 */ public static void copyDirectory(File srcDir, File destDir) throws IOException { copyDirectory(srcDir, destDir, true); } /** * Copies a whole directory to a new location. *

* This method copies the contents of the specified source directory * to within the specified destination directory. *

* The destination directory is created if it does not exist. * If the destination directory did exist, then this method merges * the source with the destination, with the source taking precedence. *

* Note: Setting preserveFileDate to * {@code true} tries to preserve the files' last modified * date/times using {@link File#setLastModified(long)}, however it is * not guaranteed that those operations will succeed. * If the modification operation fails, no indication is provided. * * @param srcDir an existing directory to copy, must not be {@code null} * @param destDir the new directory, must not be {@code null} * @param preserveFileDate true if the file date of the copy * should be the same as the original * * @throws NullPointerException if source or destination is {@code null} * @throws IOException if source or destination is invalid * @throws IOException if an IO error occurs during copying * @since 1.1 */ public static void copyDirectory(File srcDir, File destDir, boolean preserveFileDate) throws IOException { copyDirectory(srcDir, destDir, null, preserveFileDate); } /** * Copies a filtered directory to a new location preserving the file dates. *

* This method copies the contents of the specified source directory * to within the specified destination directory. *

* The destination directory is created if it does not exist. * If the destination directory did exist, then this method merges * the source with the destination, with the source taking precedence. *

* Note: This method tries to preserve the files' last * modified date/times using {@link File#setLastModified(long)}, however * it is not guaranteed that those operations will succeed. * If the modification operation fails, no indication is provided. * *

Example: Copy directories only

*
     *  // only copy the directory structure
     *  FileUtils.copyDirectory(srcDir, destDir, DirectoryFileFilter.DIRECTORY);
     *  
* *

Example: Copy directories and txt files

*
     *  // Create a filter for ".txt" files
     *  IOFileFilter txtSuffixFilter = FileFilterUtils.suffixFileFilter(".txt");
     *  IOFileFilter txtFiles = FileFilterUtils.andFileFilter(FileFileFilter.FILE, txtSuffixFilter);
     *
     *  // Create a filter for either directories or ".txt" files
     *  FileFilter filter = FileFilterUtils.orFileFilter(DirectoryFileFilter.DIRECTORY, txtFiles);
     *
     *  // Copy using the filter
     *  FileUtils.copyDirectory(srcDir, destDir, filter);
     *  
* * @param srcDir an existing directory to copy, must not be {@code null} * @param destDir the new directory, must not be {@code null} * @param filter the filter to apply, null means copy all directories and files * should be the same as the original * * @throws NullPointerException if source or destination is {@code null} * @throws IOException if source or destination is invalid * @throws IOException if an IO error occurs during copying * @since 1.4 */ public static void copyDirectory(File srcDir, File destDir, FileFilter filter) throws IOException { copyDirectory(srcDir, destDir, filter, true); } /** * Copies a filtered directory to a new location. *

* This method copies the contents of the specified source directory * to within the specified destination directory. *

* The destination directory is created if it does not exist. * If the destination directory did exist, then this method merges * the source with the destination, with the source taking precedence. *

* Note: Setting preserveFileDate to * {@code true} tries to preserve the files' last modified * date/times using {@link File#setLastModified(long)}, however it is * not guaranteed that those operations will succeed. * If the modification operation fails, no indication is provided. * *

Example: Copy directories only

*
     *  // only copy the directory structure
     *  FileUtils.copyDirectory(srcDir, destDir, DirectoryFileFilter.DIRECTORY, false);
     *  
* *

Example: Copy directories and txt files

*
     *  // Create a filter for ".txt" files
     *  IOFileFilter txtSuffixFilter = FileFilterUtils.suffixFileFilter(".txt");
     *  IOFileFilter txtFiles = FileFilterUtils.andFileFilter(FileFileFilter.FILE, txtSuffixFilter);
     *
     *  // Create a filter for either directories or ".txt" files
     *  FileFilter filter = FileFilterUtils.orFileFilter(DirectoryFileFilter.DIRECTORY, txtFiles);
     *
     *  // Copy using the filter
     *  FileUtils.copyDirectory(srcDir, destDir, filter, false);
     *  
* * @param srcDir an existing directory to copy, must not be {@code null} * @param destDir the new directory, must not be {@code null} * @param filter the filter to apply, null means copy all directories and files * @param preserveFileDate true if the file date of the copy * should be the same as the original * * @throws NullPointerException if source or destination is {@code null} * @throws IOException if source or destination is invalid * @throws IOException if an IO error occurs during copying * @since 1.4 */ public static void copyDirectory(File srcDir, File destDir, FileFilter filter, boolean preserveFileDate) throws IOException { if (srcDir == null) { throw new NullPointerException("Source must not be null"); } if (destDir == null) { throw new NullPointerException("Destination must not be null"); } if (srcDir.exists() == false) { throw new FileNotFoundException("Source '" + srcDir + "' does not exist"); } if (srcDir.isDirectory() == false) { throw new IOException("Source '" + srcDir + "' exists but is not a directory"); } if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath())) { throw new IOException("Source '" + srcDir + "' and destination '" + destDir + "' are the same"); } // Cater for destination being directory within the source directory (see IO-141) List exclusionList = null; if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) { File[] srcFiles = filter == null ? srcDir.listFiles() : srcDir.listFiles(filter); if (srcFiles != null && srcFiles.length > 0) { exclusionList = new ArrayList(srcFiles.length); for (File srcFile : srcFiles) { File copiedFile = new File(destDir, srcFile.getName()); exclusionList.add(copiedFile.getCanonicalPath()); } } } doCopyDirectory(srcDir, destDir, filter, preserveFileDate, exclusionList); } /** * Internal copy directory method. * * @param srcDir the validated source directory, must not be {@code null} * @param destDir the validated destination directory, must not be {@code null} * @param filter the filter to apply, null means copy all directories and files * @param preserveFileDate whether to preserve the file date * @param exclusionList List of files and directories to exclude from the copy, may be null * @throws IOException if an error occurs * @since 1.1 */ private static void doCopyDirectory(File srcDir, File destDir, FileFilter filter, boolean preserveFileDate, List exclusionList) throws IOException { // recurse File[] srcFiles = filter == null ? srcDir.listFiles() : srcDir.listFiles(filter); if (srcFiles == null) { // null if abstract pathname does not denote a directory, or if an I/O error occurs throw new IOException("Failed to list contents of " + srcDir); } if (destDir.exists()) { if (destDir.isDirectory() == false) { throw new IOException("Destination '" + destDir + "' exists but is not a directory"); } } else { if (!destDir.mkdirs() && !destDir.isDirectory()) { throw new IOException("Destination '" + destDir + "' directory cannot be created"); } } if (destDir.canWrite() == false) { throw new IOException("Destination '" + destDir + "' cannot be written to"); } for (File srcFile : srcFiles) { File dstFile = new File(destDir, srcFile.getName()); if (exclusionList == null || !exclusionList.contains(srcFile.getCanonicalPath())) { if (srcFile.isDirectory()) { doCopyDirectory(srcFile, dstFile, filter, preserveFileDate, exclusionList); } else { doCopyFile(srcFile, dstFile, preserveFileDate); } } } // Do this last, as the above has probably affected directory metadata if (preserveFileDate) { destDir.setLastModified(srcDir.lastModified()); } } //----------------------------------------------------------------------- /** * Copies bytes from the URL source to a file * destination. The directories up to destination * will be created if they don't already exist. destination * will be overwritten if it already exists. *

* Warning: this method does not set a connection or read timeout and thus * might block forever. Use {@link #copyURLToFile(URL, File, int, int)} * with reasonable timeouts to prevent this. * * @param source the URL to copy bytes from, must not be {@code null} * @param destination the non-directory File to write bytes to * (possibly overwriting), must not be {@code null} * @throws IOException if source URL cannot be opened * @throws IOException if destination is a directory * @throws IOException if destination cannot be written * @throws IOException if destination needs creating but can't be * @throws IOException if an IO error occurs during copying */ public static void copyURLToFile(URL source, File destination) throws IOException { InputStream input = source.openStream(); copyInputStreamToFile(input, destination); } /** * Copies bytes from the URL source to a file * destination. The directories up to destination * will be created if they don't already exist. destination * will be overwritten if it already exists. * * @param source the URL to copy bytes from, must not be {@code null} * @param destination the non-directory File to write bytes to * (possibly overwriting), must not be {@code null} * @param connectionTimeout the number of milliseconds until this method * will timeout if no connection could be established to the source * @param readTimeout the number of milliseconds until this method will * timeout if no data could be read from the source * @throws IOException if source URL cannot be opened * @throws IOException if destination is a directory * @throws IOException if destination cannot be written * @throws IOException if destination needs creating but can't be * @throws IOException if an IO error occurs during copying * @since 2.0 */ public static void copyURLToFile(URL source, File destination, int connectionTimeout, int readTimeout) throws IOException { URLConnection connection = source.openConnection(); connection.setConnectTimeout(connectionTimeout); connection.setReadTimeout(readTimeout); InputStream input = connection.getInputStream(); copyInputStreamToFile(input, destination); } /** * Copies bytes from an {@link InputStream} source to a file * destination. The directories up to destination * will be created if they don't already exist. destination * will be overwritten if it already exists. * * @param source the InputStream to copy bytes from, must not be {@code null} * @param destination the non-directory File to write bytes to * (possibly overwriting), must not be {@code null} * @throws IOException if destination is a directory * @throws IOException if destination cannot be written * @throws IOException if destination needs creating but can't be * @throws IOException if an IO error occurs during copying * @since 2.0 */ public static void copyInputStreamToFile(InputStream source, File destination) throws IOException { try { FileOutputStream output = openOutputStream(destination); try { IOUtils.copy(source, output); output.close(); // don't swallow close Exception if copy completes normally } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(source); } } //----------------------------------------------------------------------- /** * Deletes a directory recursively. * * @param directory directory to delete * @throws IOException in case deletion is unsuccessful */ public static void deleteDirectory(File directory) throws IOException { if (!directory.exists()) { return; } if (!isSymlink(directory)) { cleanDirectory(directory); } if (!directory.delete()) { String message = "Unable to delete directory " + directory + "."; throw new IOException(message); } } /** * Deletes a file, never throwing an exception. If file is a directory, delete it and all sub-directories. *

* The difference between File.delete() and this method are: *

    *
  • A directory to be deleted does not have to be empty.
  • *
  • No exceptions are thrown when a file or directory cannot be deleted.
  • *
* * @param file file or directory to delete, can be {@code null} * @return {@code true} if the file or directory was deleted, otherwise * {@code false} * * @since 1.4 */ public static boolean deleteQuietly(File file) { if (file == null) { return false; } try { if (file.isDirectory()) { cleanDirectory(file); } } catch (Exception ignored) { } try { return file.delete(); } catch (Exception ignored) { return false; } } /** * Determines whether the {@code parent} directory contains the {@code child} element (a file or directory). *

* Files are normalized before comparison. *

* * Edge cases: *
    *
  • A {@code directory} must not be null: if null, throw IllegalArgumentException
  • *
  • A {@code directory} must be a directory: if not a directory, throw IllegalArgumentException
  • *
  • A directory does not contain itself: return false
  • *
  • A null child file is not contained in any parent: return false
  • *
* * @param directory * the file to consider as the parent. * @param child * the file to consider as the child. * @return true is the candidate leaf is under by the specified composite. False otherwise. * @throws IOException * if an IO error occurs while checking the files. * @since 2.2 * @see FilenameUtils#directoryContains(String, String) */ public static boolean directoryContains(final File directory, final File child) throws IOException { // Fail fast against NullPointerException if (directory == null) { throw new IllegalArgumentException("Directory must not be null"); } if (!directory.isDirectory()) { throw new IllegalArgumentException("Not a directory: " + directory); } if (child == null) { return false; } if (!directory.exists() || !child.exists()) { return false; } // Canonicalize paths (normalizes relative paths) String canonicalParent = directory.getCanonicalPath(); String canonicalChild = child.getCanonicalPath(); return FilenameUtils.directoryContains(canonicalParent, canonicalChild); } /** * Cleans a directory without deleting it. * * @param directory directory to clean * @throws IOException in case cleaning is unsuccessful */ public static void cleanDirectory(File directory) throws IOException { if (!directory.exists()) { String message = directory + " does not exist"; throw new IllegalArgumentException(message); } if (!directory.isDirectory()) { String message = directory + " is not a directory"; throw new IllegalArgumentException(message); } File[] files = directory.listFiles(); if (files == null) { // null if security restricted throw new IOException("Failed to list contents of " + directory); } IOException exception = null; for (File file : files) { try { forceDelete(file); } catch (IOException ioe) { exception = ioe; } } if (null != exception) { throw exception; } } //----------------------------------------------------------------------- /** * Waits for NFS to propagate a file creation, imposing a timeout. *

* This method repeatedly tests {@link File#exists()} until it returns * true up to the maximum time specified in seconds. * * @param file the file to check, must not be {@code null} * @param seconds the maximum time in seconds to wait * @return true if file exists * @throws NullPointerException if the file is {@code null} */ public static boolean waitFor(File file, int seconds) { int timeout = 0; int tick = 0; while (!file.exists()) { if (tick++ >= 10) { tick = 0; if (timeout++ > seconds) { return false; } } try { Thread.sleep(100); } catch (InterruptedException ignore) { // ignore exception } catch (Exception ex) { break; } } return true; } //----------------------------------------------------------------------- /** * Reads the contents of a file into a String. * The file is always closed. * * @param file the file to read, must not be {@code null} * @param encoding the encoding to use, {@code null} means platform default * @return the file contents, never {@code null} * @throws IOException in case of an I/O error * @since 2.3 */ public static String readFileToString(File file, Charset encoding) throws IOException { InputStream in = null; try { in = openInputStream(file); return IOUtils.toString(in, Charsets.toCharset(encoding)); } finally { IOUtils.closeQuietly(in); } } /** * Reads the contents of a file into a String. The file is always closed. * * @param file * the file to read, must not be {@code null} * @param encoding * the encoding to use, {@code null} means platform default * @return the file contents, never {@code null} * @throws IOException * in case of an I/O error * @throws UnsupportedCharsetException * thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not * supported. * @since 2.3 */ public static String readFileToString(File file, String encoding) throws IOException { return readFileToString(file, Charsets.toCharset(encoding)); } /** * Reads the contents of a file into a String using the default encoding for the VM. * The file is always closed. * * @param file the file to read, must not be {@code null} * @return the file contents, never {@code null} * @throws IOException in case of an I/O error * @since 1.3.1 */ public static String readFileToString(File file) throws IOException { return readFileToString(file, Charset.defaultCharset()); } /** * Reads the contents of a file into a byte array. * The file is always closed. * * @param file the file to read, must not be {@code null} * @return the file contents, never {@code null} * @throws IOException in case of an I/O error * @since 1.1 */ public static byte[] readFileToByteArray(File file) throws IOException { InputStream in = null; try { in = openInputStream(file); return IOUtils.toByteArray(in, file.length()); } finally { IOUtils.closeQuietly(in); } } /** * Reads the contents of a file line by line to a List of Strings. * The file is always closed. * * @param file the file to read, must not be {@code null} * @param encoding the encoding to use, {@code null} means platform default * @return the list of Strings representing each line in the file, never {@code null} * @throws IOException in case of an I/O error * @since 2.3 */ public static List readLines(File file, Charset encoding) throws IOException { InputStream in = null; try { in = openInputStream(file); return IOUtils.readLines(in, Charsets.toCharset(encoding)); } finally { IOUtils.closeQuietly(in); } } /** * Reads the contents of a file line by line to a List of Strings. The file is always closed. * * @param file * the file to read, must not be {@code null} * @param encoding * the encoding to use, {@code null} means platform default * @return the list of Strings representing each line in the file, never {@code null} * @throws IOException * in case of an I/O error * @throws UnsupportedCharsetException * thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not * supported. * @since 1.1 */ public static List readLines(File file, String encoding) throws IOException { return readLines(file, Charsets.toCharset(encoding)); } /** * Reads the contents of a file line by line to a List of Strings using the default encoding for the VM. * The file is always closed. * * @param file the file to read, must not be {@code null} * @return the list of Strings representing each line in the file, never {@code null} * @throws IOException in case of an I/O error * @since 1.3 */ public static List readLines(File file) throws IOException { return readLines(file, Charset.defaultCharset()); } /** * Returns an Iterator for the lines in a File. *

* This method opens an InputStream for the file. * When you have finished with the iterator you should close the stream * to free internal resources. This can be done by calling the * {@link LineIterator#close()} or * {@link LineIterator#closeQuietly(LineIterator)} method. *

* The recommended usage pattern is: *

     * LineIterator it = FileUtils.lineIterator(file, "UTF-8");
     * try {
     *   while (it.hasNext()) {
     *     String line = it.nextLine();
     *     /// do something with line
     *   }
     * } finally {
     *   LineIterator.closeQuietly(iterator);
     * }
     * 
*

* If an exception occurs during the creation of the iterator, the * underlying stream is closed. * * @param file the file to open for input, must not be {@code null} * @param encoding the encoding to use, {@code null} means platform default * @return an Iterator of the lines in the file, never {@code null} * @throws IOException in case of an I/O error (file closed) * @since 1.2 */ public static LineIterator lineIterator(File file, String encoding) throws IOException { InputStream in = null; try { in = openInputStream(file); return IOUtils.lineIterator(in, encoding); } catch (IOException ex) { IOUtils.closeQuietly(in); throw ex; } catch (RuntimeException ex) { IOUtils.closeQuietly(in); throw ex; } } /** * Returns an Iterator for the lines in a File using the default encoding for the VM. * * @param file the file to open for input, must not be {@code null} * @return an Iterator of the lines in the file, never {@code null} * @throws IOException in case of an I/O error (file closed) * @since 1.3 * @see #lineIterator(File, String) */ public static LineIterator lineIterator(File file) throws IOException { return lineIterator(file, null); } //----------------------------------------------------------------------- /** * Writes a String to a file creating the file if it does not exist. * * NOTE: As from v1.3, the parent directories of the file will be created * if they do not exist. * * @param file the file to write * @param data the content to write to the file * @param encoding the encoding to use, {@code null} means platform default * @throws IOException in case of an I/O error * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM * @since 2.4 */ public static void writeStringToFile(File file, String data, Charset encoding) throws IOException { writeStringToFile(file, data, encoding, false); } /** * Writes a String to a file creating the file if it does not exist. * * NOTE: As from v1.3, the parent directories of the file will be created * if they do not exist. * * @param file the file to write * @param data the content to write to the file * @param encoding the encoding to use, {@code null} means platform default * @throws IOException in case of an I/O error * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM */ public static void writeStringToFile(File file, String data, String encoding) throws IOException { writeStringToFile(file, data, encoding, false); } /** * Writes a String to a file creating the file if it does not exist. * * @param file the file to write * @param data the content to write to the file * @param encoding the encoding to use, {@code null} means platform default * @param append if {@code true}, then the String will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @since 2.3 */ public static void writeStringToFile(File file, String data, Charset encoding, boolean append) throws IOException { OutputStream out = null; try { out = openOutputStream(file, append); IOUtils.write(data, out, encoding); out.close(); // don't swallow close Exception if copy completes normally } finally { IOUtils.closeQuietly(out); } } /** * Writes a String to a file creating the file if it does not exist. * * @param file the file to write * @param data the content to write to the file * @param encoding the encoding to use, {@code null} means platform default * @param append if {@code true}, then the String will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @throws UnsupportedCharsetException * thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not * supported by the VM * @since 2.1 */ public static void writeStringToFile(File file, String data, String encoding, boolean append) throws IOException { writeStringToFile(file, data, Charsets.toCharset(encoding), append); } /** * Writes a String to a file creating the file if it does not exist using the default encoding for the VM. * * @param file the file to write * @param data the content to write to the file * @throws IOException in case of an I/O error */ public static void writeStringToFile(File file, String data) throws IOException { writeStringToFile(file, data, Charset.defaultCharset(), false); } /** * Writes a String to a file creating the file if it does not exist using the default encoding for the VM. * * @param file the file to write * @param data the content to write to the file * @param append if {@code true}, then the String will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @since 2.1 */ public static void writeStringToFile(File file, String data, boolean append) throws IOException { writeStringToFile(file, data, Charset.defaultCharset(), append); } /** * Writes a CharSequence to a file creating the file if it does not exist using the default encoding for the VM. * * @param file the file to write * @param data the content to write to the file * @throws IOException in case of an I/O error * @since 2.0 */ public static void write(File file, CharSequence data) throws IOException { write(file, data, Charset.defaultCharset(), false); } /** * Writes a CharSequence to a file creating the file if it does not exist using the default encoding for the VM. * * @param file the file to write * @param data the content to write to the file * @param append if {@code true}, then the data will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @since 2.1 */ public static void write(File file, CharSequence data, boolean append) throws IOException { write(file, data, Charset.defaultCharset(), append); } /** * Writes a CharSequence to a file creating the file if it does not exist. * * @param file the file to write * @param data the content to write to the file * @param encoding the encoding to use, {@code null} means platform default * @throws IOException in case of an I/O error * @since 2.3 */ public static void write(File file, CharSequence data, Charset encoding) throws IOException { write(file, data, encoding, false); } /** * Writes a CharSequence to a file creating the file if it does not exist. * * @param file the file to write * @param data the content to write to the file * @param encoding the encoding to use, {@code null} means platform default * @throws IOException in case of an I/O error * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM * @since 2.0 */ public static void write(File file, CharSequence data, String encoding) throws IOException { write(file, data, encoding, false); } /** * Writes a CharSequence to a file creating the file if it does not exist. * * @param file the file to write * @param data the content to write to the file * @param encoding the encoding to use, {@code null} means platform default * @param append if {@code true}, then the data will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @since 2.3 */ public static void write(File file, CharSequence data, Charset encoding, boolean append) throws IOException { String str = data == null ? null : data.toString(); writeStringToFile(file, str, encoding, append); } /** * Writes a CharSequence to a file creating the file if it does not exist. * * @param file the file to write * @param data the content to write to the file * @param encoding the encoding to use, {@code null} means platform default * @param append if {@code true}, then the data will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @throws UnsupportedCharsetException * thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not * supported by the VM * @since IO 2.1 */ public static void write(File file, CharSequence data, String encoding, boolean append) throws IOException { write(file, data, Charsets.toCharset(encoding), append); } /** * Writes a byte array to a file creating the file if it does not exist. *

* NOTE: As from v1.3, the parent directories of the file will be created * if they do not exist. * * @param file the file to write to * @param data the content to write to the file * @throws IOException in case of an I/O error * @since 1.1 */ public static void writeByteArrayToFile(File file, byte[] data) throws IOException { writeByteArrayToFile(file, data, false); } /** * Writes a byte array to a file creating the file if it does not exist. * * @param file the file to write to * @param data the content to write to the file * @param append if {@code true}, then bytes will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @since IO 2.1 */ public static void writeByteArrayToFile(File file, byte[] data, boolean append) throws IOException { OutputStream out = null; try { out = openOutputStream(file, append); out.write(data); out.close(); // don't swallow close Exception if copy completes normally } finally { IOUtils.closeQuietly(out); } } /** * Writes the toString() value of each item in a collection to * the specified File line by line. * The specified character encoding and the default line ending will be used. *

* NOTE: As from v1.3, the parent directories of the file will be created * if they do not exist. * * @param file the file to write to * @param encoding the encoding to use, {@code null} means platform default * @param lines the lines to write, {@code null} entries produce blank lines * @throws IOException in case of an I/O error * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM * @since 1.1 */ public static void writeLines(File file, String encoding, Collection lines) throws IOException { writeLines(file, encoding, lines, null, false); } /** * Writes the toString() value of each item in a collection to * the specified File line by line, optionally appending. * The specified character encoding and the default line ending will be used. * * @param file the file to write to * @param encoding the encoding to use, {@code null} means platform default * @param lines the lines to write, {@code null} entries produce blank lines * @param append if {@code true}, then the lines will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM * @since 2.1 */ public static void writeLines(File file, String encoding, Collection lines, boolean append) throws IOException { writeLines(file, encoding, lines, null, append); } /** * Writes the toString() value of each item in a collection to * the specified File line by line. * The default VM encoding and the default line ending will be used. * * @param file the file to write to * @param lines the lines to write, {@code null} entries produce blank lines * @throws IOException in case of an I/O error * @since 1.3 */ public static void writeLines(File file, Collection lines) throws IOException { writeLines(file, null, lines, null, false); } /** * Writes the toString() value of each item in a collection to * the specified File line by line. * The default VM encoding and the default line ending will be used. * * @param file the file to write to * @param lines the lines to write, {@code null} entries produce blank lines * @param append if {@code true}, then the lines will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @since 2.1 */ public static void writeLines(File file, Collection lines, boolean append) throws IOException { writeLines(file, null, lines, null, append); } /** * Writes the toString() value of each item in a collection to * the specified File line by line. * The specified character encoding and the line ending will be used. *

* NOTE: As from v1.3, the parent directories of the file will be created * if they do not exist. * * @param file the file to write to * @param encoding the encoding to use, {@code null} means platform default * @param lines the lines to write, {@code null} entries produce blank lines * @param lineEnding the line separator to use, {@code null} is system default * @throws IOException in case of an I/O error * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM * @since 1.1 */ public static void writeLines(File file, String encoding, Collection lines, String lineEnding) throws IOException { writeLines(file, encoding, lines, lineEnding, false); } /** * Writes the toString() value of each item in a collection to * the specified File line by line. * The specified character encoding and the line ending will be used. * * @param file the file to write to * @param encoding the encoding to use, {@code null} means platform default * @param lines the lines to write, {@code null} entries produce blank lines * @param lineEnding the line separator to use, {@code null} is system default * @param append if {@code true}, then the lines will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM * @since 2.1 */ public static void writeLines(File file, String encoding, Collection lines, String lineEnding, boolean append) throws IOException { FileOutputStream out = null; try { out = openOutputStream(file, append); final BufferedOutputStream buffer = new BufferedOutputStream(out); IOUtils.writeLines(lines, lineEnding, buffer, encoding); buffer.flush(); out.close(); // don't swallow close Exception if copy completes normally } finally { IOUtils.closeQuietly(out); } } /** * Writes the toString() value of each item in a collection to * the specified File line by line. * The default VM encoding and the specified line ending will be used. * * @param file the file to write to * @param lines the lines to write, {@code null} entries produce blank lines * @param lineEnding the line separator to use, {@code null} is system default * @throws IOException in case of an I/O error * @since 1.3 */ public static void writeLines(File file, Collection lines, String lineEnding) throws IOException { writeLines(file, null, lines, lineEnding, false); } /** * Writes the toString() value of each item in a collection to * the specified File line by line. * The default VM encoding and the specified line ending will be used. * * @param file the file to write to * @param lines the lines to write, {@code null} entries produce blank lines * @param lineEnding the line separator to use, {@code null} is system default * @param append if {@code true}, then the lines will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @since 2.1 */ public static void writeLines(File file, Collection lines, String lineEnding, boolean append) throws IOException { writeLines(file, null, lines, lineEnding, append); } //----------------------------------------------------------------------- /** * Deletes a file. If file is a directory, delete it and all sub-directories. *

* The difference between File.delete() and this method are: *

    *
  • A directory to be deleted does not have to be empty.
  • *
  • You get exceptions when a file or directory cannot be deleted. * (java.io.File methods returns a boolean)
  • *
* * @param file file or directory to delete, must not be {@code null} * @throws NullPointerException if the directory is {@code null} * @throws FileNotFoundException if the file was not found * @throws IOException in case deletion is unsuccessful */ public static void forceDelete(File file) throws IOException { if (file.isDirectory()) { deleteDirectory(file); } else { boolean filePresent = file.exists(); if (!file.delete()) { if (!filePresent){ throw new FileNotFoundException("File does not exist: " + file); } String message = "Unable to delete file: " + file; throw new IOException(message); } } } /** * Schedules a file to be deleted when JVM exits. * If file is directory delete it and all sub-directories. * * @param file file or directory to delete, must not be {@code null} * @throws NullPointerException if the file is {@code null} * @throws IOException in case deletion is unsuccessful */ public static void forceDeleteOnExit(File file) throws IOException { if (file.isDirectory()) { deleteDirectoryOnExit(file); } else { file.deleteOnExit(); } } /** * Schedules a directory recursively for deletion on JVM exit. * * @param directory directory to delete, must not be {@code null} * @throws NullPointerException if the directory is {@code null} * @throws IOException in case deletion is unsuccessful */ private static void deleteDirectoryOnExit(File directory) throws IOException { if (!directory.exists()) { return; } directory.deleteOnExit(); if (!isSymlink(directory)) { cleanDirectoryOnExit(directory); } } /** * Cleans a directory without deleting it. * * @param directory directory to clean, must not be {@code null} * @throws NullPointerException if the directory is {@code null} * @throws IOException in case cleaning is unsuccessful */ private static void cleanDirectoryOnExit(File directory) throws IOException { if (!directory.exists()) { String message = directory + " does not exist"; throw new IllegalArgumentException(message); } if (!directory.isDirectory()) { String message = directory + " is not a directory"; throw new IllegalArgumentException(message); } File[] files = directory.listFiles(); if (files == null) { // null if security restricted throw new IOException("Failed to list contents of " + directory); } IOException exception = null; for (File file : files) { try { forceDeleteOnExit(file); } catch (IOException ioe) { exception = ioe; } } if (null != exception) { throw exception; } } /** * Makes a directory, including any necessary but nonexistent parent * directories. If a file already exists with specified name but it is * not a directory then an IOException is thrown. * If the directory cannot be created (or does not already exist) * then an IOException is thrown. * * @param directory directory to create, must not be {@code null} * @throws NullPointerException if the directory is {@code null} * @throws IOException if the directory cannot be created or the file already exists but is not a directory */ public static void forceMkdir(File directory) throws IOException { if (directory.exists()) { if (!directory.isDirectory()) { String message = "File " + directory + " exists and is " + "not a directory. Unable to create directory."; throw new IOException(message); } } else { if (!directory.mkdirs()) { // Double-check that some other thread or process hasn't made // the directory in the background if (!directory.isDirectory()) { String message = "Unable to create directory " + directory; throw new IOException(message); } } } } //----------------------------------------------------------------------- /** * Returns the size of the specified file or directory. If the provided * {@link File} is a regular file, then the file's length is returned. * If the argument is a directory, then the size of the directory is * calculated recursively. If a directory or subdirectory is security * restricted, its size will not be included. * * @param file the regular file or directory to return the size * of (must not be {@code null}). * * @return the length of the file, or recursive size of the directory, * provided (in bytes). * * @throws NullPointerException if the file is {@code null} * @throws IllegalArgumentException if the file does not exist. * * @since 2.0 */ public static long sizeOf(File file) { if (!file.exists()) { String message = file + " does not exist"; throw new IllegalArgumentException(message); } if (file.isDirectory()) { return sizeOfDirectory(file); } else { return file.length(); } } /** * Returns the size of the specified file or directory. If the provided * {@link File} is a regular file, then the file's length is returned. * If the argument is a directory, then the size of the directory is * calculated recursively. If a directory or subdirectory is security * restricted, its size will not be included. * * @param file the regular file or directory to return the size * of (must not be {@code null}). * * @return the length of the file, or recursive size of the directory, * provided (in bytes). * * @throws NullPointerException if the file is {@code null} * @throws IllegalArgumentException if the file does not exist. * * @since 2.4 */ public static BigInteger sizeOfAsBigInteger(File file) { if (!file.exists()) { String message = file + " does not exist"; throw new IllegalArgumentException(message); } if (file.isDirectory()) { return sizeOfDirectoryAsBigInteger(file); } else { return BigInteger.valueOf(file.length()); } } /** * Counts the size of a directory recursively (sum of the length of all files). * * @param directory * directory to inspect, must not be {@code null} * @return size of directory in bytes, 0 if directory is security restricted, a negative number when the real total * is greater than {@link Long#MAX_VALUE}. * @throws NullPointerException * if the directory is {@code null} */ public static long sizeOfDirectory(File directory) { checkDirectory(directory); final File[] files = directory.listFiles(); if (files == null) { // null if security restricted return 0L; } long size = 0; for (final File file : files) { try { if (!isSymlink(file)) { size += sizeOf(file); if (size < 0) { break; } } } catch (IOException ioe) { // Ignore exceptions caught when asking if a File is a symlink. } } return size; } /** * Counts the size of a directory recursively (sum of the length of all files). * * @param directory * directory to inspect, must not be {@code null} * @return size of directory in bytes, 0 if directory is security restricted. * @throws NullPointerException * if the directory is {@code null} * @since 2.4 */ public static BigInteger sizeOfDirectoryAsBigInteger(File directory) { checkDirectory(directory); final File[] files = directory.listFiles(); if (files == null) { // null if security restricted return BigInteger.ZERO; } BigInteger size = BigInteger.ZERO; for (final File file : files) { try { if (!isSymlink(file)) { size = size.add(BigInteger.valueOf(sizeOf(file))); } } catch (IOException ioe) { // Ignore exceptions caught when asking if a File is a symlink. } } return size; } /** * Checks that the given {@code File} exists and is a directory. * * @param directory The {@code File} to check. * @throws IllegalArgumentException if the given {@code File} does not exist or is not a directory. */ private static void checkDirectory(File directory) { if (!directory.exists()) { throw new IllegalArgumentException(directory + " does not exist"); } if (!directory.isDirectory()) { throw new IllegalArgumentException(directory + " is not a directory"); } } //----------------------------------------------------------------------- /** * Tests if the specified File is newer than the reference * File. * * @param file the File of which the modification date must * be compared, must not be {@code null} * @param reference the File of which the modification date * is used, must not be {@code null} * @return true if the File exists and has been modified more * recently than the reference File * @throws IllegalArgumentException if the file is {@code null} * @throws IllegalArgumentException if the reference file is {@code null} or doesn't exist */ public static boolean isFileNewer(File file, File reference) { if (reference == null) { throw new IllegalArgumentException("No specified reference file"); } if (!reference.exists()) { throw new IllegalArgumentException("The reference file '" + reference + "' doesn't exist"); } return isFileNewer(file, reference.lastModified()); } /** * Tests if the specified File is newer than the specified * Date. * * @param file the File of which the modification date * must be compared, must not be {@code null} * @param date the date reference, must not be {@code null} * @return true if the File exists and has been modified * after the given Date. * @throws IllegalArgumentException if the file is {@code null} * @throws IllegalArgumentException if the date is {@code null} */ public static boolean isFileNewer(File file, Date date) { if (date == null) { throw new IllegalArgumentException("No specified date"); } return isFileNewer(file, date.getTime()); } /** * Tests if the specified File is newer than the specified * time reference. * * @param file the File of which the modification date must * be compared, must not be {@code null} * @param timeMillis the time reference measured in milliseconds since the * epoch (00:00:00 GMT, January 1, 1970) * @return true if the File exists and has been modified after * the given time reference. * @throws IllegalArgumentException if the file is {@code null} */ public static boolean isFileNewer(File file, long timeMillis) { if (file == null) { throw new IllegalArgumentException("No specified file"); } if (!file.exists()) { return false; } return file.lastModified() > timeMillis; } //----------------------------------------------------------------------- /** * Tests if the specified File is older than the reference * File. * * @param file the File of which the modification date must * be compared, must not be {@code null} * @param reference the File of which the modification date * is used, must not be {@code null} * @return true if the File exists and has been modified before * the reference File * @throws IllegalArgumentException if the file is {@code null} * @throws IllegalArgumentException if the reference file is {@code null} or doesn't exist */ public static boolean isFileOlder(File file, File reference) { if (reference == null) { throw new IllegalArgumentException("No specified reference file"); } if (!reference.exists()) { throw new IllegalArgumentException("The reference file '" + reference + "' doesn't exist"); } return isFileOlder(file, reference.lastModified()); } /** * Tests if the specified File is older than the specified * Date. * * @param file the File of which the modification date * must be compared, must not be {@code null} * @param date the date reference, must not be {@code null} * @return true if the File exists and has been modified * before the given Date. * @throws IllegalArgumentException if the file is {@code null} * @throws IllegalArgumentException if the date is {@code null} */ public static boolean isFileOlder(File file, Date date) { if (date == null) { throw new IllegalArgumentException("No specified date"); } return isFileOlder(file, date.getTime()); } /** * Tests if the specified File is older than the specified * time reference. * * @param file the File of which the modification date must * be compared, must not be {@code null} * @param timeMillis the time reference measured in milliseconds since the * epoch (00:00:00 GMT, January 1, 1970) * @return true if the File exists and has been modified before * the given time reference. * @throws IllegalArgumentException if the file is {@code null} */ public static boolean isFileOlder(File file, long timeMillis) { if (file == null) { throw new IllegalArgumentException("No specified file"); } if (!file.exists()) { return false; } return file.lastModified() < timeMillis; } //----------------------------------------------------------------------- /** * Computes the checksum of a file using the CRC32 checksum routine. * The value of the checksum is returned. * * @param file the file to checksum, must not be {@code null} * @return the checksum value * @throws NullPointerException if the file or checksum is {@code null} * @throws IllegalArgumentException if the file is a directory * @throws IOException if an IO error occurs reading the file * @since 1.3 */ public static long checksumCRC32(File file) throws IOException { CRC32 crc = new CRC32(); checksum(file, crc); return crc.getValue(); } /** * Computes the checksum of a file using the specified checksum object. * Multiple files may be checked using one Checksum instance * if desired simply by reusing the same checksum object. * For example: *
     *   long csum = FileUtils.checksum(file, new CRC32()).getValue();
     * 
* * @param file the file to checksum, must not be {@code null} * @param checksum the checksum object to be used, must not be {@code null} * @return the checksum specified, updated with the content of the file * @throws NullPointerException if the file or checksum is {@code null} * @throws IllegalArgumentException if the file is a directory * @throws IOException if an IO error occurs reading the file * @since 1.3 */ public static Checksum checksum(File file, Checksum checksum) throws IOException { if (file.isDirectory()) { throw new IllegalArgumentException("Checksums can't be computed on directories"); } InputStream in = null; try { in = new CheckedInputStream(new FileInputStream(file), checksum); IOUtils.copy(in, new NullOutputStream()); } finally { IOUtils.closeQuietly(in); } return checksum; } /** * Moves a directory. *

* When the destination directory is on another file system, do a "copy and delete". * * @param srcDir the directory to be moved * @param destDir the destination directory * @throws NullPointerException if source or destination is {@code null} * @throws FileExistsException if the destination directory exists * @throws IOException if source or destination is invalid * @throws IOException if an IO error occurs moving the file * @since 1.4 */ public static void moveDirectory(File srcDir, File destDir) throws IOException { if (srcDir == null) { throw new NullPointerException("Source must not be null"); } if (destDir == null) { throw new NullPointerException("Destination must not be null"); } if (!srcDir.exists()) { throw new FileNotFoundException("Source '" + srcDir + "' does not exist"); } if (!srcDir.isDirectory()) { throw new IOException("Source '" + srcDir + "' is not a directory"); } if (destDir.exists()) { throw new FileExistsException("Destination '" + destDir + "' already exists"); } boolean rename = srcDir.renameTo(destDir); if (!rename) { if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) { throw new IOException("Cannot move directory: "+srcDir+" to a subdirectory of itself: "+destDir); } copyDirectory( srcDir, destDir ); deleteDirectory( srcDir ); if (srcDir.exists()) { throw new IOException("Failed to delete original directory '" + srcDir + "' after copy to '" + destDir + "'"); } } } /** * Moves a directory to another directory. * * @param src the file to be moved * @param destDir the destination file * @param createDestDir If {@code true} create the destination directory, * otherwise if {@code false} throw an IOException * @throws NullPointerException if source or destination is {@code null} * @throws FileExistsException if the directory exists in the destination directory * @throws IOException if source or destination is invalid * @throws IOException if an IO error occurs moving the file * @since 1.4 */ public static void moveDirectoryToDirectory(File src, File destDir, boolean createDestDir) throws IOException { if (src == null) { throw new NullPointerException("Source must not be null"); } if (destDir == null) { throw new NullPointerException("Destination directory must not be null"); } if (!destDir.exists() && createDestDir) { destDir.mkdirs(); } if (!destDir.exists()) { throw new FileNotFoundException("Destination directory '" + destDir + "' does not exist [createDestDir=" + createDestDir +"]"); } if (!destDir.isDirectory()) { throw new IOException("Destination '" + destDir + "' is not a directory"); } moveDirectory(src, new File(destDir, src.getName())); } /** * Moves a file. *

* When the destination file is on another file system, do a "copy and delete". * * @param srcFile the file to be moved * @param destFile the destination file * @throws NullPointerException if source or destination is {@code null} * @throws FileExistsException if the destination file exists * @throws IOException if source or destination is invalid * @throws IOException if an IO error occurs moving the file * @since 1.4 */ public static void moveFile(File srcFile, File destFile) throws IOException { if (srcFile == null) { throw new NullPointerException("Source must not be null"); } if (destFile == null) { throw new NullPointerException("Destination must not be null"); } if (!srcFile.exists()) { throw new FileNotFoundException("Source '" + srcFile + "' does not exist"); } if (srcFile.isDirectory()) { throw new IOException("Source '" + srcFile + "' is a directory"); } if (destFile.exists()) { throw new FileExistsException("Destination '" + destFile + "' already exists"); } if (destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' is a directory"); } boolean rename = srcFile.renameTo(destFile); if (!rename) { copyFile( srcFile, destFile ); if (!srcFile.delete()) { FileUtils.deleteQuietly(destFile); throw new IOException("Failed to delete original file '" + srcFile + "' after copy to '" + destFile + "'"); } } } /** * Moves a file to a directory. * * @param srcFile the file to be moved * @param destDir the destination file * @param createDestDir If {@code true} create the destination directory, * otherwise if {@code false} throw an IOException * @throws NullPointerException if source or destination is {@code null} * @throws FileExistsException if the destination file exists * @throws IOException if source or destination is invalid * @throws IOException if an IO error occurs moving the file * @since 1.4 */ public static void moveFileToDirectory(File srcFile, File destDir, boolean createDestDir) throws IOException { if (srcFile == null) { throw new NullPointerException("Source must not be null"); } if (destDir == null) { throw new NullPointerException("Destination directory must not be null"); } if (!destDir.exists() && createDestDir) { destDir.mkdirs(); } if (!destDir.exists()) { throw new FileNotFoundException("Destination directory '" + destDir + "' does not exist [createDestDir=" + createDestDir +"]"); } if (!destDir.isDirectory()) { throw new IOException("Destination '" + destDir + "' is not a directory"); } moveFile(srcFile, new File(destDir, srcFile.getName())); } /** * Moves a file or directory to the destination directory. *

* When the destination is on another file system, do a "copy and delete". * * @param src the file or directory to be moved * @param destDir the destination directory * @param createDestDir If {@code true} create the destination directory, * otherwise if {@code false} throw an IOException * @throws NullPointerException if source or destination is {@code null} * @throws FileExistsException if the directory or file exists in the destination directory * @throws IOException if source or destination is invalid * @throws IOException if an IO error occurs moving the file * @since 1.4 */ public static void moveToDirectory(File src, File destDir, boolean createDestDir) throws IOException { if (src == null) { throw new NullPointerException("Source must not be null"); } if (destDir == null) { throw new NullPointerException("Destination must not be null"); } if (!src.exists()) { throw new FileNotFoundException("Source '" + src + "' does not exist"); } if (src.isDirectory()) { moveDirectoryToDirectory(src, destDir, createDestDir); } else { moveFileToDirectory(src, destDir, createDestDir); } } /** * Determines whether the specified file is a Symbolic Link rather than an actual file. *

* Will not return true if there is a Symbolic Link anywhere in the path, * only if the specific file is. *

* Note: the current implementation always returns {@code false} if the system * is detected as Windows using {@link FilenameUtils#isSystemWindows()} * * @param file the file to check * @return true if the file is a Symbolic Link * @throws IOException if an IO error occurs while checking the file * @since 2.0 */ public static boolean isSymlink(File file) throws IOException { if (file == null) { throw new NullPointerException("File must not be null"); } if (FilenameUtils.isSystemWindows()) { return false; } File fileInCanonicalDir = null; if (file.getParent() == null) { fileInCanonicalDir = file; } else { File canonicalDir = file.getParentFile().getCanonicalFile(); fileInCanonicalDir = new File(canonicalDir, file.getName()); } if (fileInCanonicalDir.getCanonicalFile().equals(fileInCanonicalDir.getAbsoluteFile())) { return false; } else { return true; } } } libcommons-io-java-2.4.orig/src/main/java/org/apache/commons/io/package.html0000644000175000017500000000345112125050425026342 0ustar ebourgebourg

This package defines utility classes for working with streams, readers, writers and files. The most commonly used classes are described here:

IOUtils is the most frequently used class. It provides operations to read, write, copy and close streams.

FileUtils provides operations based around the JDK File class. These include reading, writing, copying, comparing and deleting.

FilenameUtils provides utilities based on filenames. This utility class manipulates filenames without using File objects. It aims to simplify the transition between Windows and Unix. Before using this class however, you should consider whether you should be using File objects.

FileSystemUtils allows access to the filing system in ways the JDK does not support. At present this allows you to get the free space on a drive.

EndianUtils swaps data between Big-Endian and Little-Endian formats.

libcommons-io-java-2.4.orig/src/main/assembly/0000755000175000017500000000000012125050425020662 5ustar ebourgebourglibcommons-io-java-2.4.orig/src/main/assembly/src.xml0000644000175000017500000000304612125050425022176 0ustar ebourgebourg src tar.gz zip ${artifactId}-${commons.release.version}-src build.xml checkstyle.xml findbugs-exclude-filter.xml LICENSE.txt NOTICE.txt pom.xml PROPOSAL.html RELEASE-NOTES.txt src libcommons-io-java-2.4.orig/src/main/assembly/bin.xml0000644000175000017500000000340412125050425022155 0ustar ebourgebourg bin tar.gz zip false LICENSE.txt NOTICE.txt RELEASE-NOTES.txt target *.jar target/site/apidocs docs **/customsorttypes.js **/sortabletable.js **/stringbuilder.js libcommons-io-java-2.4.orig/findbugs-exclude-filter.xml0000644000175000017500000000716312125050425022574 0ustar ebourgebourg libcommons-io-java-2.4.orig/LICENSE.txt0000644000175000017500000002613712125050425017164 0ustar ebourgebourg Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.