first commit

This commit is contained in:
MaddoScientisto 2026-03-14 20:04:39 +01:00
commit 4d332ef662
27586 changed files with 3281783 additions and 0 deletions

View file

@ -0,0 +1,203 @@
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.

View file

@ -0,0 +1,38 @@
Manifest-Version: 1.0
Export-Package: org.apache.commons.io;version="1.4.9999",org.apache.co
mmons.io.comparator;version="1.4.9999",org.apache.commons.io.filefilt
er;version="1.4.9999",org.apache.commons.io.input;version="1.4.9999",
org.apache.commons.io.output;version="1.4.9999",org.apache.commons.io
;version="2.4",org.apache.commons.io.comparator;version="2.4",org.apa
che.commons.io.filefilter;version="2.4",org.apache.commons.io.input;v
ersion="2.4",org.apache.commons.io.output;version="2.4",org.apache.co
mmons.io.monitor;version="2.4"
Implementation-Title: Commons IO
Built-By: ggregory
Tool: Bnd-1.50.0
Implementation-Vendor: The Apache Software Foundation
Implementation-Vendor-Id: org.apache
Specification-Title: Commons IO
Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt
Bundle-SymbolicName: org.apache.commons.io
X-Compile-Target-JDK: 1.6
Implementation-Version: 2.4
Specification-Vendor: The Apache Software Foundation
Bundle-Name: Commons IO
Created-By: Apache Maven Bundle Plugin
X-Compile-Source-JDK: 1.6
Bundle-Vendor: The Apache Software Foundation
Build-Jdk: 1.6.0_31
Bundle-Version: 2.4.0
Bnd-LastModified: 1339539506978
Bundle-ManifestVersion: 2
Bundle-Description: The Commons IO library contains utility classes, s
tream implementations, file filters, file comparators, endian transfo
rmation classes, and much more.
Bundle-DocURL: http://commons.apache.org/io/
Implementation-Build: tags/2.4-RC2@r1349569; 2012-06-12 18:18:20-0400
Specification-Version: 2.4
Include-Resource: META-INF/LICENSE.txt=LICENSE.txt,META-INF/NOTICE.txt
=NOTICE.txt
Archiver-Version: Plexus Archiver

View file

@ -0,0 +1,6 @@
Apache Commons IO
Copyright 2002-2012 The Apache Software Foundation
This product includes software developed by
The Apache Software Foundation (http://www.apache.org/).

View file

@ -0,0 +1,5 @@
#Generated by Maven
#Tue Jun 12 18:19:43 EDT 2012
version=2.4
groupId=commons-io
artifactId=commons-io

View file

@ -0,0 +1,323 @@
<?xml version="1.0"?>
<!--
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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>org.apache.commons</groupId>
<artifactId>commons-parent</artifactId>
<version>25</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
<name>Commons IO</name>
<inceptionYear>2002</inceptionYear>
<description>
The Commons IO library contains utility classes, stream implementations, file filters,
file comparators, endian transformation classes, and much more.
</description>
<url>http://commons.apache.org/io/</url>
<issueManagement>
<system>jira</system>
<url>http://issues.apache.org/jira/browse/IO</url>
</issueManagement>
<distributionManagement>
<site>
<id>apache.website</id>
<name>Apache Commons IO Site</name>
<url>${commons.deployment.protocol}://people.apache.org/www/commons.apache.org/${commons.componentid}</url>
</site>
</distributionManagement>
<scm>
<connection>scm:svn:http://svn.apache.org/repos/asf/commons/proper/io/trunk</connection>
<developerConnection>scm:svn:https://svn.apache.org/repos/asf/commons/proper/io/trunk</developerConnection>
<url>http://svn.apache.org/viewvc/commons/proper/io/trunk</url>
</scm>
<developers>
<developer>
<name>Scott Sanders</name>
<id>sanders</id>
<email>sanders@apache.org</email>
<organization></organization>
<roles>
<role>Java Developer</role>
</roles>
</developer>
<developer>
<name>dIon Gillard</name>
<id>dion</id>
<email>dion@apache.org</email>
<organization></organization>
<roles>
<role>Java Developer</role>
</roles>
</developer>
<developer>
<name>Nicola Ken Barozzi</name>
<id>nicolaken</id>
<email>nicolaken@apache.org</email>
<organization></organization>
<roles>
<role>Java Developer</role>
</roles>
</developer>
<developer>
<name>Henri Yandell</name>
<id>bayard</id>
<email>bayard@apache.org</email>
<organization></organization>
<roles>
<role>Java Developer</role>
</roles>
</developer>
<developer>
<name>Stephen Colebourne</name>
<id>scolebourne</id>
<organization></organization>
<roles>
<role>Java Developer</role>
</roles>
<timezone>0</timezone>
</developer>
<developer>
<name>Jeremias Maerki</name>
<id>jeremias</id>
<email>jeremias@apache.org</email>
<organization />
<roles>
<role>Java Developer</role>
</roles>
<timezone>+1</timezone>
</developer>
<developer>
<name>Matthew Hawthorne</name>
<id>matth</id>
<email>matth@apache.org</email>
<organization />
<roles>
<role>Java Developer</role>
</roles>
</developer>
<developer>
<name>Martin Cooper</name>
<id>martinc</id>
<email>martinc@apache.org</email>
<organization />
<roles>
<role>Java Developer</role>
</roles>
</developer>
<developer>
<name>Rob Oxspring</name>
<id>roxspring</id>
<email>roxspring@apache.org</email>
<organization />
<roles>
<role>Java Developer</role>
</roles>
</developer>
<developer>
<name>Jochen Wiedmann</name>
<id>jochen</id>
<email>jochen.wiedmann@gmail.com</email>
</developer>
<developer>
<name>Niall Pemberton</name>
<id>niallp</id>
<roles>
<role>Java Developer</role>
</roles>
</developer>
<developer>
<name>Jukka Zitting</name>
<id>jukka</id>
<roles>
<role>Java Developer</role>
</roles>
</developer>
<developer>
<name>Gary Gregory</name>
<id>ggregory</id>
<email>ggregory@apache.org</email>
<url>http://www.garygregory.com</url>
<timezone>-5</timezone>
</developer>
</developers>
<contributors>
<contributor>
<name>Rahul Akolkar</name>
</contributor>
<contributor>
<name>Jason Anderson</name>
</contributor>
<contributor>
<name>Nathan Beyer</name>
</contributor>
<contributor>
<name>Emmanuel Bourg</name>
</contributor>
<contributor>
<name>Chris Eldredge</name>
</contributor>
<contributor>
<name>Magnus Grimsell</name>
</contributor>
<contributor>
<name>Jim Harrington</name>
</contributor>
<contributor>
<name>Thomas Ledoux</name>
</contributor>
<contributor>
<name>Andy Lehane</name>
</contributor>
<contributor>
<name>Marcelo Liberato</name>
</contributor>
<contributor>
<name>Alban Peignier</name>
<email>alban.peignier at free.fr</email>
</contributor>
<contributor>
<name>Ian Springer</name>
</contributor>
<contributor>
<name>Masato Tezuka</name>
</contributor>
<contributor>
<name>James Urie</name>
</contributor>
<contributor>
<name>Frank W. Zammetti</name>
</contributor>
</contributors>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<maven.compile.source>1.6</maven.compile.source>
<maven.compile.target>1.6</maven.compile.target>
<commons.componentid>io</commons.componentid>
<commons.rc.version>RC1</commons.rc.version>
<commons.release.version>2.4</commons.release.version>
<commons.release.desc>(requires JDK 1.6+)</commons.release.desc>
<commons.release.2.version>2.2</commons.release.2.version>
<commons.release.2.desc>(requires JDK 1.5+)</commons.release.2.desc>
<commons.jira.id>IO</commons.jira.id>
<commons.jira.pid>12310477</commons.jira.pid>
<commons.osgi.export>
<!-- Explicit list of packages from IO 1.4 -->
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,
<!-- Same list plus * for new packages -->
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
</commons.osgi.export>
</properties>
<build>
<pluginManagement>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<forkMode>pertest</forkMode>
<!-- limit memory size see IO-161 -->
<argLine>-Xmx25M</argLine>
<includes>
<!-- Only include test classes, not test data -->
<include>**/*Test*.class</include>
</includes>
<excludes>
<exclude>**/*AbstractTestCase*</exclude>
<exclude>**/testtools/**</exclude>
<!-- http://jira.codehaus.org/browse/SUREFIRE-44 -->
<exclude>**/*$*</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptors>
<descriptor>src/main/assembly/bin.xml</descriptor>
<descriptor>src/main/assembly/src.xml</descriptor>
</descriptors>
<tarLongFileMode>gnu</tarLongFileMode>
</configuration>
</plugin>
</plugins>
</build>
<reporting>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>2.9.1</version>
<configuration>
<configLocation>${basedir}/checkstyle.xml</configLocation>
<enableRulesSummary>false</enableRulesSummary>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>findbugs-maven-plugin</artifactId>
<version>2.4.0</version>
<configuration>
<threshold>Normal</threshold>
<effort>Default</effort>
<excludeFilterFile>${basedir}/findbugs-exclude-filter.xml</excludeFilterFile>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.rat</groupId>
<artifactId>apache-rat-plugin</artifactId>
<configuration>
<excludes>
<exclude>src/test/resources/**/*.bin</exclude>
<exclude>.pmd</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</reporting>
</project>

View file

@ -0,0 +1,86 @@
package org.apache.commons.io;
import java.io.Serializable;
public class ByteOrderMark implements Serializable {
private static final long serialVersionUID = 1L;
public static final ByteOrderMark UTF_8 = new ByteOrderMark("UTF-8", new int[] { 239, 187, 191 });
public static final ByteOrderMark UTF_16BE = new ByteOrderMark("UTF-16BE", new int[] { 254, 255 });
public static final ByteOrderMark UTF_16LE = new ByteOrderMark("UTF-16LE", new int[] { 255, 254 });
public static final ByteOrderMark UTF_32BE = new ByteOrderMark("UTF-32BE", new int[] { 0, 0, 254, 255 });
public static final ByteOrderMark UTF_32LE = new ByteOrderMark("UTF-32LE", new int[] { 255, 254, 0, 0 });
private final String charsetName;
private final int[] bytes;
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);
}
public String getCharsetName() {
return this.charsetName;
}
public int length() {
return this.bytes.length;
}
public int get(int pos) {
return this.bytes[pos];
}
public byte[] getBytes() {
byte[] copy = new byte[this.bytes.length];
for (int i = 0; i < this.bytes.length; i++)
copy[i] = (byte)this.bytes[i];
return copy;
}
public boolean equals(Object obj) {
if (!(obj instanceof ByteOrderMark))
return false;
ByteOrderMark bom = (ByteOrderMark)obj;
if (this.bytes.length != bom.length())
return false;
for (int i = 0; i < this.bytes.length; i++) {
if (this.bytes[i] != bom.get(i))
return false;
}
return true;
}
public int hashCode() {
int hashCode = getClass().hashCode();
for (int b : this.bytes)
hashCode += b;
return hashCode;
}
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(getClass().getSimpleName());
builder.append('[');
builder.append(this.charsetName);
builder.append(": ");
for (int i = 0; i < this.bytes.length; i++) {
if (i > 0)
builder.append(",");
builder.append("0x");
builder.append(Integer.toHexString(0xFF & this.bytes[i]).toUpperCase());
}
builder.append(']');
return builder.toString();
}
}

View file

@ -0,0 +1,25 @@
package org.apache.commons.io;
import java.nio.charset.Charset;
public class Charsets {
public static Charset toCharset(Charset charset) {
return (charset == null) ? Charset.defaultCharset() : charset;
}
public static Charset toCharset(String charset) {
return (charset == null) ? Charset.defaultCharset() : Charset.forName(charset);
}
public static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1");
public static final Charset US_ASCII = Charset.forName("US-ASCII");
public static final Charset UTF_16 = Charset.forName("UTF-16");
public static final Charset UTF_16BE = Charset.forName("UTF-16BE");
public static final Charset UTF_16LE = Charset.forName("UTF-16LE");
public static final Charset UTF_8 = Charset.forName("UTF-8");
}

View file

@ -0,0 +1,79 @@
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;
@Deprecated
public class CopyUtils {
private static final int DEFAULT_BUFFER_SIZE = 4096;
public static void copy(byte[] input, OutputStream output) throws IOException {
output.write(input);
}
public static void copy(byte[] input, Writer output) throws IOException {
ByteArrayInputStream in = new ByteArrayInputStream(input);
copy(in, output);
}
public static void copy(byte[] input, Writer output, String encoding) throws IOException {
ByteArrayInputStream in = new ByteArrayInputStream(input);
copy(in, output, encoding);
}
public static int copy(InputStream input, OutputStream output) throws IOException {
byte[] buffer = new byte[4096];
int count = 0;
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
}
return count;
}
public static int copy(Reader input, Writer output) throws IOException {
char[] buffer = new char[4096];
int count = 0;
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
}
return count;
}
public static void copy(InputStream input, Writer output) throws IOException {
InputStreamReader in = new InputStreamReader(input);
copy(in, output);
}
public static void copy(InputStream input, Writer output, String encoding) throws IOException {
InputStreamReader in = new InputStreamReader(input, encoding);
copy(in, output);
}
public static void copy(Reader input, OutputStream output) throws IOException {
OutputStreamWriter out = new OutputStreamWriter(output);
copy(input, out);
out.flush();
}
public static void copy(String input, OutputStream output) throws IOException {
StringReader in = new StringReader(input);
OutputStreamWriter out = new OutputStreamWriter(output);
copy(in, out);
out.flush();
}
public static void copy(String input, Writer output) throws IOException {
output.write(input);
}
}

View file

@ -0,0 +1,136 @@
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;
public abstract class DirectoryWalker<T> {
private final FileFilter filter;
private final int depthLimit;
protected DirectoryWalker() {
this(null, -1);
}
protected DirectoryWalker(FileFilter filter, int depthLimit) {
this.filter = filter;
this.depthLimit = depthLimit;
}
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;
}
protected final void walk(File startDirectory, Collection<T> 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);
}
}
private void walk(File directory, int depth, Collection<T> results) throws IOException {
checkIfCancelled(directory, depth, results);
if (handleDirectory(directory, depth, results)) {
handleDirectoryStart(directory, depth, results);
int childDepth = depth + 1;
if (this.depthLimit < 0 || childDepth <= this.depthLimit) {
checkIfCancelled(directory, depth, results);
File[] childFiles = (this.filter == null) ? directory.listFiles() : directory.listFiles(this.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);
}
protected final void checkIfCancelled(File file, int depth, Collection<T> results) throws IOException {
if (handleIsCancelled(file, depth, results))
throw new CancelException(file, depth);
}
protected boolean handleIsCancelled(File file, int depth, Collection<T> results) throws IOException {
return false;
}
protected void handleCancelled(File startDirectory, Collection<T> results, CancelException cancel) throws IOException {
throw cancel;
}
protected void handleStart(File startDirectory, Collection<T> results) throws IOException {}
protected boolean handleDirectory(File directory, int depth, Collection<T> results) throws IOException {
return true;
}
protected void handleDirectoryStart(File directory, int depth, Collection<T> results) throws IOException {}
protected File[] filterDirectoryContents(File directory, int depth, File[] files) throws IOException {
return files;
}
protected void handleFile(File file, int depth, Collection<T> results) throws IOException {}
protected void handleRestricted(File directory, int depth, Collection<T> results) throws IOException {}
protected void handleDirectoryEnd(File directory, int depth, Collection<T> results) throws IOException {}
protected void handleEnd(Collection<T> results) throws IOException {}
public static class CancelException extends IOException {
private static final long serialVersionUID = 1347339620135041008L;
private final File file;
private final int depth;
public CancelException(File file, int depth) {
this("Operation Cancelled", file, depth);
}
public CancelException(String message, File file, int depth) {
super(message);
this.file = file;
this.depth = depth;
}
public File getFile() {
return this.file;
}
public int getDepth() {
return this.depth;
}
}
}

View file

@ -0,0 +1,172 @@
package org.apache.commons.io;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class EndianUtils {
public static short swapShort(short value) {
return (short)(((value >> 0 & 0xFF) << 8) + ((value >> 8 & 0xFF) << 0));
}
public static int swapInteger(int value) {
return ((value >> 0 & 0xFF) << 24) + ((value >> 8 & 0xFF) << 16) + ((value >> 16 & 0xFF) << 8) + ((value >> 24 & 0xFF) << 0);
}
public static long swapLong(long value) {
return ((value >> 0L & 0xFFL) << 56L) + ((value >> 8L & 0xFFL) << 48L) + ((value >> 16L & 0xFFL) << 40L) + ((value >> 24L & 0xFFL) << 32L) + ((value >> 32L & 0xFFL) << 24L) + ((value >> 40L & 0xFFL) << 16L) + ((value >> 48L & 0xFFL) << 8L) + ((value >> 56L & 0xFFL) << 0L);
}
public static float swapFloat(float value) {
return Float.intBitsToFloat(swapInteger(Float.floatToIntBits(value)));
}
public static double swapDouble(double value) {
return Double.longBitsToDouble(swapLong(Double.doubleToLongBits(value)));
}
public static void writeSwappedShort(byte[] data, int offset, short value) {
data[offset + 0] = (byte)(value >> 0 & 0xFF);
data[offset + 1] = (byte)(value >> 8 & 0xFF);
}
public static short readSwappedShort(byte[] data, int offset) {
return (short)(((data[offset + 0] & 0xFF) << 0) + ((data[offset + 1] & 0xFF) << 8));
}
public static int readSwappedUnsignedShort(byte[] data, int offset) {
return ((data[offset + 0] & 0xFF) << 0) + ((data[offset + 1] & 0xFF) << 8);
}
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);
}
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);
}
public static long readSwappedUnsignedInteger(byte[] data, int offset) {
long low = (long)(((data[offset + 0] & 0xFF) << 0) + ((data[offset + 1] & 0xFF) << 8) + ((data[offset + 2] & 0xFF) << 16));
long high = (long)(data[offset + 3] & 0xFF);
return (high << 24L) + (0xFFFFFFFFL & low);
}
public static void writeSwappedLong(byte[] data, int offset, long value) {
data[offset + 0] = (byte)(int)(value >> 0L & 0xFFL);
data[offset + 1] = (byte)(int)(value >> 8L & 0xFFL);
data[offset + 2] = (byte)(int)(value >> 16L & 0xFFL);
data[offset + 3] = (byte)(int)(value >> 24L & 0xFFL);
data[offset + 4] = (byte)(int)(value >> 32L & 0xFFL);
data[offset + 5] = (byte)(int)(value >> 40L & 0xFFL);
data[offset + 6] = (byte)(int)(value >> 48L & 0xFFL);
data[offset + 7] = (byte)(int)(value >> 56L & 0xFFL);
}
public static long readSwappedLong(byte[] data, int offset) {
long low = (long)(((data[offset + 0] & 0xFF) << 0) + ((data[offset + 1] & 0xFF) << 8) + ((data[offset + 2] & 0xFF) << 16) + ((data[offset + 3] & 0xFF) << 24));
long high = (long)(((data[offset + 4] & 0xFF) << 0) + ((data[offset + 5] & 0xFF) << 8) + ((data[offset + 6] & 0xFF) << 16) + ((data[offset + 7] & 0xFF) << 24));
return (high << 32L) + (0xFFFFFFFFL & low);
}
public static void writeSwappedFloat(byte[] data, int offset, float value) {
writeSwappedInteger(data, offset, Float.floatToIntBits(value));
}
public static float readSwappedFloat(byte[] data, int offset) {
return Float.intBitsToFloat(readSwappedInteger(data, offset));
}
public static void writeSwappedDouble(byte[] data, int offset, double value) {
writeSwappedLong(data, offset, Double.doubleToLongBits(value));
}
public static double readSwappedDouble(byte[] data, int offset) {
return Double.longBitsToDouble(readSwappedLong(data, offset));
}
public static void writeSwappedShort(OutputStream output, short value) throws IOException {
output.write((byte)(value >> 0 & 0xFF));
output.write((byte)(value >> 8 & 0xFF));
}
public static short readSwappedShort(InputStream input) throws IOException {
return (short)(((read(input) & 0xFF) << 0) + ((read(input) & 0xFF) << 8));
}
public static int readSwappedUnsignedShort(InputStream input) throws IOException {
int value1 = read(input);
int value2 = read(input);
return ((value1 & 0xFF) << 0) + ((value2 & 0xFF) << 8);
}
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));
}
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);
}
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 = (long)(((value1 & 0xFF) << 0) + ((value2 & 0xFF) << 8) + ((value3 & 0xFF) << 16));
long high = (long)(value4 & 0xFF);
return (high << 24L) + (0xFFFFFFFFL & low);
}
public static void writeSwappedLong(OutputStream output, long value) throws IOException {
output.write((byte)(int)(value >> 0L & 0xFFL));
output.write((byte)(int)(value >> 8L & 0xFFL));
output.write((byte)(int)(value >> 16L & 0xFFL));
output.write((byte)(int)(value >> 24L & 0xFFL));
output.write((byte)(int)(value >> 32L & 0xFFL));
output.write((byte)(int)(value >> 40L & 0xFFL));
output.write((byte)(int)(value >> 48L & 0xFFL));
output.write((byte)(int)(value >> 56L & 0xFFL));
}
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);
}
public static void writeSwappedFloat(OutputStream output, float value) throws IOException {
writeSwappedInteger(output, Float.floatToIntBits(value));
}
public static float readSwappedFloat(InputStream input) throws IOException {
return Float.intBitsToFloat(readSwappedInteger(input));
}
public static void writeSwappedDouble(OutputStream output, double value) throws IOException {
writeSwappedLong(output, Double.doubleToLongBits(value));
}
public static double readSwappedDouble(InputStream input) throws IOException {
return Double.longBitsToDouble(readSwappedLong(input));
}
private static int read(InputStream input) throws IOException {
int value = input.read();
if (-1 == value)
throw new EOFException("Unexpected EOF reached");
return value;
}
}

View file

@ -0,0 +1,42 @@
package org.apache.commons.io;
import java.io.File;
@Deprecated
public class FileCleaner {
static final FileCleaningTracker theInstance = new FileCleaningTracker();
@Deprecated
public static void track(File file, Object marker) {
theInstance.track(file, marker);
}
@Deprecated
public static void track(File file, Object marker, FileDeleteStrategy deleteStrategy) {
theInstance.track(file, marker, deleteStrategy);
}
@Deprecated
public static void track(String path, Object marker) {
theInstance.track(path, marker);
}
@Deprecated
public static void track(String path, Object marker, FileDeleteStrategy deleteStrategy) {
theInstance.track(path, marker, deleteStrategy);
}
@Deprecated
public static int getTrackCount() {
return theInstance.getTrackCount();
}
@Deprecated
public static synchronized void exitWhenFinished() {
theInstance.exitWhenFinished();
}
public static FileCleaningTracker getInstance() {
return theInstance;
}
}

View file

@ -0,0 +1,108 @@
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;
public class FileCleaningTracker {
ReferenceQueue<Object> q = new ReferenceQueue();
final Collection<Tracker> trackers = Collections.<Tracker>synchronizedSet(new HashSet<Tracker>());
final List<String> deleteFailures = Collections.<String>synchronizedList(new ArrayList<String>());
volatile boolean exitWhenFinished = false;
Thread reaper;
public void track(File file, Object marker) {
track(file, marker, (FileDeleteStrategy)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);
}
public void track(String path, Object marker) {
track(path, marker, (FileDeleteStrategy)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);
}
private synchronized void addTracker(String path, Object marker, FileDeleteStrategy deleteStrategy) {
if (this.exitWhenFinished)
throw new IllegalStateException("No new trackers can be added once exitWhenFinished() is called");
if (this.reaper == null) {
this.reaper = new Reaper();
this.reaper.start();
}
this.trackers.add(new Tracker(path, deleteStrategy, marker, this.q));
}
public int getTrackCount() {
return this.trackers.size();
}
public List<String> getDeleteFailures() {
return this.deleteFailures;
}
public synchronized void exitWhenFinished() {
this.exitWhenFinished = true;
if (this.reaper != null)
synchronized (this.reaper) {
this.reaper.interrupt();
}
}
private final class Reaper extends Thread {
Reaper() {
super("File Reaper");
setPriority(10);
setDaemon(true);
}
public void run() {
while (!FileCleaningTracker.this.exitWhenFinished || FileCleaningTracker.this.trackers.size() > 0) {
try {
FileCleaningTracker.Tracker tracker = (FileCleaningTracker.Tracker)FileCleaningTracker.this.q.remove();
FileCleaningTracker.this.trackers.remove(tracker);
if (!tracker.delete())
FileCleaningTracker.this.deleteFailures.add(tracker.getPath());
tracker.clear();
} catch (InterruptedException e) {}
}
}
}
private static final class Tracker extends PhantomReference<Object> {
private final String path;
private final FileDeleteStrategy deleteStrategy;
Tracker(String path, FileDeleteStrategy deleteStrategy, Object marker, ReferenceQueue<? super Object> queue) {
super(marker, queue);
this.path = path;
this.deleteStrategy = (deleteStrategy == null) ? FileDeleteStrategy.NORMAL : deleteStrategy;
}
public String getPath() {
return this.path;
}
public boolean delete() {
return this.deleteStrategy.deleteQuietly(new File(this.path));
}
}
}

View file

@ -0,0 +1,50 @@
package org.apache.commons.io;
import java.io.File;
import java.io.IOException;
public class FileDeleteStrategy {
public static final FileDeleteStrategy NORMAL = new FileDeleteStrategy("Normal");
public static final FileDeleteStrategy FORCE = new ForceFileDeleteStrategy();
private final String name;
protected FileDeleteStrategy(String name) {
this.name = name;
}
public boolean deleteQuietly(File fileToDelete) {
if (fileToDelete == null || !fileToDelete.exists())
return true;
try {
return doDelete(fileToDelete);
} catch (IOException ex) {
return false;
}
}
public void delete(File fileToDelete) throws IOException {
if (fileToDelete.exists() && !doDelete(fileToDelete))
throw new IOException("Deletion failed: " + fileToDelete);
}
protected boolean doDelete(File fileToDelete) throws IOException {
return fileToDelete.delete();
}
public String toString() {
return "FileDeleteStrategy[" + this.name + "]";
}
static class ForceFileDeleteStrategy extends FileDeleteStrategy {
ForceFileDeleteStrategy() {
super("Force");
}
protected boolean doDelete(File fileToDelete) throws IOException {
FileUtils.forceDelete(fileToDelete);
return true;
}
}
}

View file

@ -0,0 +1,18 @@
package org.apache.commons.io;
import java.io.File;
import java.io.IOException;
public class FileExistsException extends IOException {
private static final long serialVersionUID = 1L;
public FileExistsException() {}
public FileExistsException(String message) {
super(message);
}
public FileExistsException(File file) {
super("File " + file + " exists");
}
}

View file

@ -0,0 +1,224 @@
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.io.Reader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.StringTokenizer;
public class FileSystemUtils {
private static final FileSystemUtils INSTANCE = new FileSystemUtils();
private static final int INIT_PROBLEM = -1;
private static final int OTHER = 0;
private static final int WINDOWS = 1;
private static final int UNIX = 2;
private static final int POSIX_UNIX = 3;
private static final int OS;
private static final String DF;
static {
int os = 0;
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);
if (osName.indexOf("windows") != -1) {
os = 1;
} 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 = 2;
} else if (osName.indexOf("sun os") != -1 || osName.indexOf("sunos") != -1 || osName.indexOf("solaris") != -1) {
os = 3;
dfPath = "/usr/xpg4/bin/df";
} else if (osName.indexOf("hp-ux") != -1 || osName.indexOf("aix") != -1) {
os = 3;
} else {
os = 0;
}
} catch (Exception ex) {
os = -1;
}
OS = os;
DF = dfPath;
}
@Deprecated
public static long freeSpace(String path) throws IOException {
return INSTANCE.freeSpaceOS(path, OS, false, -1L);
}
public static long freeSpaceKb(String path) throws IOException {
return freeSpaceKb(path, -1L);
}
public static long freeSpaceKb(String path, long timeout) throws IOException {
return INSTANCE.freeSpaceOS(path, OS, true, timeout);
}
public static long freeSpaceKb() throws IOException {
return freeSpaceKb(-1L);
}
public static long freeSpaceKb(long timeout) throws IOException {
return freeSpaceKb(new File(".").getAbsolutePath(), timeout);
}
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 1:
return kb ? (freeSpaceWindows(path, timeout) / 1024L) : freeSpaceWindows(path, timeout);
case 2:
return freeSpaceUnix(path, kb, false, timeout);
case 3:
return freeSpaceUnix(path, kb, true, timeout);
case 0:
throw new IllegalStateException("Unsupported operating system");
}
throw new IllegalStateException("Exception caught when determining operating system");
}
long freeSpaceWindows(String path, long timeout) throws IOException {
path = FilenameUtils.normalize(path, false);
if (path.length() > 0 && path.charAt(0) != '"')
path = "\"" + path + "\"";
String[] cmdAttribs = { "cmd.exe", "/C", "dir /a /-c " + path };
List<String> lines = performCommand(cmdAttribs, Integer.MAX_VALUE, timeout);
for (int i = lines.size() - 1; i >= 0; i--) {
String line = lines.get(i);
if (line.length() > 0)
return parseDir(line, path);
}
throw new IOException("Command line 'dir /-c' did not return any info for path '" + path + "'");
}
long parseDir(String line, String path) throws IOException {
int bytesStart = 0;
int bytesEnd = 0;
int j = line.length() - 1;
while (j >= 0) {
char c = line.charAt(j);
if (Character.isDigit(c)) {
bytesEnd = j + 1;
break;
}
j--;
}
while (j >= 0) {
char c = line.charAt(j);
if (!Character.isDigit(c) && c != ',' && c != '.') {
bytesStart = j + 1;
break;
}
j--;
}
if (j < 0)
throw new IOException("Command line 'dir /-c' did not return valid info for path '" + path + "'");
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);
}
long freeSpaceUnix(String path, boolean kb, boolean posix, long timeout) throws IOException {
if (path.length() == 0)
throw new IllegalArgumentException("Path must not be empty");
String flags = "-";
if (kb)
flags = flags + "k";
if (posix)
flags = flags + "P";
String[] cmdAttribs = (flags.length() > 1) ? new String[] { DF, flags, path } : new String[] { DF, path };
List<String> lines = performCommand(cmdAttribs, 3, timeout);
if (lines.size() < 2)
throw new IOException("Command line '" + DF + "' did not return info as expected " + "for path '" + path + "'- response was " + lines);
String line2 = lines.get(1);
StringTokenizer tok = new StringTokenizer(line2, " ");
if (tok.countTokens() < 4) {
if (tok.countTokens() == 1 && lines.size() >= 3) {
String line3 = lines.get(2);
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();
}
tok.nextToken();
tok.nextToken();
String freeSpace = tok.nextToken();
return parseBytes(freeSpace, path);
}
long parseBytes(String freeSpace, String path) throws IOException {
try {
long bytes = Long.parseLong(freeSpace);
if (bytes < 0L)
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);
}
}
List<String> performCommand(String[] cmdAttribs, int max, long timeout) throws IOException {
List<String> lines = new ArrayList<String>(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)
throw new IOException("Command line returned OS error code '" + proc.exitValue() + "' for command " + Arrays.asList(cmdAttribs));
if (lines.isEmpty())
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((Reader)inr);
if (proc != null)
proc.destroy();
}
}
Process openProcess(String[] cmdAttribs) throws IOException {
return Runtime.getRuntime().exec(cmdAttribs);
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,473 @@
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;
public class FilenameUtils {
public static final char EXTENSION_SEPARATOR = '.';
public static final String EXTENSION_SEPARATOR_STR = Character.toString('.');
private static final char UNIX_SEPARATOR = '/';
private static final char WINDOWS_SEPARATOR = '\\';
private static final char SYSTEM_SEPARATOR = File.separatorChar;
private static final char OTHER_SEPARATOR;
static {
if (isSystemWindows()) {
OTHER_SEPARATOR = '/';
} else {
OTHER_SEPARATOR = '\\';
}
}
static boolean isSystemWindows() {
return (SYSTEM_SEPARATOR == '\\');
}
private static boolean isSeparator(char ch) {
return (ch == '/' || ch == '\\');
}
public static String normalize(String filename) {
return doNormalize(filename, SYSTEM_SEPARATOR, true);
}
public static String normalize(String filename, boolean unixSeparator) {
char separator = unixSeparator ? '/' : '\\';
return doNormalize(filename, separator, true);
}
public static String normalizeNoEndSeparator(String filename) {
return doNormalize(filename, SYSTEM_SEPARATOR, false);
}
public static String normalizeNoEndSeparator(String filename, boolean unixSeparator) {
char separator = unixSeparator ? '/' : '\\';
return doNormalize(filename, separator, false);
}
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];
filename.getChars(0, filename.length(), array, 0);
char otherSeparator = (separator == SYSTEM_SEPARATOR) ? OTHER_SEPARATOR : SYSTEM_SEPARATOR;
for (int i = 0; i < array.length; i++) {
if (array[i] == otherSeparator)
array[i] = separator;
}
boolean lastIsDirectory = true;
if (array[size - 1] != separator) {
array[size++] = separator;
lastIsDirectory = false;
}
for (int m = prefix + 1; m < size; m++) {
if (array[m] == separator && array[m - 1] == separator) {
System.arraycopy(array, m, array, m - 1, size - m);
size--;
m--;
}
}
for (int k = prefix + 1; k < size; k++) {
if (array[k] == separator && array[k - 1] == '.' && (k == prefix + 1 || array[k - 2] == separator)) {
if (k == size - 1)
lastIsDirectory = true;
System.arraycopy(array, k + 1, array, k - 1, size - k);
size -= 2;
k--;
}
}
for (int j = prefix + 2; j < size; j++) {
if (array[j] == separator && array[j - 1] == '.' && array[j - 2] == '.' && (j == prefix + 2 || array[j - 3] == separator)) {
if (j == prefix + 2)
return null;
if (j == size - 1)
lastIsDirectory = true;
int n = j - 4;
while (true) {
if (n >= prefix) {
if (array[n] == separator) {
System.arraycopy(array, j + 1, array, n + 1, size - j);
size -= j - n;
j = n + 1;
break;
}
n--;
continue;
}
System.arraycopy(array, j + 1, array, prefix, size - j);
size -= j + 1 - prefix;
j = prefix + 1;
break;
}
}
}
if (size <= 0)
return "";
if (size <= prefix)
return new String(array, 0, size);
if (lastIsDirectory && keepSeparator)
return new String(array, 0, size);
return new String(array, 0, size - 1);
}
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);
return normalize(basePath + '/' + fullFilenameToAdd);
}
public static boolean directoryContains(String canonicalParent, String canonicalChild) throws IOException {
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);
}
public static String separatorsToUnix(String path) {
if (path == null || path.indexOf('\\') == -1)
return path;
return path.replace('\\', '/');
}
public static String separatorsToWindows(String path) {
if (path == null || path.indexOf('/') == -1)
return path;
return path.replace('/', '\\');
}
public static String separatorsToSystem(String path) {
if (path == null)
return null;
if (isSystemWindows())
return separatorsToWindows(path);
return separatorsToUnix(path);
}
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 isSeparator(ch0) ? 1 : 0;
}
if (ch0 == '~') {
int posUnix = filename.indexOf('/', 1);
int posWin = filename.indexOf('\\', 1);
if (posUnix == -1 && posWin == -1)
return len + 1;
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)))
return 2;
return 3;
}
return -1;
}
if (isSeparator(ch0) && isSeparator(ch1)) {
int posUnix = filename.indexOf('/', 2);
int posWin = filename.indexOf('\\', 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;
}
return isSeparator(ch0) ? 1 : 0;
}
public static int indexOfLastSeparator(String filename) {
if (filename == null)
return -1;
int lastUnixPos = filename.lastIndexOf('/');
int lastWindowsPos = filename.lastIndexOf('\\');
return Math.max(lastUnixPos, lastWindowsPos);
}
public static int indexOfExtension(String filename) {
if (filename == null)
return -1;
int extensionPos = filename.lastIndexOf('.');
int lastSeparator = indexOfLastSeparator(filename);
return (lastSeparator > extensionPos) ? -1 : extensionPos;
}
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 + '/';
return filename.substring(0, len);
}
public static String getPath(String filename) {
return doGetPath(filename, 1);
}
public static String getPathNoEndSeparator(String filename) {
return doGetPath(filename, 0);
}
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);
}
public static String getFullPath(String filename) {
return doGetFullPath(filename, true);
}
public static String getFullPathNoEndSeparator(String filename) {
return doGetFullPath(filename, false);
}
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);
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);
}
public static String getName(String filename) {
if (filename == null)
return null;
int index = indexOfLastSeparator(filename);
return filename.substring(index + 1);
}
public static String getBaseName(String filename) {
return removeExtension(getName(filename));
}
public static String getExtension(String filename) {
if (filename == null)
return null;
int index = indexOfExtension(filename);
if (index == -1)
return "";
return filename.substring(index + 1);
}
public static String removeExtension(String filename) {
if (filename == null)
return null;
int index = indexOfExtension(filename);
if (index == -1)
return filename;
return filename.substring(0, index);
}
public static boolean equals(String filename1, String filename2) {
return equals(filename1, filename2, false, IOCase.SENSITIVE);
}
public static boolean equalsOnSystem(String filename1, String filename2) {
return equals(filename1, filename2, false, IOCase.SYSTEM);
}
public static boolean equalsNormalized(String filename1, String filename2) {
return equals(filename1, filename2, true, IOCase.SENSITIVE);
}
public static boolean equalsNormalizedOnSystem(String filename1, String filename2) {
return equals(filename1, filename2, true, IOCase.SYSTEM);
}
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);
}
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);
}
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;
}
public static boolean isExtension(String filename, Collection<String> 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;
}
public static boolean wildcardMatch(String filename, String wildcardMatcher) {
return wildcardMatch(filename, wildcardMatcher, IOCase.SENSITIVE);
}
public static boolean wildcardMatchOnSystem(String filename, String wildcardMatcher) {
return wildcardMatch(filename, wildcardMatcher, IOCase.SYSTEM);
}
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<int[]> backtrack = new Stack<int[]>();
do {
if (backtrack.size() > 0) {
int[] array = backtrack.pop();
wcsIdx = array[0];
textIdx = array[1];
anyChars = true;
}
while (wcsIdx < wcs.length) {
if (wcs[wcsIdx].equals("?")) {
textIdx++;
if (textIdx > filename.length())
break;
anyChars = false;
} else if (wcs[wcsIdx].equals("*")) {
anyChars = true;
if (wcsIdx == wcs.length - 1)
textIdx = filename.length();
} else {
if (anyChars) {
textIdx = caseSensitivity.checkIndexOf(filename, textIdx, wcs[wcsIdx]);
if (textIdx == -1)
break;
int repeat = caseSensitivity.checkIndexOf(filename, textIdx + 1, wcs[wcsIdx]);
if (repeat >= 0)
backtrack.push(new int[] { wcsIdx, repeat });
} else if (!caseSensitivity.checkRegionMatches(filename, textIdx, wcs[wcsIdx])) {
break;
}
textIdx += wcs[wcsIdx].length();
anyChars = false;
}
wcsIdx++;
}
if (wcsIdx == wcs.length && textIdx == filename.length())
return true;
} while (backtrack.size() > 0);
return false;
}
static String[] splitOnTokens(String text) {
if (text.indexOf('?') == -1 && text.indexOf('*') == -1)
return new String[] { text };
char[] array = text.toCharArray();
ArrayList<String> list = new ArrayList<String>();
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("*"))) {
list.add("*");
}
} else {
buffer.append(array[i]);
}
}
if (buffer.length() != 0)
list.add(buffer.toString());
return list.<String>toArray(new String[list.size()]);
}
}

View file

@ -0,0 +1,61 @@
package org.apache.commons.io;
import java.io.IOException;
import java.io.OutputStream;
public class HexDump {
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 + (long)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 i = 0; i < 16; i++) {
if (i < chars_read) {
dump(buffer, data[i + j]);
} else {
buffer.append(" ");
}
buffer.append(' ');
}
for (int k = 0; k < chars_read; k++) {
if (data[k + j] >= 32 && data[k + j] < Byte.MAX_VALUE) {
buffer.append((char)data[k + j]);
} else {
buffer.append('.');
}
}
buffer.append(EOL);
stream.write(buffer.toString().getBytes());
stream.flush();
buffer.setLength(0);
display_offset += (long)chars_read;
}
}
public static final String EOL = System.getProperty("line.separator");
private static final char[] _hexcodes = new char[] {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F' };
private static final int[] _shifts = new int[] { 28, 24, 20, 16, 12, 8, 4, 0 };
private static StringBuilder dump(StringBuilder _lbuffer, long value) {
for (int j = 0; j < 8; j++)
_lbuffer.append(_hexcodes[(int)(value >> _shifts[j]) & 0xF]);
return _lbuffer;
}
private static StringBuilder dump(StringBuilder _cbuffer, byte value) {
for (int j = 0; j < 2; j++)
_cbuffer.append(_hexcodes[value >> _shifts[j + 6] & 0xF]);
return _cbuffer;
}
}

View file

@ -0,0 +1,83 @@
package org.apache.commons.io;
import java.io.Serializable;
public final class IOCase implements Serializable {
public static final IOCase SENSITIVE = new IOCase("Sensitive", true);
public static final IOCase INSENSITIVE = new IOCase("Insensitive", false);
public static final IOCase SYSTEM = new IOCase("System", !FilenameUtils.isSystemWindows());
private static final long serialVersionUID = -6343169151696340687L;
private final String name;
private final transient boolean sensitive;
public static IOCase forName(String name) {
if (SENSITIVE.name.equals(name))
return SENSITIVE;
if (INSENSITIVE.name.equals(name))
return INSENSITIVE;
if (SYSTEM.name.equals(name))
return SYSTEM;
throw new IllegalArgumentException("Invalid IOCase name: " + name);
}
private IOCase(String name, boolean sensitive) {
this.name = name;
this.sensitive = sensitive;
}
private Object readResolve() {
return forName(this.name);
}
public String getName() {
return this.name;
}
public boolean isCaseSensitive() {
return this.sensitive;
}
public int checkCompareTo(String str1, String str2) {
if (str1 == null || str2 == null)
throw new NullPointerException("The strings must not be null");
return this.sensitive ? str1.compareTo(str2) : str1.compareToIgnoreCase(str2);
}
public boolean checkEquals(String str1, String str2) {
if (str1 == null || str2 == null)
throw new NullPointerException("The strings must not be null");
return this.sensitive ? str1.equals(str2) : str1.equalsIgnoreCase(str2);
}
public boolean checkStartsWith(String str, String start) {
return str.regionMatches(!this.sensitive, 0, start, 0, start.length());
}
public boolean checkEndsWith(String str, String end) {
int endLen = end.length();
return str.regionMatches(!this.sensitive, str.length() - endLen, end, 0, endLen);
}
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;
}
public boolean checkRegionMatches(String str, int strStartIndex, String search) {
return str.regionMatches(!this.sensitive, strStartIndex, search, 0, search.length());
}
public String toString() {
return this.name;
}
}

View file

@ -0,0 +1,17 @@
package org.apache.commons.io;
import java.io.IOException;
public class IOExceptionWithCause extends IOException {
private static final long serialVersionUID = 1L;
public IOExceptionWithCause(String message, Throwable cause) {
super(message);
initCause(cause);
}
public IOExceptionWithCause(Throwable cause) {
super((cause == null) ? null : cause.toString());
initCause(cause);
}
}

View file

@ -0,0 +1,706 @@
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.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.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.commons.io.output.StringBuilderWriter;
public class IOUtils {
private static final int EOF = -1;
public static final char DIR_SEPARATOR_UNIX = '/';
public static final char DIR_SEPARATOR_WINDOWS = '\\';
public static final char DIR_SEPARATOR = File.separatorChar;
public static final String LINE_SEPARATOR_UNIX = "\n";
public static final String LINE_SEPARATOR_WINDOWS = "\r\n";
public static final String LINE_SEPARATOR;
private static final int DEFAULT_BUFFER_SIZE = 4096;
private static final int SKIP_BUFFER_SIZE = 2048;
private static char[] SKIP_CHAR_BUFFER;
private static byte[] SKIP_BYTE_BUFFER;
static {
StringBuilderWriter buf = new StringBuilderWriter(4);
PrintWriter out = new PrintWriter(buf);
out.println();
LINE_SEPARATOR = buf.toString();
out.close();
}
public static void close(URLConnection conn) {
if (conn instanceof HttpURLConnection)
((HttpURLConnection)conn).disconnect();
}
public static void closeQuietly(Reader input) {
closeQuietly((Closeable)input);
}
public static void closeQuietly(Writer output) {
closeQuietly((Closeable)output);
}
public static void closeQuietly(InputStream input) {
closeQuietly((Closeable)input);
}
public static void closeQuietly(OutputStream output) {
closeQuietly((Closeable)output);
}
public static void closeQuietly(Closeable closeable) {
try {
if (closeable != null)
closeable.close();
} catch (IOException ioe) {}
}
public static void closeQuietly(Socket sock) {
if (sock != null)
try {
sock.close();
} catch (IOException ioe) {}
}
public static void closeQuietly(Selector selector) {
if (selector != null)
try {
selector.close();
} catch (IOException ioe) {}
}
public static void closeQuietly(ServerSocket sock) {
if (sock != null)
try {
sock.close();
} catch (IOException ioe) {}
}
public static InputStream toBufferedInputStream(InputStream input) throws IOException {
return ByteArrayOutputStream.toBufferedInputStream(input);
}
public static BufferedReader toBufferedReader(Reader reader) {
return (reader instanceof BufferedReader) ? (BufferedReader)reader : new BufferedReader(reader);
}
public static byte[] toByteArray(InputStream input) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
copy(input, output);
return output.toByteArray();
}
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);
}
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)) != -1)
offset += readed;
if (offset != size)
throw new IOException("Unexpected readed size. current: " + offset + ", excepted: " + size);
return data;
}
public static byte[] toByteArray(Reader input) throws IOException {
return toByteArray(input, Charset.defaultCharset());
}
public static byte[] toByteArray(Reader input, Charset encoding) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
copy(input, output, encoding);
return output.toByteArray();
}
public static byte[] toByteArray(Reader input, String encoding) throws IOException {
return toByteArray(input, Charsets.toCharset(encoding));
}
@Deprecated
public static byte[] toByteArray(String input) throws IOException {
return input.getBytes();
}
public static byte[] toByteArray(URI uri) throws IOException {
return toByteArray(uri.toURL());
}
public static byte[] toByteArray(URL url) throws IOException {
URLConnection conn = url.openConnection();
try {
return toByteArray(conn);
} finally {
close(conn);
}
}
public static byte[] toByteArray(URLConnection urlConn) throws IOException {
InputStream inputStream = urlConn.getInputStream();
try {
return toByteArray(inputStream);
} finally {
inputStream.close();
}
}
public static char[] toCharArray(InputStream is) throws IOException {
return toCharArray(is, Charset.defaultCharset());
}
public static char[] toCharArray(InputStream is, Charset encoding) throws IOException {
CharArrayWriter output = new CharArrayWriter();
copy(is, output, encoding);
return output.toCharArray();
}
public static char[] toCharArray(InputStream is, String encoding) throws IOException {
return toCharArray(is, Charsets.toCharset(encoding));
}
public static char[] toCharArray(Reader input) throws IOException {
CharArrayWriter sw = new CharArrayWriter();
copy(input, sw);
return sw.toCharArray();
}
public static String toString(InputStream input) throws IOException {
return toString(input, Charset.defaultCharset());
}
public static String toString(InputStream input, Charset encoding) throws IOException {
StringBuilderWriter sw = new StringBuilderWriter();
copy(input, sw, encoding);
return sw.toString();
}
public static String toString(InputStream input, String encoding) throws IOException {
return toString(input, Charsets.toCharset(encoding));
}
public static String toString(Reader input) throws IOException {
StringBuilderWriter sw = new StringBuilderWriter();
copy(input, sw);
return sw.toString();
}
public static String toString(URI uri) throws IOException {
return toString(uri, Charset.defaultCharset());
}
public static String toString(URI uri, Charset encoding) throws IOException {
return toString(uri.toURL(), Charsets.toCharset(encoding));
}
public static String toString(URI uri, String encoding) throws IOException {
return toString(uri, Charsets.toCharset(encoding));
}
public static String toString(URL url) throws IOException {
return toString(url, Charset.defaultCharset());
}
public static String toString(URL url, Charset encoding) throws IOException {
InputStream inputStream = url.openStream();
try {
return toString(inputStream, encoding);
} finally {
inputStream.close();
}
}
public static String toString(URL url, String encoding) throws IOException {
return toString(url, Charsets.toCharset(encoding));
}
@Deprecated
public static String toString(byte[] input) throws IOException {
return new String(input);
}
public static String toString(byte[] input, String encoding) throws IOException {
return new String(input, Charsets.toCharset(encoding));
}
public static List<String> readLines(InputStream input) throws IOException {
return readLines(input, Charset.defaultCharset());
}
public static List<String> readLines(InputStream input, Charset encoding) throws IOException {
InputStreamReader reader = new InputStreamReader(input, Charsets.toCharset(encoding));
return readLines(reader);
}
public static List<String> readLines(InputStream input, String encoding) throws IOException {
return readLines(input, Charsets.toCharset(encoding));
}
public static List<String> readLines(Reader input) throws IOException {
BufferedReader reader = toBufferedReader(input);
List<String> list = new ArrayList<String>();
String line = reader.readLine();
while (line != null) {
list.add(line);
line = reader.readLine();
}
return list;
}
public static LineIterator lineIterator(Reader reader) {
return new LineIterator(reader);
}
public static LineIterator lineIterator(InputStream input, Charset encoding) throws IOException {
return new LineIterator(new InputStreamReader(input, Charsets.toCharset(encoding)));
}
public static LineIterator lineIterator(InputStream input, String encoding) throws IOException {
return lineIterator(input, Charsets.toCharset(encoding));
}
public static InputStream toInputStream(CharSequence input) {
return toInputStream(input, Charset.defaultCharset());
}
public static InputStream toInputStream(CharSequence input, Charset encoding) {
return toInputStream(input.toString(), encoding);
}
public static InputStream toInputStream(CharSequence input, String encoding) throws IOException {
return toInputStream(input, Charsets.toCharset(encoding));
}
public static InputStream toInputStream(String input) {
return toInputStream(input, Charset.defaultCharset());
}
public static InputStream toInputStream(String input, Charset encoding) {
return new ByteArrayInputStream(input.getBytes(Charsets.toCharset(encoding)));
}
public static InputStream toInputStream(String input, String encoding) throws IOException {
byte[] bytes = input.getBytes(Charsets.toCharset(encoding));
return new ByteArrayInputStream(bytes);
}
public static void write(byte[] data, OutputStream output) throws IOException {
if (data != null)
output.write(data);
}
public static void write(byte[] data, Writer output) throws IOException {
write(data, output, Charset.defaultCharset());
}
public static void write(byte[] data, Writer output, Charset encoding) throws IOException {
if (data != null)
output.write(new String(data, Charsets.toCharset(encoding)));
}
public static void write(byte[] data, Writer output, String encoding) throws IOException {
write(data, output, Charsets.toCharset(encoding));
}
public static void write(char[] data, Writer output) throws IOException {
if (data != null)
output.write(data);
}
public static void write(char[] data, OutputStream output) throws IOException {
write(data, output, Charset.defaultCharset());
}
public static void write(char[] data, OutputStream output, Charset encoding) throws IOException {
if (data != null)
output.write(new String(data).getBytes(Charsets.toCharset(encoding)));
}
public static void write(char[] data, OutputStream output, String encoding) throws IOException {
write(data, output, Charsets.toCharset(encoding));
}
public static void write(CharSequence data, Writer output) throws IOException {
if (data != null)
write(data.toString(), output);
}
public static void write(CharSequence data, OutputStream output) throws IOException {
write(data, output, Charset.defaultCharset());
}
public static void write(CharSequence data, OutputStream output, Charset encoding) throws IOException {
if (data != null)
write(data.toString(), output, encoding);
}
public static void write(CharSequence data, OutputStream output, String encoding) throws IOException {
write(data, output, Charsets.toCharset(encoding));
}
public static void write(String data, Writer output) throws IOException {
if (data != null)
output.write(data);
}
public static void write(String data, OutputStream output) throws IOException {
write(data, output, Charset.defaultCharset());
}
public static void write(String data, OutputStream output, Charset encoding) throws IOException {
if (data != null)
output.write(data.getBytes(Charsets.toCharset(encoding)));
}
public static void write(String data, OutputStream output, String encoding) throws IOException {
write(data, output, Charsets.toCharset(encoding));
}
@Deprecated
public static void write(StringBuffer data, Writer output) throws IOException {
if (data != null)
output.write(data.toString());
}
@Deprecated
public static void write(StringBuffer data, OutputStream output) throws IOException {
write(data, output, (String)null);
}
@Deprecated
public static void write(StringBuffer data, OutputStream output, String encoding) throws IOException {
if (data != null)
output.write(data.toString().getBytes(Charsets.toCharset(encoding)));
}
public static void writeLines(Collection<?> lines, String lineEnding, OutputStream output) throws IOException {
writeLines(lines, lineEnding, output, Charset.defaultCharset());
}
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 : (Iterable<Object>)lines) {
if (line != null)
output.write(line.toString().getBytes(cs));
output.write(lineEnding.getBytes(cs));
}
}
public static void writeLines(Collection<?> lines, String lineEnding, OutputStream output, String encoding) throws IOException {
writeLines(lines, lineEnding, output, Charsets.toCharset(encoding));
}
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 : (Iterable<Object>)lines) {
if (line != null)
writer.write(line.toString());
writer.write(lineEnding);
}
}
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;
}
public static long copyLarge(InputStream input, OutputStream output) throws IOException {
return copyLarge(input, output, new byte[4096]);
}
public static long copyLarge(InputStream input, OutputStream output, byte[] buffer) throws IOException {
long count = 0L;
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += (long)n;
}
return count;
}
public static long copyLarge(InputStream input, OutputStream output, long inputOffset, long length) throws IOException {
return copyLarge(input, output, inputOffset, length, new byte[4096]);
}
public static long copyLarge(InputStream input, OutputStream output, long inputOffset, long length, byte[] buffer) throws IOException {
if (inputOffset > 0L)
skipFully(input, inputOffset);
if (length == 0L)
return 0L;
int bufferLength = buffer.length;
int bytesToRead = bufferLength;
if (length > 0L && length < (long)bufferLength)
bytesToRead = (int)length;
long totalRead = 0L;
int read;
while (bytesToRead > 0 && -1 != (read = input.read(buffer, 0, bytesToRead))) {
output.write(buffer, 0, read);
totalRead += (long)read;
if (length > 0L)
bytesToRead = (int)Math.min(length - totalRead, (long)bufferLength);
}
return totalRead;
}
public static void copy(InputStream input, Writer output) throws IOException {
copy(input, output, Charset.defaultCharset());
}
public static void copy(InputStream input, Writer output, Charset encoding) throws IOException {
InputStreamReader in = new InputStreamReader(input, Charsets.toCharset(encoding));
copy(in, output);
}
public static void copy(InputStream input, Writer output, String encoding) throws IOException {
copy(input, output, Charsets.toCharset(encoding));
}
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;
}
public static long copyLarge(Reader input, Writer output) throws IOException {
return copyLarge(input, output, new char[4096]);
}
public static long copyLarge(Reader input, Writer output, char[] buffer) throws IOException {
long count = 0L;
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += (long)n;
}
return count;
}
public static long copyLarge(Reader input, Writer output, long inputOffset, long length) throws IOException {
return copyLarge(input, output, inputOffset, length, new char[4096]);
}
public static long copyLarge(Reader input, Writer output, long inputOffset, long length, char[] buffer) throws IOException {
if (inputOffset > 0L)
skipFully(input, inputOffset);
if (length == 0L)
return 0L;
int bytesToRead = buffer.length;
if (length > 0L && length < (long)buffer.length)
bytesToRead = (int)length;
long totalRead = 0L;
int read;
while (bytesToRead > 0 && -1 != (read = input.read(buffer, 0, bytesToRead))) {
output.write(buffer, 0, read);
totalRead += (long)read;
if (length > 0L)
bytesToRead = (int)Math.min(length - totalRead, (long)buffer.length);
}
return totalRead;
}
public static void copy(Reader input, OutputStream output) throws IOException {
copy(input, output, Charset.defaultCharset());
}
public static void copy(Reader input, OutputStream output, Charset encoding) throws IOException {
OutputStreamWriter out = new OutputStreamWriter(output, Charsets.toCharset(encoding));
copy(input, out);
out.flush();
}
public static void copy(Reader input, OutputStream output, String encoding) throws IOException {
copy(input, output, Charsets.toCharset(encoding));
}
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 (-1 != ch) {
int i = input2.read();
if (ch != i)
return false;
ch = input1.read();
}
int ch2 = input2.read();
return (ch2 == -1);
}
public static boolean contentEquals(Reader input1, Reader input2) throws IOException {
input1 = toBufferedReader(input1);
input2 = toBufferedReader(input2);
int ch = input1.read();
while (-1 != ch) {
int i = input2.read();
if (ch != i)
return false;
ch = input1.read();
}
int ch2 = input2.read();
return (ch2 == -1);
}
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)) : line1.equals(line2);
}
public static long skip(InputStream input, long toSkip) throws IOException {
if (toSkip < 0L)
throw new IllegalArgumentException("Skip count must be non-negative, actual: " + toSkip);
if (SKIP_BYTE_BUFFER == null)
SKIP_BYTE_BUFFER = new byte[2048];
long remain = toSkip;
while (remain > 0L) {
long n = (long)input.read(SKIP_BYTE_BUFFER, 0, (int)Math.min(remain, 2048L));
if (n < 0L)
break;
remain -= n;
}
return toSkip - remain;
}
public static long skip(Reader input, long toSkip) throws IOException {
if (toSkip < 0L)
throw new IllegalArgumentException("Skip count must be non-negative, actual: " + toSkip);
if (SKIP_CHAR_BUFFER == null)
SKIP_CHAR_BUFFER = new char[2048];
long remain = toSkip;
while (remain > 0L) {
long n = (long)input.read(SKIP_CHAR_BUFFER, 0, (int)Math.min(remain, 2048L));
if (n < 0L)
break;
remain -= n;
}
return toSkip - remain;
}
public static void skipFully(InputStream input, long toSkip) throws IOException {
if (toSkip < 0L)
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);
}
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);
}
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 (-1 == count)
break;
remaining -= count;
}
return length - remaining;
}
public static int read(Reader input, char[] buffer) throws IOException {
return read(input, buffer, 0, buffer.length);
}
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 (-1 == count)
break;
remaining -= count;
}
return length - remaining;
}
public static int read(InputStream input, byte[] buffer) throws IOException {
return read(input, buffer, 0, buffer.length);
}
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);
}
public static void readFully(Reader input, char[] buffer) throws IOException {
readFully(input, buffer, 0, buffer.length);
}
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);
}
public static void readFully(InputStream input, byte[] buffer) throws IOException {
readFully(input, buffer, 0, buffer.length);
}
}

View file

@ -0,0 +1,79 @@
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;
public class LineIterator implements Iterator<String> {
private final BufferedReader bufferedReader;
private String cachedLine;
private boolean finished = false;
public LineIterator(Reader reader) throws IllegalArgumentException {
if (reader == null)
throw new IllegalArgumentException("Reader must not be null");
if (reader instanceof BufferedReader) {
this.bufferedReader = (BufferedReader)reader;
} else {
this.bufferedReader = new BufferedReader(reader);
}
}
public boolean hasNext() {
if (this.cachedLine != null)
return true;
if (this.finished)
return false;
try {
while (true) {
String line = this.bufferedReader.readLine();
if (line == null) {
this.finished = true;
return false;
}
if (isValidLine(line)) {
this.cachedLine = line;
return true;
}
}
} catch (IOException ioe) {
close();
throw new IllegalStateException(ioe);
}
}
protected boolean isValidLine(String line) {
return true;
}
public String next() {
return nextLine();
}
public String nextLine() {
if (!hasNext())
throw new NoSuchElementException("No more lines");
String currentLine = this.cachedLine;
this.cachedLine = null;
return currentLine;
}
public void close() {
this.finished = true;
IOUtils.closeQuietly((Reader)this.bufferedReader);
this.cachedLine = null;
}
public void remove() {
throw new UnsupportedOperationException("Remove unsupported on LineIterator");
}
public static void closeQuietly(LineIterator iterator) {
if (iterator != null)
iterator.close();
}
}

View file

@ -0,0 +1,32 @@
package org.apache.commons.io;
import java.io.IOException;
import java.io.Serializable;
public class TaggedIOException extends IOExceptionWithCause {
private static final long serialVersionUID = -6994123481142850163L;
private final Serializable tag;
public static boolean isTaggedWith(Throwable throwable, Object tag) {
return (tag != null && throwable instanceof TaggedIOException && tag.equals(((TaggedIOException)throwable).tag));
}
public static void throwCauseIfTaggedWith(Throwable throwable, Object tag) throws IOException {
if (isTaggedWith(throwable, tag))
throw ((TaggedIOException)throwable).getCause();
}
public TaggedIOException(IOException original, Serializable tag) {
super(original.getMessage(), original);
this.tag = tag;
}
public Serializable getTag() {
return this.tag;
}
public IOException getCause() {
return (IOException)super.getCause();
}
}

View file

@ -0,0 +1,39 @@
package org.apache.commons.io;
class ThreadMonitor implements Runnable {
private final Thread thread;
private final long timeout;
public static Thread start(long timeout) {
return start(Thread.currentThread(), timeout);
}
public static Thread start(Thread thread, long timeout) {
Thread monitor = null;
if (timeout > 0L) {
ThreadMonitor timout = new ThreadMonitor(thread, timeout);
monitor = new Thread(timout, ThreadMonitor.class.getSimpleName());
monitor.setDaemon(true);
monitor.start();
}
return monitor;
}
public static void stop(Thread thread) {
if (thread != null)
thread.interrupt();
}
private ThreadMonitor(Thread thread, long timeout) {
this.thread = thread;
this.timeout = timeout;
}
public void run() {
try {
Thread.sleep(this.timeout);
this.thread.interrupt();
} catch (InterruptedException e) {}
}
}

View file

@ -0,0 +1,25 @@
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 class AbstractFileComparator implements Comparator<File> {
public File[] sort(File... files) {
if (files != null)
Arrays.<File>sort(files, this);
return files;
}
public List<File> sort(List<File> files) {
if (files != null)
Collections.<File>sort(files, this);
return files;
}
public String toString() {
return getClass().getSimpleName();
}
}

View file

@ -0,0 +1,56 @@
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;
public class CompositeFileComparator extends AbstractFileComparator implements Serializable {
private static final Comparator<?>[] NO_COMPARATORS = new Comparator[0];
private final Comparator<File>[] delegates;
public CompositeFileComparator(Comparator<File>... delegates) {
if (delegates == null) {
this.delegates = (Comparator[])NO_COMPARATORS;
} else {
this.delegates = new Comparator[delegates.length];
System.arraycopy(delegates, 0, this.delegates, 0, delegates.length);
}
}
public CompositeFileComparator(Iterable<Comparator<File>> delegates) {
if (delegates == null) {
this.delegates = (Comparator[])NO_COMPARATORS;
} else {
List<Comparator<File>> list = new ArrayList<Comparator<File>>();
for (Comparator<File> comparator : delegates)
list.add(comparator);
this.delegates = list.<Comparator<File>>toArray(new Comparator[list.size()]);
}
}
public int compare(File file1, File file2) {
int result = 0;
for (Comparator<File> delegate : this.delegates) {
result = delegate.compare(file1, file2);
if (result != 0)
break;
}
return result;
}
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(super.toString());
builder.append('{');
for (int i = 0; i < this.delegates.length; i++) {
if (i > 0)
builder.append(',');
builder.append(this.delegates[i]);
}
builder.append('}');
return builder.toString();
}
}

View file

@ -0,0 +1,16 @@
package org.apache.commons.io.comparator;
import java.io.File;
import java.io.Serializable;
import java.util.Comparator;
import java.util.List;
public class DefaultFileComparator extends AbstractFileComparator implements Serializable {
public static final Comparator<File> DEFAULT_COMPARATOR = new DefaultFileComparator();
public static final Comparator<File> DEFAULT_REVERSE = new ReverseComparator(DEFAULT_COMPARATOR);
public int compare(File file1, File file2) {
return file1.compareTo(file2);
}
}

View file

@ -0,0 +1,22 @@
package org.apache.commons.io.comparator;
import java.io.File;
import java.io.Serializable;
import java.util.Comparator;
import java.util.List;
public class DirectoryFileComparator extends AbstractFileComparator implements Serializable {
public static final Comparator<File> DIRECTORY_COMPARATOR = new DirectoryFileComparator();
public static final Comparator<File> DIRECTORY_REVERSE = new ReverseComparator(DIRECTORY_COMPARATOR);
public int compare(File file1, File file2) {
return getType(file1) - getType(file2);
}
private int getType(File file) {
if (file.isDirectory())
return 1;
return 2;
}
}

View file

@ -0,0 +1,42 @@
package org.apache.commons.io.comparator;
import java.io.File;
import java.io.Serializable;
import java.util.Comparator;
import java.util.List;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOCase;
public class ExtensionFileComparator extends AbstractFileComparator implements Serializable {
public static final Comparator<File> EXTENSION_COMPARATOR = new ExtensionFileComparator();
public static final Comparator<File> EXTENSION_REVERSE = new ReverseComparator(EXTENSION_COMPARATOR);
public static final Comparator<File> EXTENSION_INSENSITIVE_COMPARATOR = new ExtensionFileComparator(IOCase.INSENSITIVE);
public static final Comparator<File> EXTENSION_INSENSITIVE_REVERSE = new ReverseComparator(EXTENSION_INSENSITIVE_COMPARATOR);
public static final Comparator<File> EXTENSION_SYSTEM_COMPARATOR = new ExtensionFileComparator(IOCase.SYSTEM);
public static final Comparator<File> EXTENSION_SYSTEM_REVERSE = new ReverseComparator(EXTENSION_SYSTEM_COMPARATOR);
private final IOCase caseSensitivity;
public ExtensionFileComparator() {
this.caseSensitivity = IOCase.SENSITIVE;
}
public ExtensionFileComparator(IOCase caseSensitivity) {
this.caseSensitivity = (caseSensitivity == null) ? IOCase.SENSITIVE : caseSensitivity;
}
public int compare(File file1, File file2) {
String suffix1 = FilenameUtils.getExtension(file1.getName());
String suffix2 = FilenameUtils.getExtension(file2.getName());
return this.caseSensitivity.checkCompareTo(suffix1, suffix2);
}
public String toString() {
return super.toString() + "[caseSensitivity=" + this.caseSensitivity + "]";
}
}

View file

@ -0,0 +1,21 @@
package org.apache.commons.io.comparator;
import java.io.File;
import java.io.Serializable;
import java.util.Comparator;
import java.util.List;
public class LastModifiedFileComparator extends AbstractFileComparator implements Serializable {
public static final Comparator<File> LASTMODIFIED_COMPARATOR = new LastModifiedFileComparator();
public static final Comparator<File> LASTMODIFIED_REVERSE = new ReverseComparator(LASTMODIFIED_COMPARATOR);
public int compare(File file1, File file2) {
long result = file1.lastModified() - file2.lastModified();
if (result < 0L)
return -1;
if (result > 0L)
return 1;
return 0;
}
}

View file

@ -0,0 +1,39 @@
package org.apache.commons.io.comparator;
import java.io.File;
import java.io.Serializable;
import java.util.Comparator;
import java.util.List;
import org.apache.commons.io.IOCase;
public class NameFileComparator extends AbstractFileComparator implements Serializable {
public static final Comparator<File> NAME_COMPARATOR = new NameFileComparator();
public static final Comparator<File> NAME_REVERSE = new ReverseComparator(NAME_COMPARATOR);
public static final Comparator<File> NAME_INSENSITIVE_COMPARATOR = new NameFileComparator(IOCase.INSENSITIVE);
public static final Comparator<File> NAME_INSENSITIVE_REVERSE = new ReverseComparator(NAME_INSENSITIVE_COMPARATOR);
public static final Comparator<File> NAME_SYSTEM_COMPARATOR = new NameFileComparator(IOCase.SYSTEM);
public static final Comparator<File> NAME_SYSTEM_REVERSE = new ReverseComparator(NAME_SYSTEM_COMPARATOR);
private final IOCase caseSensitivity;
public NameFileComparator() {
this.caseSensitivity = IOCase.SENSITIVE;
}
public NameFileComparator(IOCase caseSensitivity) {
this.caseSensitivity = (caseSensitivity == null) ? IOCase.SENSITIVE : caseSensitivity;
}
public int compare(File file1, File file2) {
return this.caseSensitivity.checkCompareTo(file1.getName(), file2.getName());
}
public String toString() {
return super.toString() + "[caseSensitivity=" + this.caseSensitivity + "]";
}
}

View file

@ -0,0 +1,39 @@
package org.apache.commons.io.comparator;
import java.io.File;
import java.io.Serializable;
import java.util.Comparator;
import java.util.List;
import org.apache.commons.io.IOCase;
public class PathFileComparator extends AbstractFileComparator implements Serializable {
public static final Comparator<File> PATH_COMPARATOR = new PathFileComparator();
public static final Comparator<File> PATH_REVERSE = new ReverseComparator(PATH_COMPARATOR);
public static final Comparator<File> PATH_INSENSITIVE_COMPARATOR = new PathFileComparator(IOCase.INSENSITIVE);
public static final Comparator<File> PATH_INSENSITIVE_REVERSE = new ReverseComparator(PATH_INSENSITIVE_COMPARATOR);
public static final Comparator<File> PATH_SYSTEM_COMPARATOR = new PathFileComparator(IOCase.SYSTEM);
public static final Comparator<File> PATH_SYSTEM_REVERSE = new ReverseComparator(PATH_SYSTEM_COMPARATOR);
private final IOCase caseSensitivity;
public PathFileComparator() {
this.caseSensitivity = IOCase.SENSITIVE;
}
public PathFileComparator(IOCase caseSensitivity) {
this.caseSensitivity = (caseSensitivity == null) ? IOCase.SENSITIVE : caseSensitivity;
}
public int compare(File file1, File file2) {
return this.caseSensitivity.checkCompareTo(file1.getPath(), file2.getPath());
}
public String toString() {
return super.toString() + "[caseSensitivity=" + this.caseSensitivity + "]";
}
}

View file

@ -0,0 +1,23 @@
package org.apache.commons.io.comparator;
import java.io.File;
import java.io.Serializable;
import java.util.Comparator;
class ReverseComparator extends AbstractFileComparator implements Serializable {
private final Comparator<File> delegate;
public ReverseComparator(Comparator<File> delegate) {
if (delegate == null)
throw new IllegalArgumentException("Delegate comparator is missing");
this.delegate = delegate;
}
public int compare(File file1, File file2) {
return this.delegate.compare(file2, file1);
}
public String toString() {
return super.toString() + "[" + this.delegate.toString() + "]";
}
}

View file

@ -0,0 +1,52 @@
package org.apache.commons.io.comparator;
import java.io.File;
import java.io.Serializable;
import java.util.Comparator;
import java.util.List;
import org.apache.commons.io.FileUtils;
public class SizeFileComparator extends AbstractFileComparator implements Serializable {
public static final Comparator<File> SIZE_COMPARATOR = new SizeFileComparator();
public static final Comparator<File> SIZE_REVERSE = new ReverseComparator(SIZE_COMPARATOR);
public static final Comparator<File> SIZE_SUMDIR_COMPARATOR = new SizeFileComparator(true);
public static final Comparator<File> SIZE_SUMDIR_REVERSE = new ReverseComparator(SIZE_SUMDIR_COMPARATOR);
private final boolean sumDirectoryContents;
public SizeFileComparator() {
this.sumDirectoryContents = false;
}
public SizeFileComparator(boolean sumDirectoryContents) {
this.sumDirectoryContents = sumDirectoryContents;
}
public int compare(File file1, File file2) {
long size1 = 0L;
if (file1.isDirectory()) {
size1 = (this.sumDirectoryContents && file1.exists()) ? FileUtils.sizeOfDirectory(file1) : 0L;
} else {
size1 = file1.length();
}
long size2 = 0L;
if (file2.isDirectory()) {
size2 = (this.sumDirectoryContents && file2.exists()) ? FileUtils.sizeOfDirectory(file2) : 0L;
} else {
size2 = file2.length();
}
long result = size1 - size2;
if (result < 0L)
return -1;
if (result > 0L)
return 1;
return 0;
}
public String toString() {
return super.toString() + "[sumDirectoryContents=" + this.sumDirectoryContents + "]";
}
}

View file

@ -0,0 +1,17 @@
package org.apache.commons.io.filefilter;
import java.io.File;
public abstract class AbstractFileFilter implements IOFileFilter {
public boolean accept(File file) {
return accept(file.getParentFile(), file.getName());
}
public boolean accept(File dir, String name) {
return accept(new File(dir, name));
}
public String toString() {
return getClass().getSimpleName();
}
}

View file

@ -0,0 +1,47 @@
package org.apache.commons.io.filefilter;
import java.io.File;
import java.io.Serializable;
import java.util.Date;
import org.apache.commons.io.FileUtils;
public class AgeFileFilter extends AbstractFileFilter implements Serializable {
private final long cutoff;
private final boolean acceptOlder;
public AgeFileFilter(long cutoff) {
this(cutoff, true);
}
public AgeFileFilter(long cutoff, boolean acceptOlder) {
this.acceptOlder = acceptOlder;
this.cutoff = cutoff;
}
public AgeFileFilter(Date cutoffDate) {
this(cutoffDate, true);
}
public AgeFileFilter(Date cutoffDate, boolean acceptOlder) {
this(cutoffDate.getTime(), acceptOlder);
}
public AgeFileFilter(File cutoffReference) {
this(cutoffReference, true);
}
public AgeFileFilter(File cutoffReference, boolean acceptOlder) {
this(cutoffReference.lastModified(), acceptOlder);
}
public boolean accept(File file) {
boolean newer = FileUtils.isFileNewer(file, this.cutoff);
return this.acceptOlder ? (!newer) : newer;
}
public String toString() {
String condition = this.acceptOlder ? "<=" : ">";
return super.toString() + "(" + condition + this.cutoff + ")";
}
}

View file

@ -0,0 +1,83 @@
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;
public class AndFileFilter extends AbstractFileFilter implements ConditionalFileFilter, Serializable {
private final List<IOFileFilter> fileFilters;
public AndFileFilter() {
this.fileFilters = new ArrayList<IOFileFilter>();
}
public AndFileFilter(List<IOFileFilter> fileFilters) {
if (fileFilters == null) {
this.fileFilters = new ArrayList<IOFileFilter>();
} else {
this.fileFilters = new ArrayList<IOFileFilter>(fileFilters);
}
}
public AndFileFilter(IOFileFilter filter1, IOFileFilter filter2) {
if (filter1 == null || filter2 == null)
throw new IllegalArgumentException("The filters must not be null");
this.fileFilters = new ArrayList<IOFileFilter>(2);
addFileFilter(filter1);
addFileFilter(filter2);
}
public void addFileFilter(IOFileFilter ioFileFilter) {
this.fileFilters.add(ioFileFilter);
}
public List<IOFileFilter> getFileFilters() {
return Collections.<IOFileFilter>unmodifiableList(this.fileFilters);
}
public boolean removeFileFilter(IOFileFilter ioFileFilter) {
return this.fileFilters.remove(ioFileFilter);
}
public void setFileFilters(List<IOFileFilter> fileFilters) {
this.fileFilters.clear();
this.fileFilters.addAll(fileFilters);
}
public boolean accept(File file) {
if (this.fileFilters.isEmpty())
return false;
for (IOFileFilter fileFilter : this.fileFilters) {
if (!fileFilter.accept(file))
return false;
}
return true;
}
public boolean accept(File file, String name) {
if (this.fileFilters.isEmpty())
return false;
for (IOFileFilter fileFilter : this.fileFilters) {
if (!fileFilter.accept(file, name))
return false;
}
return true;
}
public String toString() {
StringBuilder buffer = new StringBuilder();
buffer.append(super.toString());
buffer.append("(");
if (this.fileFilters != null)
for (int i = 0; i < this.fileFilters.size(); i++) {
if (i > 0)
buffer.append(",");
Object filter = this.fileFilters.get(i);
buffer.append((filter == null) ? "null" : filter.toString());
}
buffer.append(")");
return buffer.toString();
}
}

View file

@ -0,0 +1,16 @@
package org.apache.commons.io.filefilter;
import java.io.File;
import java.io.Serializable;
public class CanReadFileFilter extends AbstractFileFilter implements Serializable {
public static final IOFileFilter CAN_READ = new CanReadFileFilter();
public static final IOFileFilter CANNOT_READ = new NotFileFilter(CAN_READ);
public static final IOFileFilter READ_ONLY = new AndFileFilter(CAN_READ, CanWriteFileFilter.CANNOT_WRITE);
public boolean accept(File file) {
return file.canRead();
}
}

View file

@ -0,0 +1,14 @@
package org.apache.commons.io.filefilter;
import java.io.File;
import java.io.Serializable;
public class CanWriteFileFilter extends AbstractFileFilter implements Serializable {
public static final IOFileFilter CAN_WRITE = new CanWriteFileFilter();
public static final IOFileFilter CANNOT_WRITE = new NotFileFilter(CAN_WRITE);
public boolean accept(File file) {
return file.canWrite();
}
}

View file

@ -0,0 +1,13 @@
package org.apache.commons.io.filefilter;
import java.util.List;
public interface ConditionalFileFilter {
void addFileFilter(IOFileFilter paramIOFileFilter);
List<IOFileFilter> getFileFilters();
boolean removeFileFilter(IOFileFilter paramIOFileFilter);
void setFileFilters(List<IOFileFilter> paramList);
}

View file

@ -0,0 +1,43 @@
package org.apache.commons.io.filefilter;
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.io.Serializable;
public class DelegateFileFilter extends AbstractFileFilter implements Serializable {
private final FilenameFilter filenameFilter;
private final FileFilter fileFilter;
public DelegateFileFilter(FilenameFilter filter) {
if (filter == null)
throw new IllegalArgumentException("The FilenameFilter must not be null");
this.filenameFilter = filter;
this.fileFilter = null;
}
public DelegateFileFilter(FileFilter filter) {
if (filter == null)
throw new IllegalArgumentException("The FileFilter must not be null");
this.fileFilter = filter;
this.filenameFilter = null;
}
public boolean accept(File file) {
if (this.fileFilter != null)
return this.fileFilter.accept(file);
return super.accept(file);
}
public boolean accept(File dir, String name) {
if (this.filenameFilter != null)
return this.filenameFilter.accept(dir, name);
return super.accept(dir, name);
}
public String toString() {
String delegate = (this.fileFilter != null) ? this.fileFilter.toString() : this.filenameFilter.toString();
return super.toString() + "(" + delegate + ")";
}
}

View file

@ -0,0 +1,14 @@
package org.apache.commons.io.filefilter;
import java.io.File;
import java.io.Serializable;
public class DirectoryFileFilter extends AbstractFileFilter implements Serializable {
public static final IOFileFilter DIRECTORY = new DirectoryFileFilter();
public static final IOFileFilter INSTANCE = DIRECTORY;
public boolean accept(File file) {
return file.isDirectory();
}
}

View file

@ -0,0 +1,18 @@
package org.apache.commons.io.filefilter;
import java.io.File;
import java.io.Serializable;
public class EmptyFileFilter extends AbstractFileFilter implements Serializable {
public static final IOFileFilter EMPTY = new EmptyFileFilter();
public static final IOFileFilter NOT_EMPTY = new NotFileFilter(EMPTY);
public boolean accept(File file) {
if (file.isDirectory()) {
File[] files = file.listFiles();
return (files == null || files.length == 0);
}
return (file.length() == 0L);
}
}

View file

@ -0,0 +1,18 @@
package org.apache.commons.io.filefilter;
import java.io.File;
import java.io.Serializable;
public class FalseFileFilter implements IOFileFilter, Serializable {
public static final IOFileFilter FALSE = new FalseFileFilter();
public static final IOFileFilter INSTANCE = FALSE;
public boolean accept(File file) {
return false;
}
public boolean accept(File dir, String name) {
return false;
}
}

View file

@ -0,0 +1,12 @@
package org.apache.commons.io.filefilter;
import java.io.File;
import java.io.Serializable;
public class FileFileFilter extends AbstractFileFilter implements Serializable {
public static final IOFileFilter FILE = new FileFileFilter();
public boolean accept(File file) {
return file.isFile();
}
}

View file

@ -0,0 +1,229 @@
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.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.io.IOCase;
public class FileFilterUtils {
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<File> acceptedFiles = new ArrayList<File>();
for (File file : files) {
if (file == null)
throw new IllegalArgumentException("file array contains null");
if (filter.accept(file))
acceptedFiles.add(file);
}
return acceptedFiles.<File>toArray(new File[acceptedFiles.size()]);
}
public static File[] filter(IOFileFilter filter, Iterable<File> files) {
List<File> acceptedFiles = filterList(filter, files);
return acceptedFiles.<File>toArray(new File[acceptedFiles.size()]);
}
public static List<File> filterList(IOFileFilter filter, Iterable<File> files) {
return FileFilterUtils.<List<File>>filter(filter, files, new ArrayList<File>());
}
public static List<File> filterList(IOFileFilter filter, File... files) {
File[] acceptedFiles = filter(filter, files);
return Arrays.<File>asList(acceptedFiles);
}
public static Set<File> filterSet(IOFileFilter filter, File... files) {
File[] acceptedFiles = filter(filter, files);
return new HashSet<File>(Arrays.<File>asList(acceptedFiles));
}
public static Set<File> filterSet(IOFileFilter filter, Iterable<File> files) {
return FileFilterUtils.<Set<File>>filter(filter, files, new HashSet<File>());
}
private static <T extends java.util.Collection<File>> T filter(IOFileFilter filter, Iterable<File> 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;
}
public static IOFileFilter prefixFileFilter(String prefix) {
return new PrefixFileFilter(prefix);
}
public static IOFileFilter prefixFileFilter(String prefix, IOCase caseSensitivity) {
return new PrefixFileFilter(prefix, caseSensitivity);
}
public static IOFileFilter suffixFileFilter(String suffix) {
return new SuffixFileFilter(suffix);
}
public static IOFileFilter suffixFileFilter(String suffix, IOCase caseSensitivity) {
return new SuffixFileFilter(suffix, caseSensitivity);
}
public static IOFileFilter nameFileFilter(String name) {
return new NameFileFilter(name);
}
public static IOFileFilter nameFileFilter(String name, IOCase caseSensitivity) {
return new NameFileFilter(name, caseSensitivity);
}
public static IOFileFilter directoryFileFilter() {
return DirectoryFileFilter.DIRECTORY;
}
public static IOFileFilter fileFileFilter() {
return FileFileFilter.FILE;
}
@Deprecated
public static IOFileFilter andFileFilter(IOFileFilter filter1, IOFileFilter filter2) {
return new AndFileFilter(filter1, filter2);
}
@Deprecated
public static IOFileFilter orFileFilter(IOFileFilter filter1, IOFileFilter filter2) {
return new OrFileFilter(filter1, filter2);
}
public static IOFileFilter and(IOFileFilter... filters) {
return new AndFileFilter(toList(filters));
}
public static IOFileFilter or(IOFileFilter... filters) {
return new OrFileFilter(toList(filters));
}
public static List<IOFileFilter> toList(IOFileFilter... filters) {
if (filters == null)
throw new IllegalArgumentException("The filters must not be null");
List<IOFileFilter> list = new ArrayList<IOFileFilter>(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;
}
public static IOFileFilter notFileFilter(IOFileFilter filter) {
return new NotFileFilter(filter);
}
public static IOFileFilter trueFileFilter() {
return TrueFileFilter.TRUE;
}
public static IOFileFilter falseFileFilter() {
return FalseFileFilter.FALSE;
}
public static IOFileFilter asFileFilter(FileFilter filter) {
return new DelegateFileFilter(filter);
}
public static IOFileFilter asFileFilter(FilenameFilter filter) {
return new DelegateFileFilter(filter);
}
public static IOFileFilter ageFileFilter(long cutoff) {
return new AgeFileFilter(cutoff);
}
public static IOFileFilter ageFileFilter(long cutoff, boolean acceptOlder) {
return new AgeFileFilter(cutoff, acceptOlder);
}
public static IOFileFilter ageFileFilter(Date cutoffDate) {
return new AgeFileFilter(cutoffDate);
}
public static IOFileFilter ageFileFilter(Date cutoffDate, boolean acceptOlder) {
return new AgeFileFilter(cutoffDate, acceptOlder);
}
public static IOFileFilter ageFileFilter(File cutoffReference) {
return new AgeFileFilter(cutoffReference);
}
public static IOFileFilter ageFileFilter(File cutoffReference, boolean acceptOlder) {
return new AgeFileFilter(cutoffReference, acceptOlder);
}
public static IOFileFilter sizeFileFilter(long threshold) {
return new SizeFileFilter(threshold);
}
public static IOFileFilter sizeFileFilter(long threshold, boolean acceptLarger) {
return new SizeFileFilter(threshold, acceptLarger);
}
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);
}
public static IOFileFilter magicNumberFileFilter(String magicNumber) {
return new MagicNumberFileFilter(magicNumber);
}
public static IOFileFilter magicNumberFileFilter(String magicNumber, long offset) {
return new MagicNumberFileFilter(magicNumber, offset);
}
public static IOFileFilter magicNumberFileFilter(byte[] magicNumber) {
return new MagicNumberFileFilter(magicNumber);
}
public static IOFileFilter magicNumberFileFilter(byte[] magicNumber, long offset) {
return new MagicNumberFileFilter(magicNumber, offset);
}
private static final IOFileFilter cvsFilter = notFileFilter(and(new IOFileFilter[] { directoryFileFilter(), nameFileFilter("CVS") }));
private static final IOFileFilter svnFilter = notFileFilter(and(new IOFileFilter[] { directoryFileFilter(), nameFileFilter(".svn") }));
public static IOFileFilter makeCVSAware(IOFileFilter filter) {
if (filter == null)
return cvsFilter;
return and(new IOFileFilter[] { filter, cvsFilter });
}
public static IOFileFilter makeSVNAware(IOFileFilter filter) {
if (filter == null)
return svnFilter;
return and(new IOFileFilter[] { filter, svnFilter });
}
public static IOFileFilter makeDirectoryOnly(IOFileFilter filter) {
if (filter == null)
return DirectoryFileFilter.DIRECTORY;
return new AndFileFilter(DirectoryFileFilter.DIRECTORY, filter);
}
public static IOFileFilter makeFileOnly(IOFileFilter filter) {
if (filter == null)
return FileFileFilter.FILE;
return new AndFileFilter(FileFileFilter.FILE, filter);
}
}

View file

@ -0,0 +1,14 @@
package org.apache.commons.io.filefilter;
import java.io.File;
import java.io.Serializable;
public class HiddenFileFilter extends AbstractFileFilter implements Serializable {
public static final IOFileFilter HIDDEN = new HiddenFileFilter();
public static final IOFileFilter VISIBLE = new NotFileFilter(HIDDEN);
public boolean accept(File file) {
return file.isHidden();
}
}

View file

@ -0,0 +1,11 @@
package org.apache.commons.io.filefilter;
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
public interface IOFileFilter extends FileFilter, FilenameFilter {
boolean accept(File paramFile);
boolean accept(File paramFile, String paramString);
}

View file

@ -0,0 +1,77 @@
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;
public class MagicNumberFileFilter extends AbstractFileFilter implements Serializable {
private static final long serialVersionUID = -547733176983104172L;
private final byte[] magicNumbers;
private final long byteOffset;
public MagicNumberFileFilter(byte[] magicNumber) {
this(magicNumber, 0L);
}
public MagicNumberFileFilter(String magicNumber) {
this(magicNumber, 0L);
}
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 < 0L)
throw new IllegalArgumentException("The offset cannot be negative");
this.magicNumbers = magicNumber.getBytes();
this.byteOffset = offset;
}
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 < 0L)
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;
}
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(this.byteOffset);
int read = randomAccessFile.read(fileBytes);
if (read != this.magicNumbers.length)
return false;
return Arrays.equals(this.magicNumbers, fileBytes);
} catch (IOException ioe) {
} finally {
IOUtils.closeQuietly(randomAccessFile);
}
}
return false;
}
public String toString() {
StringBuilder builder = new StringBuilder(super.toString());
builder.append("(");
builder.append(new String(this.magicNumbers));
builder.append(",");
builder.append(this.byteOffset);
builder.append(")");
return builder.toString();
}
}

View file

@ -0,0 +1,77 @@
package org.apache.commons.io.filefilter;
import java.io.File;
import java.io.Serializable;
import java.util.List;
import org.apache.commons.io.IOCase;
public class NameFileFilter extends AbstractFileFilter implements Serializable {
private final String[] names;
private final IOCase caseSensitivity;
public NameFileFilter(String name) {
this(name, 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;
}
public NameFileFilter(String[] names) {
this(names, 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;
}
public NameFileFilter(List<String> names) {
this(names, null);
}
public NameFileFilter(List<String> names, IOCase caseSensitivity) {
if (names == null)
throw new IllegalArgumentException("The list of names must not be null");
this.names = names.<String>toArray(new String[names.size()]);
this.caseSensitivity = (caseSensitivity == null) ? IOCase.SENSITIVE : caseSensitivity;
}
public boolean accept(File file) {
String name = file.getName();
for (String name2 : this.names) {
if (this.caseSensitivity.checkEquals(name, name2))
return true;
}
return false;
}
public boolean accept(File dir, String name) {
for (String name2 : this.names) {
if (this.caseSensitivity.checkEquals(name, name2))
return true;
}
return false;
}
public String toString() {
StringBuilder buffer = new StringBuilder();
buffer.append(super.toString());
buffer.append("(");
if (this.names != null)
for (int i = 0; i < this.names.length; i++) {
if (i > 0)
buffer.append(",");
buffer.append(this.names[i]);
}
buffer.append(")");
return buffer.toString();
}
}

View file

@ -0,0 +1,26 @@
package org.apache.commons.io.filefilter;
import java.io.File;
import java.io.Serializable;
public class NotFileFilter extends AbstractFileFilter implements Serializable {
private final IOFileFilter filter;
public NotFileFilter(IOFileFilter filter) {
if (filter == null)
throw new IllegalArgumentException("The filter must not be null");
this.filter = filter;
}
public boolean accept(File file) {
return !this.filter.accept(file);
}
public boolean accept(File file, String name) {
return !this.filter.accept(file, name);
}
public String toString() {
return super.toString() + "(" + this.filter.toString() + ")";
}
}

View file

@ -0,0 +1,79 @@
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;
public class OrFileFilter extends AbstractFileFilter implements ConditionalFileFilter, Serializable {
private final List<IOFileFilter> fileFilters;
public OrFileFilter() {
this.fileFilters = new ArrayList<IOFileFilter>();
}
public OrFileFilter(List<IOFileFilter> fileFilters) {
if (fileFilters == null) {
this.fileFilters = new ArrayList<IOFileFilter>();
} else {
this.fileFilters = new ArrayList<IOFileFilter>(fileFilters);
}
}
public OrFileFilter(IOFileFilter filter1, IOFileFilter filter2) {
if (filter1 == null || filter2 == null)
throw new IllegalArgumentException("The filters must not be null");
this.fileFilters = new ArrayList<IOFileFilter>(2);
addFileFilter(filter1);
addFileFilter(filter2);
}
public void addFileFilter(IOFileFilter ioFileFilter) {
this.fileFilters.add(ioFileFilter);
}
public List<IOFileFilter> getFileFilters() {
return Collections.<IOFileFilter>unmodifiableList(this.fileFilters);
}
public boolean removeFileFilter(IOFileFilter ioFileFilter) {
return this.fileFilters.remove(ioFileFilter);
}
public void setFileFilters(List<IOFileFilter> fileFilters) {
this.fileFilters.clear();
this.fileFilters.addAll(fileFilters);
}
public boolean accept(File file) {
for (IOFileFilter fileFilter : this.fileFilters) {
if (fileFilter.accept(file))
return true;
}
return false;
}
public boolean accept(File file, String name) {
for (IOFileFilter fileFilter : this.fileFilters) {
if (fileFilter.accept(file, name))
return true;
}
return false;
}
public String toString() {
StringBuilder buffer = new StringBuilder();
buffer.append(super.toString());
buffer.append("(");
if (this.fileFilters != null)
for (int i = 0; i < this.fileFilters.size(); i++) {
if (i > 0)
buffer.append(",");
Object filter = this.fileFilters.get(i);
buffer.append((filter == null) ? "null" : filter.toString());
}
buffer.append(")");
return buffer.toString();
}
}

View file

@ -0,0 +1,77 @@
package org.apache.commons.io.filefilter;
import java.io.File;
import java.io.Serializable;
import java.util.List;
import org.apache.commons.io.IOCase;
public class PrefixFileFilter extends AbstractFileFilter implements Serializable {
private final String[] prefixes;
private final IOCase caseSensitivity;
public PrefixFileFilter(String prefix) {
this(prefix, IOCase.SENSITIVE);
}
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;
}
public PrefixFileFilter(String[] prefixes) {
this(prefixes, IOCase.SENSITIVE);
}
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;
}
public PrefixFileFilter(List<String> prefixes) {
this(prefixes, IOCase.SENSITIVE);
}
public PrefixFileFilter(List<String> prefixes, IOCase caseSensitivity) {
if (prefixes == null)
throw new IllegalArgumentException("The list of prefixes must not be null");
this.prefixes = prefixes.<String>toArray(new String[prefixes.size()]);
this.caseSensitivity = (caseSensitivity == null) ? IOCase.SENSITIVE : caseSensitivity;
}
public boolean accept(File file) {
String name = file.getName();
for (String prefix : this.prefixes) {
if (this.caseSensitivity.checkStartsWith(name, prefix))
return true;
}
return false;
}
public boolean accept(File file, String name) {
for (String prefix : this.prefixes) {
if (this.caseSensitivity.checkStartsWith(name, prefix))
return true;
}
return false;
}
public String toString() {
StringBuilder buffer = new StringBuilder();
buffer.append(super.toString());
buffer.append("(");
if (this.prefixes != null)
for (int i = 0; i < this.prefixes.length; i++) {
if (i > 0)
buffer.append(",");
buffer.append(this.prefixes[i]);
}
buffer.append(")");
return buffer.toString();
}
}

View file

@ -0,0 +1,41 @@
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;
public class RegexFileFilter extends AbstractFileFilter implements Serializable {
private final Pattern pattern;
public RegexFileFilter(String pattern) {
if (pattern == null)
throw new IllegalArgumentException("Pattern is missing");
this.pattern = Pattern.compile(pattern);
}
public RegexFileFilter(String pattern, IOCase caseSensitivity) {
if (pattern == null)
throw new IllegalArgumentException("Pattern is missing");
int flags = 0;
if (caseSensitivity != null && !caseSensitivity.isCaseSensitive())
flags = 2;
this.pattern = Pattern.compile(pattern, flags);
}
public RegexFileFilter(String pattern, int flags) {
if (pattern == null)
throw new IllegalArgumentException("Pattern is missing");
this.pattern = Pattern.compile(pattern, flags);
}
public RegexFileFilter(Pattern pattern) {
if (pattern == null)
throw new IllegalArgumentException("Pattern is missing");
this.pattern = pattern;
}
public boolean accept(File dir, String name) {
return this.pattern.matcher(name).matches();
}
}

View file

@ -0,0 +1,31 @@
package org.apache.commons.io.filefilter;
import java.io.File;
import java.io.Serializable;
public class SizeFileFilter extends AbstractFileFilter implements Serializable {
private final long size;
private final boolean acceptLarger;
public SizeFileFilter(long size) {
this(size, true);
}
public SizeFileFilter(long size, boolean acceptLarger) {
if (size < 0L)
throw new IllegalArgumentException("The size must be non-negative");
this.size = size;
this.acceptLarger = acceptLarger;
}
public boolean accept(File file) {
boolean smaller = (file.length() < this.size);
return this.acceptLarger ? (!smaller) : smaller;
}
public String toString() {
String condition = this.acceptLarger ? ">=" : "<";
return super.toString() + "(" + condition + this.size + ")";
}
}

View file

@ -0,0 +1,77 @@
package org.apache.commons.io.filefilter;
import java.io.File;
import java.io.Serializable;
import java.util.List;
import org.apache.commons.io.IOCase;
public class SuffixFileFilter extends AbstractFileFilter implements Serializable {
private final String[] suffixes;
private final IOCase caseSensitivity;
public SuffixFileFilter(String suffix) {
this(suffix, IOCase.SENSITIVE);
}
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;
}
public SuffixFileFilter(String[] suffixes) {
this(suffixes, IOCase.SENSITIVE);
}
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;
}
public SuffixFileFilter(List<String> suffixes) {
this(suffixes, IOCase.SENSITIVE);
}
public SuffixFileFilter(List<String> suffixes, IOCase caseSensitivity) {
if (suffixes == null)
throw new IllegalArgumentException("The list of suffixes must not be null");
this.suffixes = suffixes.<String>toArray(new String[suffixes.size()]);
this.caseSensitivity = (caseSensitivity == null) ? IOCase.SENSITIVE : caseSensitivity;
}
public boolean accept(File file) {
String name = file.getName();
for (String suffix : this.suffixes) {
if (this.caseSensitivity.checkEndsWith(name, suffix))
return true;
}
return false;
}
public boolean accept(File file, String name) {
for (String suffix : this.suffixes) {
if (this.caseSensitivity.checkEndsWith(name, suffix))
return true;
}
return false;
}
public String toString() {
StringBuilder buffer = new StringBuilder();
buffer.append(super.toString());
buffer.append("(");
if (this.suffixes != null)
for (int i = 0; i < this.suffixes.length; i++) {
if (i > 0)
buffer.append(",");
buffer.append(this.suffixes[i]);
}
buffer.append(")");
return buffer.toString();
}
}

View file

@ -0,0 +1,18 @@
package org.apache.commons.io.filefilter;
import java.io.File;
import java.io.Serializable;
public class TrueFileFilter implements IOFileFilter, Serializable {
public static final IOFileFilter TRUE = new TrueFileFilter();
public static final IOFileFilter INSTANCE = TRUE;
public boolean accept(File file) {
return true;
}
public boolean accept(File dir, String name) {
return true;
}
}

View file

@ -0,0 +1,78 @@
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;
public class WildcardFileFilter extends AbstractFileFilter implements Serializable {
private final String[] wildcards;
private final IOCase caseSensitivity;
public WildcardFileFilter(String wildcard) {
this(wildcard, 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;
}
public WildcardFileFilter(String[] wildcards) {
this(wildcards, 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;
}
public WildcardFileFilter(List<String> wildcards) {
this(wildcards, null);
}
public WildcardFileFilter(List<String> wildcards, IOCase caseSensitivity) {
if (wildcards == null)
throw new IllegalArgumentException("The wildcard list must not be null");
this.wildcards = wildcards.<String>toArray(new String[wildcards.size()]);
this.caseSensitivity = (caseSensitivity == null) ? IOCase.SENSITIVE : caseSensitivity;
}
public boolean accept(File dir, String name) {
for (String wildcard : this.wildcards) {
if (FilenameUtils.wildcardMatch(name, wildcard, this.caseSensitivity))
return true;
}
return false;
}
public boolean accept(File file) {
String name = file.getName();
for (String wildcard : this.wildcards) {
if (FilenameUtils.wildcardMatch(name, wildcard, this.caseSensitivity))
return true;
}
return false;
}
public String toString() {
StringBuilder buffer = new StringBuilder();
buffer.append(super.toString());
buffer.append("(");
if (this.wildcards != null)
for (int i = 0; i < this.wildcards.length; i++) {
if (i > 0)
buffer.append(",");
buffer.append(this.wildcards[i]);
}
buffer.append(")");
return buffer.toString();
}
}

View file

@ -0,0 +1,50 @@
package org.apache.commons.io.filefilter;
import java.io.File;
import java.io.Serializable;
import java.util.List;
import org.apache.commons.io.FilenameUtils;
@Deprecated
public class WildcardFilter extends AbstractFileFilter implements Serializable {
private final String[] wildcards;
public WildcardFilter(String wildcard) {
if (wildcard == null)
throw new IllegalArgumentException("The wildcard must not be null");
this.wildcards = new String[] { wildcard };
}
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);
}
public WildcardFilter(List<String> wildcards) {
if (wildcards == null)
throw new IllegalArgumentException("The wildcard list must not be null");
this.wildcards = wildcards.<String>toArray(new String[wildcards.size()]);
}
public boolean accept(File dir, String name) {
if (dir != null && new File(dir, name).isDirectory())
return false;
for (String wildcard : this.wildcards) {
if (FilenameUtils.wildcardMatch(name, wildcard))
return true;
}
return false;
}
public boolean accept(File file) {
if (file.isDirectory())
return false;
for (String wildcard : this.wildcards) {
if (FilenameUtils.wildcardMatch(file.getName(), wildcard))
return true;
}
return false;
}
}

View file

@ -0,0 +1,25 @@
package org.apache.commons.io.input;
import java.io.IOException;
import java.io.InputStream;
public class AutoCloseInputStream extends ProxyInputStream {
public AutoCloseInputStream(InputStream in) {
super(in);
}
public void close() throws IOException {
this.in.close();
this.in = new ClosedInputStream();
}
protected void afterRead(int n) throws IOException {
if (n == -1)
close();
}
protected void finalize() throws Throwable {
close();
super.finalize();
}
}

View file

@ -0,0 +1,161 @@
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;
public class BOMInputStream extends ProxyInputStream {
private final boolean include;
private final List<ByteOrderMark> boms;
private ByteOrderMark byteOrderMark;
private int[] firstBytes;
private int fbLength;
private int fbIndex;
private int markFbIndex;
private boolean markedAtStart;
public BOMInputStream(InputStream delegate) {
this(delegate, false, new ByteOrderMark[] { ByteOrderMark.UTF_8 });
}
public BOMInputStream(InputStream delegate, boolean include) {
this(delegate, include, new ByteOrderMark[] { ByteOrderMark.UTF_8 });
}
public BOMInputStream(InputStream delegate, ByteOrderMark... boms) {
this(delegate, false, boms);
}
private static final Comparator<ByteOrderMark> ByteOrderMarkLengthComparator = new Comparator<ByteOrderMark>() {
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;
}
};
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;
Arrays.<ByteOrderMark>sort(boms, ByteOrderMarkLengthComparator);
this.boms = Arrays.<ByteOrderMark>asList(boms);
}
public boolean hasBOM() throws IOException {
return (getBOM() != null);
}
public boolean hasBOM(ByteOrderMark bom) throws IOException {
if (!this.boms.contains(bom))
throw new IllegalArgumentException("Stream not configure to detect " + bom);
return (this.byteOrderMark != null && getBOM().equals(bom));
}
public ByteOrderMark getBOM() throws IOException {
if (this.firstBytes == null) {
this.fbLength = 0;
int maxBomSize = this.boms.get(0).length();
this.firstBytes = new int[maxBomSize];
for (int i = 0; i < this.firstBytes.length; i++) {
this.firstBytes[i] = this.in.read();
this.fbLength++;
if (this.firstBytes[i] < 0)
break;
}
this.byteOrderMark = find();
if (this.byteOrderMark != null &&
!this.include)
if (this.byteOrderMark.length() < this.firstBytes.length) {
this.fbIndex = this.byteOrderMark.length();
} else {
this.fbLength = 0;
}
}
return this.byteOrderMark;
}
public String getBOMCharsetName() throws IOException {
getBOM();
return (this.byteOrderMark == null) ? null : this.byteOrderMark.getCharsetName();
}
private int readFirstBytes() throws IOException {
getBOM();
return (this.fbIndex < this.fbLength) ? this.firstBytes[this.fbIndex++] : -1;
}
private ByteOrderMark find() {
for (ByteOrderMark bom : this.boms) {
if (matches(bom))
return bom;
}
return null;
}
private boolean matches(ByteOrderMark bom) {
for (int i = 0; i < bom.length(); i++) {
if (bom.get(i) != this.firstBytes[i])
return false;
}
return true;
}
public int read() throws IOException {
int b = readFirstBytes();
return (b >= 0) ? b : this.in.read();
}
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 = this.in.read(buf, off, len);
return (secondCount < 0) ? ((firstCount > 0) ? firstCount : -1) : (firstCount + secondCount);
}
public int read(byte[] buf) throws IOException {
return read(buf, 0, buf.length);
}
public synchronized void mark(int readlimit) {
this.markFbIndex = this.fbIndex;
this.markedAtStart = (this.firstBytes == null);
this.in.mark(readlimit);
}
public synchronized void reset() throws IOException {
this.fbIndex = this.markFbIndex;
if (this.markedAtStart)
this.firstBytes = null;
this.in.reset();
}
public long skip(long n) throws IOException {
while (n > 0L && readFirstBytes() >= 0)
n--;
return this.in.skip(n);
}
}

View file

@ -0,0 +1,92 @@
package org.apache.commons.io.input;
import java.io.IOException;
import java.io.InputStream;
public class BoundedInputStream extends InputStream {
private final InputStream in;
private final long max;
private long pos = 0L;
private long mark = -1L;
private boolean propagateClose = true;
public BoundedInputStream(InputStream in, long size) {
this.max = size;
this.in = in;
}
public BoundedInputStream(InputStream in) {
this(in, -1L);
}
public int read() throws IOException {
if (this.max >= 0L && this.pos >= this.max)
return -1;
int result = this.in.read();
this.pos++;
return result;
}
public int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
public int read(byte[] b, int off, int len) throws IOException {
if (this.max >= 0L && this.pos >= this.max)
return -1;
long maxRead = (this.max >= 0L) ? Math.min((long)len, this.max - this.pos) : (long)len;
int bytesRead = this.in.read(b, off, (int)maxRead);
if (bytesRead == -1)
return -1;
this.pos += (long)bytesRead;
return bytesRead;
}
public long skip(long n) throws IOException {
long toSkip = (this.max >= 0L) ? Math.min(n, this.max - this.pos) : n;
long skippedBytes = this.in.skip(toSkip);
this.pos += skippedBytes;
return skippedBytes;
}
public int available() throws IOException {
if (this.max >= 0L && this.pos >= this.max)
return 0;
return this.in.available();
}
public String toString() {
return this.in.toString();
}
public void close() throws IOException {
if (this.propagateClose)
this.in.close();
}
public synchronized void reset() throws IOException {
this.in.reset();
this.pos = this.mark;
}
public synchronized void mark(int readlimit) {
this.in.mark(readlimit);
this.mark = this.pos;
}
public boolean markSupported() {
return this.in.markSupported();
}
public boolean isPropagateClose() {
return this.propagateClose;
}
public void setPropagateClose(boolean propagateClose) {
this.propagateClose = propagateClose;
}
}

View file

@ -0,0 +1,36 @@
package org.apache.commons.io.input;
import java.io.IOException;
import java.io.InputStream;
public class BrokenInputStream extends InputStream {
private final IOException exception;
public BrokenInputStream(IOException exception) {
this.exception = exception;
}
public BrokenInputStream() {
this(new IOException("Broken input stream"));
}
public int read() throws IOException {
throw this.exception;
}
public int available() throws IOException {
throw this.exception;
}
public long skip(long n) throws IOException {
throw this.exception;
}
public void reset() throws IOException {
throw this.exception;
}
public void close() throws IOException {
throw this.exception;
}
}

View file

@ -0,0 +1,120 @@
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;
public class CharSequenceInputStream extends InputStream {
private final CharsetEncoder encoder;
private final CharBuffer cbuf;
private final ByteBuffer bbuf;
private int mark;
public CharSequenceInputStream(CharSequence s, Charset charset, int bufferSize) {
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;
}
public CharSequenceInputStream(CharSequence s, String charset, int bufferSize) {
this(s, Charset.forName(charset), bufferSize);
}
public CharSequenceInputStream(CharSequence s, Charset charset) {
this(s, charset, 2048);
}
public CharSequenceInputStream(CharSequence s, String charset) {
this(s, charset, 2048);
}
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();
}
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;
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;
continue;
}
fillBuffer();
if (!this.bbuf.hasRemaining() && !this.cbuf.hasRemaining())
break;
}
return (bytesRead == 0 && !this.cbuf.hasRemaining()) ? -1 : bytesRead;
}
public int read() throws IOException {
while (true) {
if (this.bbuf.hasRemaining())
return this.bbuf.get() & 0xFF;
fillBuffer();
if (!this.bbuf.hasRemaining() && !this.cbuf.hasRemaining())
return -1;
}
}
public int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
public long skip(long n) throws IOException {
int skipped = 0;
while (n > 0L && this.cbuf.hasRemaining()) {
this.cbuf.get();
n--;
skipped++;
}
return (long)skipped;
}
public int available() throws IOException {
return this.cbuf.remaining();
}
public void close() throws IOException {}
public synchronized void mark(int readlimit) {
this.mark = this.cbuf.position();
}
public synchronized void reset() throws IOException {
if (this.mark != -1) {
this.cbuf.position(this.mark);
this.mark = -1;
}
}
public boolean markSupported() {
return true;
}
}

View file

@ -0,0 +1,72 @@
package org.apache.commons.io.input;
import java.io.Reader;
import java.io.Serializable;
public class CharSequenceReader extends Reader implements Serializable {
private final CharSequence charSequence;
private int idx;
private int mark;
public CharSequenceReader(CharSequence charSequence) {
this.charSequence = (charSequence != null) ? charSequence : "";
}
public void close() {
this.idx = 0;
this.mark = 0;
}
public void mark(int readAheadLimit) {
this.mark = this.idx;
}
public boolean markSupported() {
return true;
}
public int read() {
if (this.idx >= this.charSequence.length())
return -1;
return this.charSequence.charAt(this.idx++);
}
public int read(char[] array, int offset, int length) {
if (this.idx >= this.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;
}
public void reset() {
this.idx = this.mark;
}
public long skip(long n) {
if (n < 0L)
throw new IllegalArgumentException("Number of characters to skip is less than zero: " + n);
if (this.idx >= this.charSequence.length())
return -1L;
int dest = (int)Math.min((long)this.charSequence.length(), (long)this.idx + n);
int count = dest - this.idx;
this.idx = dest;
return (long)count;
}
public String toString() {
return this.charSequence.toString();
}
}

View file

@ -0,0 +1,35 @@
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;
public class ClassLoaderObjectInputStream extends ObjectInputStream {
private final ClassLoader classLoader;
public ClassLoaderObjectInputStream(ClassLoader classLoader, InputStream inputStream) throws IOException, StreamCorruptedException {
super(inputStream);
this.classLoader = classLoader;
}
protected Class<?> resolveClass(ObjectStreamClass objectStreamClass) throws IOException, ClassNotFoundException {
Class<?> clazz = Class.forName(objectStreamClass.getName(), false, this.classLoader);
if (clazz != null)
return clazz;
return super.resolveClass(objectStreamClass);
}
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, this.classLoader);
try {
return Proxy.getProxyClass(this.classLoader, interfaceClasses);
} catch (IllegalArgumentException e) {
return super.resolveProxyClass(interfaces);
}
}
}

View file

@ -0,0 +1,13 @@
package org.apache.commons.io.input;
import java.io.InputStream;
public class CloseShieldInputStream extends ProxyInputStream {
public CloseShieldInputStream(InputStream in) {
super(in);
}
public void close() {
this.in = new ClosedInputStream();
}
}

View file

@ -0,0 +1,11 @@
package org.apache.commons.io.input;
import java.io.InputStream;
public class ClosedInputStream extends InputStream {
public static final ClosedInputStream CLOSED_INPUT_STREAM = new ClosedInputStream();
public int read() {
return -1;
}
}

View file

@ -0,0 +1,47 @@
package org.apache.commons.io.input;
import java.io.IOException;
import java.io.InputStream;
public class CountingInputStream extends ProxyInputStream {
private long count;
public CountingInputStream(InputStream in) {
super(in);
}
public synchronized long skip(long length) throws IOException {
long skip = super.skip(length);
this.count += skip;
return skip;
}
protected synchronized void afterRead(int n) {
if (n != -1)
this.count += (long)n;
}
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;
}
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;
}
public synchronized long getByteCount() {
return this.count;
}
public synchronized long resetByteCount() {
long tmp = this.count;
this.count = 0L;
return tmp;
}
}

View file

@ -0,0 +1,27 @@
package org.apache.commons.io.input;
import java.io.IOException;
import java.io.InputStream;
public class DemuxInputStream extends InputStream {
private final InheritableThreadLocal<InputStream> m_streams = new InheritableThreadLocal<InputStream>();
public InputStream bindStream(InputStream input) {
InputStream oldValue = this.m_streams.get();
this.m_streams.set(input);
return oldValue;
}
public void close() throws IOException {
InputStream input = this.m_streams.get();
if (null != input)
input.close();
}
public int read() throws IOException {
InputStream input = this.m_streams.get();
if (null != input)
return input.read();
return -1;
}
}

View file

@ -0,0 +1,131 @@
package org.apache.commons.io.input;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
public class NullInputStream extends InputStream {
private final long size;
private long position;
private long mark = -1L;
private long readlimit;
private boolean eof;
private final boolean throwEofException;
private final boolean markSupported;
public NullInputStream(long size) {
this(size, true, false);
}
public NullInputStream(long size, boolean markSupported, boolean throwEofException) {
this.size = size;
this.markSupported = markSupported;
this.throwEofException = throwEofException;
}
public long getPosition() {
return this.position;
}
public long getSize() {
return this.size;
}
public int available() {
long avail = this.size - this.position;
if (avail <= 0L)
return 0;
if (avail > Integer.MAX_VALUE)
return Integer.MAX_VALUE;
return (int)avail;
}
public void close() throws IOException {
this.eof = false;
this.position = 0L;
this.mark = -1L;
}
public synchronized void mark(int readlimit) {
if (!this.markSupported)
throw new UnsupportedOperationException("Mark not supported");
this.mark = this.position;
this.readlimit = (long)readlimit;
}
public boolean markSupported() {
return this.markSupported;
}
public int read() throws IOException {
if (this.eof)
throw new IOException("Read after end of file");
if (this.position == this.size)
return doEndOfFile();
this.position++;
return processByte();
}
public int read(byte[] bytes) throws IOException {
return read(bytes, 0, bytes.length);
}
public int read(byte[] bytes, int offset, int length) throws IOException {
if (this.eof)
throw new IOException("Read after end of file");
if (this.position == this.size)
return doEndOfFile();
this.position += (long)length;
int returnLength = length;
if (this.position > this.size) {
returnLength = length - (int)(this.position - this.size);
this.position = this.size;
}
processBytes(bytes, offset, returnLength);
return returnLength;
}
public synchronized void reset() throws IOException {
if (!this.markSupported)
throw new UnsupportedOperationException("Mark not supported");
if (this.mark < 0L)
throw new IOException("No position has been marked");
if (this.position > this.mark + this.readlimit)
throw new IOException("Marked position [" + this.mark + "] is no longer valid - passed the read limit [" + this.readlimit + "]");
this.position = this.mark;
this.eof = false;
}
public long skip(long numberOfBytes) throws IOException {
if (this.eof)
throw new IOException("Skip after end of file");
if (this.position == this.size)
return (long)doEndOfFile();
this.position += numberOfBytes;
long returnLength = numberOfBytes;
if (this.position > this.size) {
returnLength = numberOfBytes - (this.position - this.size);
this.position = this.size;
}
return returnLength;
}
protected int processByte() {
return 0;
}
protected void processBytes(byte[] bytes, int offset, int length) {}
private int doEndOfFile() throws EOFException {
this.eof = true;
if (this.throwEofException)
throw new EOFException();
return -1;
}
}

View file

@ -0,0 +1,122 @@
package org.apache.commons.io.input;
import java.io.EOFException;
import java.io.IOException;
import java.io.Reader;
public class NullReader extends Reader {
private final long size;
private long position;
private long mark = -1L;
private long readlimit;
private boolean eof;
private final boolean throwEofException;
private final boolean markSupported;
public NullReader(long size) {
this(size, true, false);
}
public NullReader(long size, boolean markSupported, boolean throwEofException) {
this.size = size;
this.markSupported = markSupported;
this.throwEofException = throwEofException;
}
public long getPosition() {
return this.position;
}
public long getSize() {
return this.size;
}
public void close() throws IOException {
this.eof = false;
this.position = 0L;
this.mark = -1L;
}
public synchronized void mark(int readlimit) {
if (!this.markSupported)
throw new UnsupportedOperationException("Mark not supported");
this.mark = this.position;
this.readlimit = (long)readlimit;
}
public boolean markSupported() {
return this.markSupported;
}
public int read() throws IOException {
if (this.eof)
throw new IOException("Read after end of file");
if (this.position == this.size)
return doEndOfFile();
this.position++;
return processChar();
}
public int read(char[] chars) throws IOException {
return read(chars, 0, chars.length);
}
public int read(char[] chars, int offset, int length) throws IOException {
if (this.eof)
throw new IOException("Read after end of file");
if (this.position == this.size)
return doEndOfFile();
this.position += (long)length;
int returnLength = length;
if (this.position > this.size) {
returnLength = length - (int)(this.position - this.size);
this.position = this.size;
}
processChars(chars, offset, returnLength);
return returnLength;
}
public synchronized void reset() throws IOException {
if (!this.markSupported)
throw new UnsupportedOperationException("Mark not supported");
if (this.mark < 0L)
throw new IOException("No position has been marked");
if (this.position > this.mark + this.readlimit)
throw new IOException("Marked position [" + this.mark + "] is no longer valid - passed the read limit [" + this.readlimit + "]");
this.position = this.mark;
this.eof = false;
}
public long skip(long numberOfChars) throws IOException {
if (this.eof)
throw new IOException("Skip after end of file");
if (this.position == this.size)
return (long)doEndOfFile();
this.position += numberOfChars;
long returnLength = numberOfChars;
if (this.position > this.size) {
returnLength = numberOfChars - (this.position - this.size);
this.position = this.size;
}
return returnLength;
}
protected int processChar() {
return 0;
}
protected void processChars(char[] chars, int offset, int length) {}
private int doEndOfFile() throws EOFException {
this.eof = true;
if (this.throwEofException)
throw new EOFException();
return -1;
}
}

View file

@ -0,0 +1,97 @@
package org.apache.commons.io.input;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
public abstract class ProxyInputStream extends FilterInputStream {
public ProxyInputStream(InputStream proxy) {
super(proxy);
}
public int read() throws IOException {
try {
beforeRead(1);
int b = this.in.read();
afterRead((b != -1) ? 1 : -1);
return b;
} catch (IOException e) {
handleIOException(e);
return -1;
}
}
public int read(byte[] bts) throws IOException {
try {
beforeRead((bts != null) ? bts.length : 0);
int n = this.in.read(bts);
afterRead(n);
return n;
} catch (IOException e) {
handleIOException(e);
return -1;
}
}
public int read(byte[] bts, int off, int len) throws IOException {
try {
beforeRead(len);
int n = this.in.read(bts, off, len);
afterRead(n);
return n;
} catch (IOException e) {
handleIOException(e);
return -1;
}
}
public long skip(long ln) throws IOException {
try {
return this.in.skip(ln);
} catch (IOException e) {
handleIOException(e);
return 0L;
}
}
public int available() throws IOException {
try {
return super.available();
} catch (IOException e) {
handleIOException(e);
return 0;
}
}
public void close() throws IOException {
try {
this.in.close();
} catch (IOException e) {
handleIOException(e);
}
}
public synchronized void mark(int readlimit) {
this.in.mark(readlimit);
}
public synchronized void reset() throws IOException {
try {
this.in.reset();
} catch (IOException e) {
handleIOException(e);
}
}
public boolean markSupported() {
return this.in.markSupported();
}
protected void beforeRead(int n) throws IOException {}
protected void afterRead(int n) throws IOException {}
protected void handleIOException(IOException e) throws IOException {
throw e;
}
}

View file

@ -0,0 +1,114 @@
package org.apache.commons.io.input;
import java.io.FilterReader;
import java.io.IOException;
import java.io.Reader;
import java.nio.CharBuffer;
public abstract class ProxyReader extends FilterReader {
public ProxyReader(Reader proxy) {
super(proxy);
}
public int read() throws IOException {
try {
beforeRead(1);
int c = this.in.read();
afterRead((c != -1) ? 1 : -1);
return c;
} catch (IOException e) {
handleIOException(e);
return -1;
}
}
public int read(char[] chr) throws IOException {
try {
beforeRead((chr != null) ? chr.length : 0);
int n = this.in.read(chr);
afterRead(n);
return n;
} catch (IOException e) {
handleIOException(e);
return -1;
}
}
public int read(char[] chr, int st, int len) throws IOException {
try {
beforeRead(len);
int n = this.in.read(chr, st, len);
afterRead(n);
return n;
} catch (IOException e) {
handleIOException(e);
return -1;
}
}
public int read(CharBuffer target) throws IOException {
try {
beforeRead((target != null) ? target.length() : 0);
int n = this.in.read(target);
afterRead(n);
return n;
} catch (IOException e) {
handleIOException(e);
return -1;
}
}
public long skip(long ln) throws IOException {
try {
return this.in.skip(ln);
} catch (IOException e) {
handleIOException(e);
return 0L;
}
}
public boolean ready() throws IOException {
try {
return this.in.ready();
} catch (IOException e) {
handleIOException(e);
return false;
}
}
public void close() throws IOException {
try {
this.in.close();
} catch (IOException e) {
handleIOException(e);
}
}
public synchronized void mark(int idx) throws IOException {
try {
this.in.mark(idx);
} catch (IOException e) {
handleIOException(e);
}
}
public synchronized void reset() throws IOException {
try {
this.in.reset();
} catch (IOException e) {
handleIOException(e);
}
}
public boolean markSupported() {
return this.in.markSupported();
}
protected void beforeRead(int n) throws IOException {}
protected void afterRead(int n) throws IOException {}
protected void handleIOException(IOException e) throws IOException {
throw e;
}
}

View file

@ -0,0 +1,119 @@
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;
public class ReaderInputStream extends InputStream {
private static final int DEFAULT_BUFFER_SIZE = 1024;
private final Reader reader;
private final CharsetEncoder encoder;
private final CharBuffer encoderIn;
private final ByteBuffer encoderOut;
private CoderResult lastCoderResult;
private boolean endOfInput;
public ReaderInputStream(Reader reader, CharsetEncoder encoder) {
this(reader, encoder, 1024);
}
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();
}
public ReaderInputStream(Reader reader, Charset charset, int bufferSize) {
this(reader, charset.newEncoder().onMalformedInput(CodingErrorAction.REPLACE).onUnmappableCharacter(CodingErrorAction.REPLACE), bufferSize);
}
public ReaderInputStream(Reader reader, Charset charset) {
this(reader, charset, 1024);
}
public ReaderInputStream(Reader reader, String charsetName, int bufferSize) {
this(reader, Charset.forName(charsetName), bufferSize);
}
public ReaderInputStream(Reader reader, String charsetName) {
this(reader, charsetName, 1024);
}
public ReaderInputStream(Reader reader) {
this(reader, Charset.defaultCharset());
}
private void fillBuffer() throws IOException {
if (!this.endOfInput && (this.lastCoderResult == null || this.lastCoderResult.isUnderflow())) {
this.encoderIn.compact();
int position = this.encoderIn.position();
int c = this.reader.read(this.encoderIn.array(), position, this.encoderIn.remaining());
if (c == -1) {
this.endOfInput = true;
} else {
this.encoderIn.position(position + c);
}
this.encoderIn.flip();
}
this.encoderOut.compact();
this.lastCoderResult = this.encoder.encode(this.encoderIn, this.encoderOut, this.endOfInput);
this.encoderOut.flip();
}
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;
while (len > 0) {
if (this.encoderOut.hasRemaining()) {
int c = Math.min(this.encoderOut.remaining(), len);
this.encoderOut.get(b, off, c);
off += c;
len -= c;
read += c;
continue;
}
fillBuffer();
if (this.endOfInput && !this.encoderOut.hasRemaining())
break;
}
return (read == 0 && this.endOfInput) ? -1 : read;
}
public int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
public int read() throws IOException {
while (true) {
if (this.encoderOut.hasRemaining())
return this.encoderOut.get() & 0xFF;
fillBuffer();
if (this.endOfInput && !this.encoderOut.hasRemaining())
return -1;
}
}
public void close() throws IOException {
this.reader.close();
}
}

View file

@ -0,0 +1,190 @@
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 org.apache.commons.io.Charsets;
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;
public ReversedLinesFileReader(File file) throws IOException {
this(file, 4096, Charset.defaultCharset().toString());
}
public ReversedLinesFileReader(File file, int blockSize, Charset encoding) throws IOException {
this.blockSize = blockSize;
this.encoding = encoding;
this.randomAccessFile = new RandomAccessFile(file, "r");
this.totalByteLength = this.randomAccessFile.length();
int lastBlockLength = (int)(this.totalByteLength % (long)blockSize);
if (lastBlockLength > 0) {
this.totalBlockCount = this.totalByteLength / (long)blockSize + 1L;
} else {
this.totalBlockCount = this.totalByteLength / (long)blockSize;
if (this.totalByteLength > 0L)
lastBlockLength = blockSize;
}
this.currentFilePart = new FilePart(this.totalBlockCount, lastBlockLength, null);
Charset charset = Charsets.toCharset(encoding);
CharsetEncoder charsetEncoder = charset.newEncoder();
float maxBytesPerChar = charsetEncoder.maxBytesPerChar();
if (maxBytesPerChar == 1.0F) {
this.byteDecrement = 1;
} else if (charset == Charset.forName("UTF-8")) {
this.byteDecrement = 1;
} else if (charset == Charset.forName("Shift_JIS")) {
this.byteDecrement = 1;
} else if (charset == Charset.forName("UTF-16BE") || charset == Charset.forName("UTF-16LE")) {
this.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)");
throw new UnsupportedEncodingException("Encoding " + encoding + " is not supported yet (feel free to submit a patch)");
}
this.newLineSequences = new byte[][] { "\r\n".getBytes(encoding), "\n".getBytes(encoding), "\r".getBytes(encoding) };
this.avoidNewlineSplitBufferSize = (this.newLineSequences[0]).length;
}
public ReversedLinesFileReader(File file, int blockSize, String encoding) throws IOException {
this(file, blockSize, Charsets.toCharset(encoding));
}
public String readLine() throws IOException {
String line = this.currentFilePart.readLine();
while (line == null) {
this.currentFilePart = this.currentFilePart.rollOver();
if (this.currentFilePart != null) {
line = this.currentFilePart.readLine();
continue;
}
break;
}
if ("".equals(line) && !this.trailingNewlineOfFileSkipped) {
this.trailingNewlineOfFileSkipped = true;
line = readLine();
}
return line;
}
public void close() throws IOException {
this.randomAccessFile.close();
}
private class FilePart {
private final long no;
private final byte[] data;
private byte[] leftOver;
private int currentLastBytePos;
private FilePart(long no, int length, byte[] leftOverOfLastFilePart) throws IOException {
this.no = no;
int dataLength = length + ((leftOverOfLastFilePart != null) ? leftOverOfLastFilePart.length : 0);
this.data = new byte[dataLength];
long off = (no - 1L) * (long)ReversedLinesFileReader.this.blockSize;
if (no > 0L) {
ReversedLinesFileReader.this.randomAccessFile.seek(off);
int countRead = ReversedLinesFileReader.this.randomAccessFile.read(this.data, 0, length);
if (countRead != length)
throw new IllegalStateException("Count of requested bytes and actually read bytes don't match");
}
if (leftOverOfLastFilePart != null)
System.arraycopy(leftOverOfLastFilePart, 0, this.data, length, leftOverOfLastFilePart.length);
this.currentLastBytePos = this.data.length - 1;
this.leftOver = null;
}
private FilePart rollOver() throws IOException {
if (this.currentLastBytePos > -1)
throw new IllegalStateException("Current currentLastCharPos unexpectedly positive... last readLine() should have returned something! currentLastCharPos=" + this.currentLastBytePos);
if (this.no > 1L)
return new FilePart(this.no - 1L, ReversedLinesFileReader.this.blockSize, this.leftOver);
if (this.leftOver != null)
throw new IllegalStateException("Unexpected leftover of the last block: leftOverOfThisFilePart=" + new String(this.leftOver, ReversedLinesFileReader.this.encoding));
return null;
}
private String readLine() throws IOException {
String line = null;
boolean isLastFilePart = (this.no == 1L);
int i = this.currentLastBytePos;
while (i > -1) {
if (!isLastFilePart && i < ReversedLinesFileReader.this.avoidNewlineSplitBufferSize) {
createLeftOver();
break;
}
int newLineMatchByteCount;
if ((newLineMatchByteCount = getNewLineMatchByteCount(this.data, i)) > 0) {
int lineStart = i + 1;
int lineLengthBytes = this.currentLastBytePos - lineStart + 1;
if (lineLengthBytes < 0)
throw new IllegalStateException("Unexpected negative line length=" + lineLengthBytes);
byte[] lineData = new byte[lineLengthBytes];
System.arraycopy(this.data, lineStart, lineData, 0, lineLengthBytes);
line = new String(lineData, ReversedLinesFileReader.this.encoding);
this.currentLastBytePos = i - newLineMatchByteCount;
break;
}
i -= ReversedLinesFileReader.this.byteDecrement;
if (i < 0) {
createLeftOver();
break;
}
}
if (isLastFilePart && this.leftOver != null) {
line = new String(this.leftOver, ReversedLinesFileReader.this.encoding);
this.leftOver = null;
}
return line;
}
private void createLeftOver() {
int lineLengthBytes = this.currentLastBytePos + 1;
if (lineLengthBytes > 0) {
this.leftOver = new byte[lineLengthBytes];
System.arraycopy(this.data, 0, this.leftOver, 0, lineLengthBytes);
} else {
this.leftOver = null;
}
this.currentLastBytePos = -1;
}
private int getNewLineMatchByteCount(byte[] data, int i) {
for (byte[] newLineSequence : ReversedLinesFileReader.this.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]) ? true : false;
}
if (match)
return newLineSequence.length;
}
return 0;
}
}
}

View file

@ -0,0 +1,80 @@
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;
public class SwappedDataInputStream extends ProxyInputStream implements DataInput {
public SwappedDataInputStream(InputStream input) {
super(input);
}
public boolean readBoolean() throws IOException, EOFException {
return (0 != readByte());
}
public byte readByte() throws IOException, EOFException {
return (byte)this.in.read();
}
public char readChar() throws IOException, EOFException {
return (char)readShort();
}
public double readDouble() throws IOException, EOFException {
return EndianUtils.readSwappedDouble(this.in);
}
public float readFloat() throws IOException, EOFException {
return EndianUtils.readSwappedFloat(this.in);
}
public void readFully(byte[] data) throws IOException, EOFException {
readFully(data, 0, data.length);
}
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;
}
}
public int readInt() throws IOException, EOFException {
return EndianUtils.readSwappedInteger(this.in);
}
public String readLine() throws IOException, EOFException {
throw new UnsupportedOperationException("Operation not supported: readLine()");
}
public long readLong() throws IOException, EOFException {
return EndianUtils.readSwappedLong(this.in);
}
public short readShort() throws IOException, EOFException {
return EndianUtils.readSwappedShort(this.in);
}
public int readUnsignedByte() throws IOException, EOFException {
return this.in.read();
}
public int readUnsignedShort() throws IOException, EOFException {
return EndianUtils.readSwappedUnsignedShort(this.in);
}
public String readUTF() throws IOException, EOFException {
throw new UnsupportedOperationException("Operation not supported: readUTF()");
}
public int skipBytes(int count) throws IOException, EOFException {
return (int)this.in.skip((long)count);
}
}

View file

@ -0,0 +1,27 @@
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;
public class TaggedInputStream extends ProxyInputStream {
private final Serializable tag = UUID.randomUUID();
public TaggedInputStream(InputStream proxy) {
super(proxy);
}
public boolean isCauseOf(Throwable exception) {
return TaggedIOException.isTaggedWith(exception, this.tag);
}
public void throwIfCauseOf(Throwable throwable) throws IOException {
TaggedIOException.throwCauseIfTaggedWith(throwable, this.tag);
}
protected void handleIOException(IOException e) throws IOException {
throw new TaggedIOException(e, this.tag);
}
}

View file

@ -0,0 +1,204 @@
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;
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;
private final byte[] inbuf;
private final File file;
private final long delayMillis;
private final boolean end;
private final TailerListener listener;
private final boolean reOpen;
private volatile boolean run = true;
public Tailer(File file, TailerListener listener) {
this(file, listener, 1000L);
}
public Tailer(File file, TailerListener listener, long delayMillis) {
this(file, listener, delayMillis, false);
}
public Tailer(File file, TailerListener listener, long delayMillis, boolean end) {
this(file, listener, delayMillis, end, 4096);
}
public Tailer(File file, TailerListener listener, long delayMillis, boolean end, boolean reOpen) {
this(file, listener, delayMillis, end, reOpen, 4096);
}
public Tailer(File file, TailerListener listener, long delayMillis, boolean end, int bufSize) {
this(file, listener, delayMillis, end, false, bufSize);
}
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];
this.listener = listener;
listener.init(this);
this.reOpen = reOpen;
}
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;
}
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;
}
public static Tailer create(File file, TailerListener listener, long delayMillis, boolean end) {
return create(file, listener, delayMillis, end, 4096);
}
public static Tailer create(File file, TailerListener listener, long delayMillis, boolean end, boolean reOpen) {
return create(file, listener, delayMillis, end, reOpen, 4096);
}
public static Tailer create(File file, TailerListener listener, long delayMillis) {
return create(file, listener, delayMillis, false);
}
public static Tailer create(File file, TailerListener listener) {
return create(file, listener, 1000L, false);
}
public File getFile() {
return this.file;
}
public long getDelay() {
return this.delayMillis;
}
public void run() {
RandomAccessFile reader = null;
try {
long last = 0L;
long position = 0L;
while (this.run && reader == null) {
try {
reader = new RandomAccessFile(this.file, "r");
} catch (FileNotFoundException e) {
this.listener.fileNotFound();
}
if (reader == null) {
try {
Thread.sleep(this.delayMillis);
} catch (InterruptedException e) {}
continue;
}
position = this.end ? this.file.length() : 0L;
last = System.currentTimeMillis();
reader.seek(position);
}
while (this.run) {
boolean newer = FileUtils.isFileNewer(this.file, last);
long length = this.file.length();
if (length < position) {
this.listener.fileRotated();
try {
RandomAccessFile save = reader;
reader = new RandomAccessFile(this.file, "r");
position = 0L;
IOUtils.closeQuietly(save);
} catch (FileNotFoundException e) {
this.listener.fileNotFound();
}
continue;
}
if (length > position) {
position = readLines(reader);
last = System.currentTimeMillis();
} else if (newer) {
position = 0L;
reader.seek(position);
position = readLines(reader);
last = System.currentTimeMillis();
}
if (this.reOpen)
IOUtils.closeQuietly(reader);
try {
Thread.sleep(this.delayMillis);
} catch (InterruptedException e) {}
if (this.run && this.reOpen) {
reader = new RandomAccessFile(this.file, "r");
reader.seek(position);
}
}
} catch (Exception e) {
this.listener.handle(e);
} finally {
IOUtils.closeQuietly(reader);
}
}
public void stop() {
this.run = false;
}
private long readLines(RandomAccessFile reader) throws IOException {
StringBuilder sb = new StringBuilder();
long pos = reader.getFilePointer();
long rePos = pos;
boolean seenCR = false;
int num;
while (this.run && (num = reader.read(this.inbuf)) != -1) {
for (int i = 0; i < num; i++) {
byte ch = this.inbuf[i];
switch (ch) {
case 10:
seenCR = false;
this.listener.handle(sb.toString());
sb.setLength(0);
rePos = pos + (long)i + 1L;
break;
case 13:
if (seenCR)
sb.append('\r');
seenCR = true;
break;
default:
if (seenCR) {
seenCR = false;
this.listener.handle(sb.toString());
sb.setLength(0);
rePos = pos + (long)i + 1L;
}
sb.append((char)ch);
break;
}
}
pos = reader.getFilePointer();
}
reader.seek(rePos);
return rePos;
}
}

View file

@ -0,0 +1,13 @@
package org.apache.commons.io.input;
public interface TailerListener {
void init(Tailer paramTailer);
void fileNotFound();
void fileRotated();
void handle(String paramString);
void handle(Exception paramException);
}

View file

@ -0,0 +1,13 @@
package org.apache.commons.io.input;
public class TailerListenerAdapter implements TailerListener {
public void init(Tailer tailer) {}
public void fileNotFound() {}
public void fileRotated() {}
public void handle(String line) {}
public void handle(Exception ex) {}
}

View file

@ -0,0 +1,51 @@
package org.apache.commons.io.input;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class TeeInputStream extends ProxyInputStream {
private final OutputStream branch;
private final boolean closeBranch;
public TeeInputStream(InputStream input, OutputStream branch) {
this(input, branch, false);
}
public TeeInputStream(InputStream input, OutputStream branch, boolean closeBranch) {
super(input);
this.branch = branch;
this.closeBranch = closeBranch;
}
public void close() throws IOException {
try {
super.close();
} finally {
if (this.closeBranch)
this.branch.close();
}
}
public int read() throws IOException {
int ch = super.read();
if (ch != -1)
this.branch.write(ch);
return ch;
}
public int read(byte[] bts, int st, int end) throws IOException {
int n = super.read(bts, st, end);
if (n != -1)
this.branch.write(bts, st, n);
return n;
}
public int read(byte[] bts) throws IOException {
int n = super.read(bts);
if (n != -1)
this.branch.write(bts, 0, n);
return n;
}
}

View file

@ -0,0 +1,351 @@
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.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;
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 };
private static final ByteOrderMark[] XML_GUESS_BYTES = new ByteOrderMark[] { new ByteOrderMark("UTF-8", new int[] { 60, 63, 120, 109 }), new ByteOrderMark("UTF-16BE", new int[] { 0, 60, 0, 63 }), new ByteOrderMark("UTF-16LE", new int[] { 60, 0, 63, 0 }), new ByteOrderMark("UTF-32BE", new int[] {
0, 0, 0, 60, 0, 0, 0, 63, 0, 0,
0, 120, 0, 0, 0, 109 }), new ByteOrderMark("UTF-32LE", new int[] {
60, 0, 0, 0, 63, 0, 0, 0, 120, 0,
0, 0, 109, 0, 0, 0 }), new ByteOrderMark("CP1047", new int[] { 76, 111, 167, 148 }) };
private final Reader reader;
private final String encoding;
private final String defaultEncoding;
public String getDefaultEncoding() {
return this.defaultEncoding;
}
public XmlStreamReader(File file) throws IOException {
this(new FileInputStream(file));
}
public XmlStreamReader(InputStream is) throws IOException {
this(is, true);
}
public XmlStreamReader(InputStream is, boolean lenient) throws IOException {
this(is, lenient, null);
}
public XmlStreamReader(InputStream is, boolean lenient, String defaultEncoding) throws IOException {
this.defaultEncoding = defaultEncoding;
BOMInputStream bom = new BOMInputStream(new BufferedInputStream(is, 4096), false, BOMS);
BOMInputStream pis = new BOMInputStream(bom, true, XML_GUESS_BYTES);
this.encoding = doRawStream(bom, pis, lenient);
this.reader = new InputStreamReader(pis, this.encoding);
}
public XmlStreamReader(URL url) throws IOException {
this(url.openConnection(), null);
}
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, 4096), false, BOMS);
BOMInputStream pis = new BOMInputStream(bom, true, XML_GUESS_BYTES);
if (conn instanceof java.net.HttpURLConnection || contentType != null) {
this.encoding = doHttpStream(bom, pis, contentType, lenient);
} else {
this.encoding = doRawStream(bom, pis, lenient);
}
this.reader = new InputStreamReader(pis, this.encoding);
}
public XmlStreamReader(InputStream is, String httpContentType) throws IOException {
this(is, httpContentType, true);
}
public XmlStreamReader(InputStream is, String httpContentType, boolean lenient, String defaultEncoding) throws IOException {
this.defaultEncoding = defaultEncoding;
BOMInputStream bom = new BOMInputStream(new BufferedInputStream(is, 4096), false, BOMS);
BOMInputStream pis = new BOMInputStream(bom, true, XML_GUESS_BYTES);
this.encoding = doHttpStream(bom, pis, httpContentType, lenient);
this.reader = new InputStreamReader(pis, this.encoding);
}
public XmlStreamReader(InputStream is, String httpContentType, boolean lenient) throws IOException {
this(is, httpContentType, lenient, null);
}
public String getEncoding() {
return this.encoding;
}
public int read(char[] buf, int offset, int len) throws IOException {
return this.reader.read(buf, offset, len);
}
public void close() throws IOException {
this.reader.close();
}
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);
throw ex;
}
}
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);
throw ex;
}
}
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 = (this.defaultEncoding == null) ? "UTF-8" : this.defaultEncoding;
return encoding;
}
String calculateRawEncoding(String bomEnc, String xmlGuessEnc, String xmlEnc) throws IOException {
if (bomEnc == null) {
if (xmlGuessEnc == null || xmlEnc == null)
return (this.defaultEncoding == null) ? "UTF-8" : this.defaultEncoding;
if (xmlEnc.equals("UTF-16") && (xmlGuessEnc.equals("UTF-16BE") || xmlGuessEnc.equals("UTF-16LE")))
return xmlGuessEnc;
return xmlEnc;
}
if (bomEnc.equals("UTF-8")) {
if (xmlGuessEnc != null && !xmlGuessEnc.equals("UTF-8")) {
String str = MessageFormat.format("Invalid encoding, BOM [{0}] XML guess [{1}] XML prolog [{2}] encoding mismatch", bomEnc, xmlGuessEnc, xmlEnc);
throw new XmlStreamReaderException(str, bomEnc, xmlGuessEnc, xmlEnc);
}
if (xmlEnc != null && !xmlEnc.equals("UTF-8")) {
String str = MessageFormat.format("Invalid encoding, BOM [{0}] XML guess [{1}] XML prolog [{2}] encoding mismatch", bomEnc, xmlGuessEnc, xmlEnc);
throw new XmlStreamReaderException(str, bomEnc, xmlGuessEnc, xmlEnc);
}
return bomEnc;
}
if (bomEnc.equals("UTF-16BE") || bomEnc.equals("UTF-16LE")) {
if (xmlGuessEnc != null && !xmlGuessEnc.equals(bomEnc)) {
String str = MessageFormat.format("Invalid encoding, BOM [{0}] XML guess [{1}] XML prolog [{2}] encoding mismatch", bomEnc, xmlGuessEnc, xmlEnc);
throw new XmlStreamReaderException(str, bomEnc, xmlGuessEnc, xmlEnc);
}
if (xmlEnc != null && !xmlEnc.equals("UTF-16") && !xmlEnc.equals(bomEnc)) {
String str = MessageFormat.format("Invalid encoding, BOM [{0}] XML guess [{1}] XML prolog [{2}] encoding mismatch", bomEnc, xmlGuessEnc, xmlEnc);
throw new XmlStreamReaderException(str, bomEnc, xmlGuessEnc, xmlEnc);
}
return bomEnc;
}
if (bomEnc.equals("UTF-32BE") || bomEnc.equals("UTF-32LE")) {
if (xmlGuessEnc != null && !xmlGuessEnc.equals(bomEnc)) {
String str = MessageFormat.format("Invalid encoding, BOM [{0}] XML guess [{1}] XML prolog [{2}] encoding mismatch", bomEnc, xmlGuessEnc, xmlEnc);
throw new XmlStreamReaderException(str, bomEnc, xmlGuessEnc, xmlEnc);
}
if (xmlEnc != null && !xmlEnc.equals("UTF-32") && !xmlEnc.equals(bomEnc)) {
String str = MessageFormat.format("Invalid encoding, BOM [{0}] XML guess [{1}] XML prolog [{2}] encoding mismatch", bomEnc, xmlGuessEnc, xmlEnc);
throw new XmlStreamReaderException(str, bomEnc, xmlGuessEnc, xmlEnc);
}
return bomEnc;
}
String msg = MessageFormat.format("Invalid encoding, BOM [{0}] XML guess [{1}] XML prolog [{2}] unknown BOM", bomEnc, xmlGuessEnc, xmlEnc);
throw new XmlStreamReaderException(msg, bomEnc, xmlGuessEnc, xmlEnc);
}
String calculateHttpEncoding(String httpContentType, String bomEnc, String xmlGuessEnc, String xmlEnc, boolean lenient) throws IOException {
if (lenient && xmlEnc != null)
return xmlEnc;
String cTMime = getContentTypeMime(httpContentType);
String cTEnc = getContentTypeEncoding(httpContentType);
boolean appXml = isAppXml(cTMime);
boolean textXml = isTextXml(cTMime);
if (!appXml && !textXml) {
String msg = MessageFormat.format("Invalid encoding, CT-MIME [{0}] CT-Enc [{1}] BOM [{2}] XML guess [{3}] XML prolog [{4}], Invalid MIME", cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc);
throw new XmlStreamReaderException(msg, cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc);
}
if (cTEnc == null) {
if (appXml)
return calculateRawEncoding(bomEnc, xmlGuessEnc, xmlEnc);
return (this.defaultEncoding == null) ? "US-ASCII" : this.defaultEncoding;
}
if (cTEnc.equals("UTF-16BE") || cTEnc.equals("UTF-16LE")) {
if (bomEnc != null) {
String msg = MessageFormat.format("Invalid encoding, CT-MIME [{0}] CT-Enc [{1}] BOM [{2}] XML guess [{3}] XML prolog [{4}], BOM must be NULL", cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc);
throw new XmlStreamReaderException(msg, cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc);
}
return cTEnc;
}
if (cTEnc.equals("UTF-16")) {
if (bomEnc != null && bomEnc.startsWith("UTF-16"))
return bomEnc;
String msg = MessageFormat.format("Invalid encoding, CT-MIME [{0}] CT-Enc [{1}] BOM [{2}] XML guess [{3}] XML prolog [{4}], encoding mismatch", cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc);
throw new XmlStreamReaderException(msg, cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc);
}
if (cTEnc.equals("UTF-32BE") || cTEnc.equals("UTF-32LE")) {
if (bomEnc != null) {
String msg = MessageFormat.format("Invalid encoding, CT-MIME [{0}] CT-Enc [{1}] BOM [{2}] XML guess [{3}] XML prolog [{4}], BOM must be NULL", cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc);
throw new XmlStreamReaderException(msg, cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc);
}
return cTEnc;
}
if (cTEnc.equals("UTF-32")) {
if (bomEnc != null && bomEnc.startsWith("UTF-32"))
return bomEnc;
String msg = MessageFormat.format("Invalid encoding, CT-MIME [{0}] CT-Enc [{1}] BOM [{2}] XML guess [{3}] XML prolog [{4}], encoding mismatch", cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc);
throw new XmlStreamReaderException(msg, cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc);
}
return cTEnc;
}
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=[\"']?([.[^; \"']]*)[\"']?");
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]*((?:\".[^\"]*\")|(?:'.[^']*'))", 8);
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";
private static String getXmlProlog(InputStream is, String guessedEnc) throws IOException {
String encoding = null;
if (guessedEnc != null) {
byte[] bytes = new byte[4096];
is.mark(4096);
int offset = 0;
int max = 4096;
int c = is.read(bytes, offset, max);
int firstGT = -1;
String xmlProlog = null;
while (c != -1 && firstGT == -1 && offset < 4096) {
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");
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;
}
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"))));
}
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"))));
}
}

View file

@ -0,0 +1,50 @@
package org.apache.commons.io.input;
import java.io.IOException;
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;
public XmlStreamReaderException(String msg, String bomEnc, String xmlGuessEnc, String xmlEnc) {
this(msg, null, null, bomEnc, xmlGuessEnc, xmlEnc);
}
public XmlStreamReaderException(String msg, String ctMime, String ctEnc, String bomEnc, String xmlGuessEnc, String xmlEnc) {
super(msg);
this.contentTypeMime = ctMime;
this.contentTypeEncoding = ctEnc;
this.bomEncoding = bomEnc;
this.xmlGuessEncoding = xmlGuessEnc;
this.xmlEncoding = xmlEnc;
}
public String getBomEncoding() {
return this.bomEncoding;
}
public String getXmlGuessEncoding() {
return this.xmlGuessEncoding;
}
public String getXmlEncoding() {
return this.xmlEncoding;
}
public String getContentTypeMime() {
return this.contentTypeMime;
}
public String getContentTypeEncoding() {
return this.contentTypeEncoding;
}
}

View file

@ -0,0 +1,21 @@
package org.apache.commons.io.monitor;
import java.io.File;
public interface FileAlterationListener {
void onStart(FileAlterationObserver paramFileAlterationObserver);
void onDirectoryCreate(File paramFile);
void onDirectoryChange(File paramFile);
void onDirectoryDelete(File paramFile);
void onFileCreate(File paramFile);
void onFileChange(File paramFile);
void onFileDelete(File paramFile);
void onStop(FileAlterationObserver paramFileAlterationObserver);
}

View file

@ -0,0 +1,21 @@
package org.apache.commons.io.monitor;
import java.io.File;
public class FileAlterationListenerAdaptor implements FileAlterationListener {
public void onStart(FileAlterationObserver observer) {}
public void onDirectoryCreate(File directory) {}
public void onDirectoryChange(File directory) {}
public void onDirectoryDelete(File directory) {}
public void onFileCreate(File file) {}
public void onFileChange(File file) {}
public void onFileDelete(File file) {}
public void onStop(FileAlterationObserver observer) {}
}

View file

@ -0,0 +1,97 @@
package org.apache.commons.io.monitor;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ThreadFactory;
public final class FileAlterationMonitor implements Runnable {
private final long interval;
private final List<FileAlterationObserver> observers = new CopyOnWriteArrayList<FileAlterationObserver>();
private Thread thread = null;
private ThreadFactory threadFactory;
private volatile boolean running = false;
public FileAlterationMonitor() {
this(10000L);
}
public FileAlterationMonitor(long interval) {
this.interval = interval;
}
public FileAlterationMonitor(long interval, FileAlterationObserver... observers) {
this(interval);
if (observers != null)
for (FileAlterationObserver observer : observers)
addObserver(observer);
}
public long getInterval() {
return this.interval;
}
public synchronized void setThreadFactory(ThreadFactory threadFactory) {
this.threadFactory = threadFactory;
}
public void addObserver(FileAlterationObserver observer) {
if (observer != null)
this.observers.add(observer);
}
public void removeObserver(FileAlterationObserver observer) {
if (observer != null)
while (this.observers.remove(observer));
}
public Iterable<FileAlterationObserver> getObservers() {
return this.observers;
}
public synchronized void start() throws Exception {
if (this.running)
throw new IllegalStateException("Monitor is already running");
for (FileAlterationObserver observer : this.observers)
observer.initialize();
this.running = true;
if (this.threadFactory != null) {
this.thread = this.threadFactory.newThread(this);
} else {
this.thread = new Thread(this);
}
this.thread.start();
}
public synchronized void stop() throws Exception {
stop(this.interval);
}
public synchronized void stop(long stopInterval) throws Exception {
if (!this.running)
throw new IllegalStateException("Monitor is not running");
this.running = false;
try {
this.thread.join(stopInterval);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
for (FileAlterationObserver observer : this.observers)
observer.destroy();
}
public void run() {
while (this.running) {
for (FileAlterationObserver observer : this.observers)
observer.checkAndNotify();
if (!this.running)
break;
try {
Thread.sleep(this.interval);
} catch (InterruptedException ignored) {}
}
}
}

View file

@ -0,0 +1,206 @@
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;
public class FileAlterationObserver implements Serializable {
private final List<FileAlterationListener> listeners = new CopyOnWriteArrayList<FileAlterationListener>();
private final FileEntry rootEntry;
private final FileFilter fileFilter;
private final Comparator<File> comparator;
public FileAlterationObserver(String directoryName) {
this(new File(directoryName));
}
public FileAlterationObserver(String directoryName, FileFilter fileFilter) {
this(new File(directoryName), fileFilter);
}
public FileAlterationObserver(String directoryName, FileFilter fileFilter, IOCase caseSensitivity) {
this(new File(directoryName), fileFilter, caseSensitivity);
}
public FileAlterationObserver(File directory) {
this(directory, (FileFilter)null);
}
public FileAlterationObserver(File directory, FileFilter fileFilter) {
this(directory, fileFilter, (IOCase)null);
}
public FileAlterationObserver(File directory, FileFilter fileFilter, IOCase caseSensitivity) {
this(new FileEntry(directory), fileFilter, caseSensitivity);
}
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;
}
}
public File getDirectory() {
return this.rootEntry.getFile();
}
public FileFilter getFileFilter() {
return this.fileFilter;
}
public void addListener(FileAlterationListener listener) {
if (listener != null)
this.listeners.add(listener);
}
public void removeListener(FileAlterationListener listener) {
if (listener != null)
while (this.listeners.remove(listener));
}
public Iterable<FileAlterationListener> getListeners() {
return this.listeners;
}
public void initialize() throws Exception {
this.rootEntry.refresh(this.rootEntry.getFile());
File[] files = listFiles(this.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(this.rootEntry, files[i]);
this.rootEntry.setChildren(children);
}
public void destroy() throws Exception {}
public void checkAndNotify() {
for (FileAlterationListener listener : this.listeners)
listener.onStart(this);
File rootFile = this.rootEntry.getFile();
if (rootFile.exists()) {
checkAndNotify(this.rootEntry, this.rootEntry.getChildren(), listFiles(rootFile));
} else if (this.rootEntry.isExists()) {
checkAndNotify(this.rootEntry, this.rootEntry.getChildren(), FileUtils.EMPTY_FILE_ARRAY);
}
for (FileAlterationListener listener : this.listeners)
listener.onStop(this);
}
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 && this.comparator.compare(entry.getFile(), files[c]) > 0) {
current[c] = createFileEntry(parent, files[c]);
doCreate(current[c]);
c++;
}
if (c < files.length && this.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);
}
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;
}
private void doCreate(FileEntry entry) {
for (FileAlterationListener listener : this.listeners) {
if (entry.isDirectory()) {
listener.onDirectoryCreate(entry.getFile());
continue;
}
listener.onFileCreate(entry.getFile());
}
FileEntry[] children = entry.getChildren();
for (FileEntry aChildren : children)
doCreate(aChildren);
}
private void doMatch(FileEntry entry, File file) {
if (entry.refresh(file))
for (FileAlterationListener listener : this.listeners) {
if (entry.isDirectory()) {
listener.onDirectoryChange(file);
continue;
}
listener.onFileChange(file);
}
}
private void doDelete(FileEntry entry) {
for (FileAlterationListener listener : this.listeners) {
if (entry.isDirectory()) {
listener.onDirectoryDelete(entry.getFile());
continue;
}
listener.onFileDelete(entry.getFile());
}
}
private File[] listFiles(File file) {
File[] children = null;
if (file.isDirectory())
children = (this.fileFilter == null) ? file.listFiles() : file.listFiles(this.fileFilter);
if (children == null)
children = FileUtils.EMPTY_FILE_ARRAY;
if (this.comparator != null && children.length > 1)
Arrays.<File>sort(children, this.comparator);
return children;
}
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(getClass().getSimpleName());
builder.append("[file='");
builder.append(getDirectory().getPath());
builder.append('\'');
if (this.fileFilter != null) {
builder.append(", ");
builder.append(this.fileFilter.toString());
}
builder.append(", listeners=");
builder.append(this.listeners.size());
builder.append("]");
return builder.toString();
}
}

View file

@ -0,0 +1,113 @@
package org.apache.commons.io.monitor;
import java.io.File;
import java.io.Serializable;
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;
public FileEntry(File file) {
this(null, file);
}
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();
}
public boolean refresh(File file) {
boolean origExists = this.exists;
long origLastModified = this.lastModified;
boolean origDirectory = this.directory;
long origLength = this.length;
this.name = file.getName();
this.exists = file.exists();
this.directory = this.exists ? file.isDirectory() : false;
this.lastModified = this.exists ? file.lastModified() : 0L;
this.length = (this.exists && !this.directory) ? file.length() : 0L;
return (this.exists != origExists || this.lastModified != origLastModified || this.directory != origDirectory || this.length != origLength);
}
public FileEntry newChildInstance(File file) {
return new FileEntry(this, file);
}
public FileEntry getParent() {
return this.parent;
}
public int getLevel() {
return (this.parent == null) ? 0 : (this.parent.getLevel() + 1);
}
public FileEntry[] getChildren() {
return (this.children != null) ? this.children : EMPTY_ENTRIES;
}
public void setChildren(FileEntry[] children) {
this.children = children;
}
public File getFile() {
return this.file;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public long getLastModified() {
return this.lastModified;
}
public void setLastModified(long lastModified) {
this.lastModified = lastModified;
}
public long getLength() {
return this.length;
}
public void setLength(long length) {
this.length = length;
}
public boolean isExists() {
return this.exists;
}
public void setExists(boolean exists) {
this.exists = exists;
}
public boolean isDirectory() {
return this.directory;
}
public void setDirectory(boolean directory) {
this.directory = directory;
}
}

View file

@ -0,0 +1,28 @@
package org.apache.commons.io.output;
import java.io.IOException;
import java.io.OutputStream;
public class BrokenOutputStream extends OutputStream {
private final IOException exception;
public BrokenOutputStream(IOException exception) {
this.exception = exception;
}
public BrokenOutputStream() {
this(new IOException("Broken output stream"));
}
public void write(int b) throws IOException {
throw this.exception;
}
public void flush() throws IOException {
throw this.exception;
}
public void close() throws IOException {
throw this.exception;
}
}

View file

@ -0,0 +1,177 @@
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;
public class ByteArrayOutputStream extends OutputStream {
private static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
private final List<byte[]> buffers = new ArrayList<byte[]>();
private int currentBufferIndex;
private int filledBufferSum;
private byte[] currentBuffer;
private int count;
public ByteArrayOutputStream() {
this(1024);
}
public ByteArrayOutputStream(int size) {
if (size < 0)
throw new IllegalArgumentException("Negative initial size: " + size);
synchronized (this) {
needNewBuffer(size);
}
}
private void needNewBuffer(int newcount) {
if (this.currentBufferIndex < this.buffers.size() - 1) {
this.filledBufferSum += this.currentBuffer.length;
this.currentBufferIndex++;
this.currentBuffer = this.buffers.get(this.currentBufferIndex);
} else {
int newBufferSize;
if (this.currentBuffer == null) {
newBufferSize = newcount;
this.filledBufferSum = 0;
} else {
newBufferSize = Math.max(this.currentBuffer.length << 1, newcount - this.filledBufferSum);
this.filledBufferSum += this.currentBuffer.length;
}
this.currentBufferIndex++;
this.currentBuffer = new byte[newBufferSize];
this.buffers.add(this.currentBuffer);
}
}
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();
if (len == 0)
return;
synchronized (this) {
int newcount = this.count + len;
int remaining = len;
int inBufferPos = this.count - this.filledBufferSum;
while (remaining > 0) {
int part = Math.min(remaining, this.currentBuffer.length - inBufferPos);
System.arraycopy(b, off + len - remaining, this.currentBuffer, inBufferPos, part);
remaining -= part;
if (remaining > 0) {
needNewBuffer(newcount);
inBufferPos = 0;
}
}
this.count = newcount;
}
}
public synchronized void write(int b) {
int inBufferPos = this.count - this.filledBufferSum;
if (inBufferPos == this.currentBuffer.length) {
needNewBuffer(this.count + 1);
inBufferPos = 0;
}
this.currentBuffer[inBufferPos] = (byte)b;
this.count++;
}
public synchronized int write(InputStream in) throws IOException {
int readCount = 0;
int inBufferPos = this.count - this.filledBufferSum;
int n = in.read(this.currentBuffer, inBufferPos, this.currentBuffer.length - inBufferPos);
while (n != -1) {
readCount += n;
inBufferPos += n;
this.count += n;
if (inBufferPos == this.currentBuffer.length) {
needNewBuffer(this.currentBuffer.length);
inBufferPos = 0;
}
n = in.read(this.currentBuffer, inBufferPos, this.currentBuffer.length - inBufferPos);
}
return readCount;
}
public synchronized int size() {
return this.count;
}
public void close() throws IOException {}
public synchronized void reset() {
this.count = 0;
this.filledBufferSum = 0;
this.currentBufferIndex = 0;
this.currentBuffer = this.buffers.get(this.currentBufferIndex);
}
public synchronized void writeTo(OutputStream out) throws IOException {
int remaining = this.count;
for (byte[] buf : this.buffers) {
int c = Math.min(buf.length, remaining);
out.write(buf, 0, c);
remaining -= c;
if (remaining == 0)
break;
}
}
public static InputStream toBufferedInputStream(InputStream input) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
output.write(input);
return output.toBufferedInputStream();
}
private InputStream toBufferedInputStream() {
int remaining = this.count;
if (remaining == 0)
return new ClosedInputStream();
List<ByteArrayInputStream> list = new ArrayList<ByteArrayInputStream>(this.buffers.size());
for (byte[] buf : this.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.<InputStream>enumeration(list));
}
public synchronized byte[] toByteArray() {
int remaining = this.count;
if (remaining == 0)
return EMPTY_BYTE_ARRAY;
byte[] newbuf = new byte[remaining];
int pos = 0;
for (byte[] buf : this.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;
}
public String toString() {
return new String(toByteArray());
}
public String toString(String enc) throws UnsupportedEncodingException {
return new String(toByteArray(), enc);
}
}

View file

@ -0,0 +1,13 @@
package org.apache.commons.io.output;
import java.io.OutputStream;
public class CloseShieldOutputStream extends ProxyOutputStream {
public CloseShieldOutputStream(OutputStream out) {
super(out);
}
public void close() {
this.out = new ClosedOutputStream();
}
}

View file

@ -0,0 +1,12 @@
package org.apache.commons.io.output;
import java.io.IOException;
import java.io.OutputStream;
public class ClosedOutputStream extends OutputStream {
public static final ClosedOutputStream CLOSED_OUTPUT_STREAM = new ClosedOutputStream();
public void write(int b) throws IOException {
throw new IOException("write(" + b + ") failed: stream is closed");
}
}

View file

@ -0,0 +1,39 @@
package org.apache.commons.io.output;
import java.io.OutputStream;
public class CountingOutputStream extends ProxyOutputStream {
private long count = 0L;
public CountingOutputStream(OutputStream out) {
super(out);
}
protected synchronized void beforeWrite(int n) {
this.count += (long)n;
}
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;
}
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;
}
public synchronized long getByteCount() {
return this.count;
}
public synchronized long resetByteCount() {
long tmp = this.count;
this.count = 0L;
return tmp;
}
}

View file

@ -0,0 +1,92 @@
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.InputStream;
import java.io.OutputStream;
import org.apache.commons.io.IOUtils;
public class DeferredFileOutputStream extends ThresholdingOutputStream {
private ByteArrayOutputStream memoryOutputStream;
private OutputStream currentOutputStream;
private File outputFile;
private final String prefix;
private final String suffix;
private final File directory;
private boolean closed = false;
public DeferredFileOutputStream(int threshold, File outputFile) {
this(threshold, outputFile, null, null, null);
}
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");
}
private DeferredFileOutputStream(int threshold, File outputFile, String prefix, String suffix, File directory) {
super(threshold);
this.outputFile = outputFile;
this.memoryOutputStream = new ByteArrayOutputStream();
this.currentOutputStream = this.memoryOutputStream;
this.prefix = prefix;
this.suffix = suffix;
this.directory = directory;
}
protected OutputStream getStream() throws IOException {
return this.currentOutputStream;
}
protected void thresholdReached() throws IOException {
if (this.prefix != null)
this.outputFile = File.createTempFile(this.prefix, this.suffix, this.directory);
FileOutputStream fos = new FileOutputStream(this.outputFile);
this.memoryOutputStream.writeTo(fos);
this.currentOutputStream = fos;
this.memoryOutputStream = null;
}
public boolean isInMemory() {
return !isThresholdExceeded();
}
public byte[] getData() {
if (this.memoryOutputStream != null)
return this.memoryOutputStream.toByteArray();
return null;
}
public File getFile() {
return this.outputFile;
}
public void close() throws IOException {
super.close();
this.closed = true;
}
public void writeTo(OutputStream out) throws IOException {
if (!this.closed)
throw new IOException("Stream not closed");
if (isInMemory()) {
this.memoryOutputStream.writeTo(out);
} else {
FileInputStream fis = new FileInputStream(this.outputFile);
try {
IOUtils.copy(fis, out);
} finally {
IOUtils.closeQuietly((InputStream)fis);
}
}
}
}

View file

@ -0,0 +1,32 @@
package org.apache.commons.io.output;
import java.io.IOException;
import java.io.OutputStream;
public class DemuxOutputStream extends OutputStream {
private final InheritableThreadLocal<OutputStream> m_streams = new InheritableThreadLocal<OutputStream>();
public OutputStream bindStream(OutputStream output) {
OutputStream stream = this.m_streams.get();
this.m_streams.set(output);
return stream;
}
public void close() throws IOException {
OutputStream output = this.m_streams.get();
if (null != output)
output.close();
}
public void flush() throws IOException {
OutputStream output = this.m_streams.get();
if (null != output)
output.flush();
}
public void write(int ch) throws IOException {
OutputStream output = this.m_streams.get();
if (null != output)
output.write(ch);
}
}

View file

@ -0,0 +1,125 @@
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;
public class FileWriterWithEncoding extends Writer {
private final Writer out;
public FileWriterWithEncoding(String filename, String encoding) throws IOException {
this(new File(filename), encoding, false);
}
public FileWriterWithEncoding(String filename, String encoding, boolean append) throws IOException {
this(new File(filename), encoding, append);
}
public FileWriterWithEncoding(String filename, Charset encoding) throws IOException {
this(new File(filename), encoding, false);
}
public FileWriterWithEncoding(String filename, Charset encoding, boolean append) throws IOException {
this(new File(filename), encoding, append);
}
public FileWriterWithEncoding(String filename, CharsetEncoder encoding) throws IOException {
this(new File(filename), encoding, false);
}
public FileWriterWithEncoding(String filename, CharsetEncoder encoding, boolean append) throws IOException {
this(new File(filename), encoding, append);
}
public FileWriterWithEncoding(File file, String encoding) throws IOException {
this(file, encoding, false);
}
public FileWriterWithEncoding(File file, String encoding, boolean append) throws IOException {
this.out = initWriter(file, encoding, append);
}
public FileWriterWithEncoding(File file, Charset encoding) throws IOException {
this(file, encoding, false);
}
public FileWriterWithEncoding(File file, Charset encoding, boolean append) throws IOException {
this.out = initWriter(file, encoding, append);
}
public FileWriterWithEncoding(File file, CharsetEncoder encoding) throws IOException {
this(file, encoding, false);
}
public FileWriterWithEncoding(File file, CharsetEncoder encoding, boolean append) throws IOException {
this.out = initWriter(file, encoding, append);
}
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)
FileUtils.deleteQuietly(file);
throw ex;
} catch (RuntimeException ex) {
IOUtils.closeQuietly(writer);
IOUtils.closeQuietly(stream);
if (!fileExistedAlready)
FileUtils.deleteQuietly(file);
throw ex;
}
return writer;
}
public void write(int idx) throws IOException {
this.out.write(idx);
}
public void write(char[] chr) throws IOException {
this.out.write(chr);
}
public void write(char[] chr, int st, int end) throws IOException {
this.out.write(chr, st, end);
}
public void write(String str) throws IOException {
this.out.write(str);
}
public void write(String str, int st, int end) throws IOException {
this.out.write(str, st, end);
}
public void flush() throws IOException {
this.out.flush();
}
public void close() throws IOException {
this.out.close();
}
}

View file

@ -0,0 +1,144 @@
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 org.apache.commons.io.Charsets;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
public class LockableFileWriter extends Writer {
private static final String LCK = ".lck";
private final Writer out;
private final File lockFile;
public LockableFileWriter(String fileName) throws IOException {
this(fileName, false, null);
}
public LockableFileWriter(String fileName, boolean append) throws IOException {
this(fileName, append, null);
}
public LockableFileWriter(String fileName, boolean append, String lockDir) throws IOException {
this(new File(fileName), append, lockDir);
}
public LockableFileWriter(File file) throws IOException {
this(file, false, null);
}
public LockableFileWriter(File file, boolean append) throws IOException {
this(file, append, null);
}
public LockableFileWriter(File file, boolean append, String lockDir) throws IOException {
this(file, Charset.defaultCharset(), append, lockDir);
}
public LockableFileWriter(File file, Charset encoding) throws IOException {
this(file, encoding, false, null);
}
public LockableFileWriter(File file, String encoding) throws IOException {
this(file, encoding, false, null);
}
public LockableFileWriter(File file, Charset encoding, boolean append, String lockDir) throws IOException {
file = file.getAbsoluteFile();
if (file.getParentFile() != null)
FileUtils.forceMkdir(file.getParentFile());
if (file.isDirectory())
throw new IOException("File specified is a directory");
if (lockDir == null)
lockDir = System.getProperty("java.io.tmpdir");
File lockDirFile = new File(lockDir);
FileUtils.forceMkdir(lockDirFile);
testLockDir(lockDirFile);
this.lockFile = new File(lockDirFile, file.getName() + ".lck");
createLock();
this.out = initWriter(file, encoding, append);
}
public LockableFileWriter(File file, String encoding, boolean append, String lockDir) throws IOException {
this(file, Charsets.toCharset(encoding), append, lockDir);
}
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());
}
private void createLock() throws IOException {
synchronized (LockableFileWriter.class) {
if (!this.lockFile.createNewFile())
throw new IOException("Can't write file, lock " + this.lockFile.getAbsolutePath() + " exists");
this.lockFile.deleteOnExit();
}
}
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(this.lockFile);
if (!fileExistedAlready)
FileUtils.deleteQuietly(file);
throw ex;
} catch (RuntimeException ex) {
IOUtils.closeQuietly(writer);
IOUtils.closeQuietly(stream);
FileUtils.deleteQuietly(this.lockFile);
if (!fileExistedAlready)
FileUtils.deleteQuietly(file);
throw ex;
}
return writer;
}
public void close() throws IOException {
try {
this.out.close();
} finally {
this.lockFile.delete();
}
}
public void write(int idx) throws IOException {
this.out.write(idx);
}
public void write(char[] chr) throws IOException {
this.out.write(chr);
}
public void write(char[] chr, int st, int end) throws IOException {
this.out.write(chr, st, end);
}
public void write(String str) throws IOException {
this.out.write(str);
}
public void write(String str, int st, int end) throws IOException {
this.out.write(str, st, end);
}
public void flush() throws IOException {
this.out.flush();
}
}

View file

@ -0,0 +1,14 @@
package org.apache.commons.io.output;
import java.io.IOException;
import java.io.OutputStream;
public class NullOutputStream extends OutputStream {
public static final NullOutputStream NULL_OUTPUT_STREAM = new NullOutputStream();
public void write(byte[] b, int off, int len) {}
public void write(int b) {}
public void write(byte[] b) throws IOException {}
}

View file

@ -0,0 +1,34 @@
package org.apache.commons.io.output;
import java.io.IOException;
import java.io.Writer;
public class NullWriter extends Writer {
public static final NullWriter NULL_WRITER = new NullWriter();
public Writer append(char c) {
return this;
}
public Writer append(CharSequence csq, int start, int end) {
return this;
}
public Writer append(CharSequence csq) {
return this;
}
public void write(int idx) {}
public void write(char[] chr) {}
public void write(char[] chr, int st, int end) {}
public void write(String str) {}
public void write(String str, int st, int end) {}
public void flush() {}
public void close() {}
}

Some files were not shown because too many files have changed in this diff Show more