lollipop版本分开,有些新特性android5.0和6.0不支持
This commit is contained in:
1 parent
0959e50f53
commit
3cf3231da5
258 files changed
+12817
-13529
No files matched your search
@@ -0,0 +1,72 @@
|
||||
package me.ag2s.epublib.util;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Enumeration;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
public class CollectionUtil {
|
||||
|
||||
/**
|
||||
* Wraps an Enumeration around an Iterator
|
||||
*
|
||||
* @param <T>
|
||||
* @author paul.siegmann
|
||||
*/
|
||||
private static class IteratorEnumerationAdapter<T> implements Enumeration<T> {
|
||||
|
||||
private final Iterator<T> iterator;
|
||||
|
||||
public IteratorEnumerationAdapter(Iterator<T> iter) {
|
||||
this.iterator = iter;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasMoreElements() {
|
||||
return iterator.hasNext();
|
||||
}
|
||||
|
||||
@Override
|
||||
public T nextElement() {
|
||||
return iterator.next();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an Enumeration out of the given Iterator.
|
||||
*
|
||||
* @param <T> g
|
||||
* @param it g
|
||||
* @return an Enumeration created out of the given Iterator.
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
public static <T> Enumeration<T> createEnumerationFromIterator(
|
||||
Iterator<T> it) {
|
||||
return new IteratorEnumerationAdapter<>(it);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the first element of the list, null if the list is null or empty.
|
||||
*
|
||||
* @param <T> f
|
||||
* @param list f
|
||||
* @return the first element of the list, null if the list is null or empty.
|
||||
*/
|
||||
public static <T> T first(List<T> list) {
|
||||
if (list == null || list.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
return list.get(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the given collection is null or has no elements.
|
||||
*
|
||||
* @param collection g
|
||||
* @return Whether the given collection is null or has no elements.
|
||||
*/
|
||||
public static boolean isEmpty(Collection<?> collection) {
|
||||
return collection == null || collection.isEmpty();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,959 @@
|
||||
package me.ag2s.epublib.util;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.Closeable;
|
||||
import java.io.EOFException;
|
||||
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.StringWriter;
|
||||
import java.io.Writer;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URLConnection;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.CharBuffer;
|
||||
import java.nio.channels.ReadableByteChannel;
|
||||
import java.nio.charset.Charset;
|
||||
|
||||
import me.ag2s.epublib.util.commons.io.IOConsumer;
|
||||
|
||||
/**
|
||||
* Most of the functions herein are re-implementations of the ones in
|
||||
* apache io IOUtils.
|
||||
* <p>
|
||||
* The reason for re-implementing this is that the functions are fairly simple
|
||||
* and using my own implementation saves the inclusion of a 200Kb jar file.
|
||||
*/
|
||||
public class IOUtil {
|
||||
private static final String TAG = IOUtil.class.getName();
|
||||
|
||||
/**
|
||||
* Represents the end-of-file (or stream).
|
||||
*
|
||||
* @since 2.5 (made public)
|
||||
*/
|
||||
public static final int EOF = -1;
|
||||
|
||||
|
||||
public static final int DEFAULT_BUFFER_SIZE = 1024 * 8;
|
||||
private static final byte[] SKIP_BYTE_BUFFER = new byte[DEFAULT_BUFFER_SIZE];
|
||||
|
||||
// Allocated in the relevant skip method if necessary.
|
||||
/*
|
||||
* These buffers are static and are shared between threads.
|
||||
* This is possible because the buffers are write-only - the contents are never read.
|
||||
*
|
||||
* N.B. there is no need to synchronize when creating these because:
|
||||
* - we don't care if the buffer is created multiple times (the data is ignored)
|
||||
* - we always use the same size buffer, so if it it is recreated it will still be OK
|
||||
* (if the buffer size were variable, we would need to synch. to ensure some other thread
|
||||
* did not create a smaller one)
|
||||
*/
|
||||
private static char[] SKIP_CHAR_BUFFER;
|
||||
|
||||
/**
|
||||
* Gets the contents of the Reader as a byte[], with the given character encoding.
|
||||
*
|
||||
* @param in g
|
||||
* @param encoding g
|
||||
* @return the contents of the Reader as a byte[], with the given character encoding.
|
||||
* @throws IOException g
|
||||
*/
|
||||
public static byte[] toByteArray(Reader in, String encoding)
|
||||
throws IOException {
|
||||
StringWriter out = new StringWriter();
|
||||
copy(in, out);
|
||||
out.flush();
|
||||
return out.toString().getBytes(encoding);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the contents of the InputStream as a byte[]
|
||||
*
|
||||
* @param in f
|
||||
* @return the contents of the InputStream as a byte[]
|
||||
* @throws IOException f
|
||||
*/
|
||||
public static byte[] toByteArray(InputStream in) throws IOException {
|
||||
ByteArrayOutputStream result = new ByteArrayOutputStream();
|
||||
copy(in, result);
|
||||
result.flush();
|
||||
return result.toByteArray();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Reads data from the InputStream, using the specified buffer size.
|
||||
* <p>
|
||||
* This is meant for situations where memory is tight, since
|
||||
* it prevents buffer expansion.
|
||||
*
|
||||
* @param in the stream to read data from
|
||||
* @param size the size of the array to create
|
||||
* @return the array, or null
|
||||
* @throws IOException f
|
||||
*/
|
||||
public static byte[] toByteArray(InputStream in, int size)
|
||||
throws IOException {
|
||||
|
||||
try {
|
||||
ByteArrayOutputStream result;
|
||||
|
||||
if (size > 0) {
|
||||
result = new ByteArrayOutputStream(size);
|
||||
} else {
|
||||
result = new ByteArrayOutputStream();
|
||||
}
|
||||
|
||||
copy(in, result);
|
||||
result.flush();
|
||||
return result.toByteArray();
|
||||
} catch (OutOfMemoryError error) {
|
||||
//Return null so it gets loaded lazily.
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* if totalNrRead < 0 then totalNrRead is returned, if
|
||||
* (nrRead + totalNrRead) < Integer.MAX_VALUE then nrRead + totalNrRead
|
||||
* is returned, -1 otherwise.
|
||||
*
|
||||
* @param nrRead f
|
||||
* @param totalNrNread f
|
||||
* @return if totalNrRead < 0 then totalNrRead is returned, if
|
||||
* (nrRead + totalNrRead) < Integer.MAX_VALUE then nrRead + totalNrRead
|
||||
* is returned, -1 otherwise.
|
||||
*/
|
||||
protected static int calcNewNrReadSize(int nrRead, int totalNrNread) {
|
||||
if (totalNrNread < 0) {
|
||||
return totalNrNread;
|
||||
}
|
||||
if (totalNrNread > (Integer.MAX_VALUE - nrRead)) {
|
||||
return -1;
|
||||
} else {
|
||||
return (totalNrNread + nrRead);
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
public static void copy(InputStream in, OutputStream result) throws IOException {
|
||||
copy(in, result, DEFAULT_BUFFER_SIZE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies bytes from an <code>InputStream</code> to an <code>OutputStream</code> using an internal buffer of the
|
||||
* given size.
|
||||
* <p>
|
||||
* This method buffers the input internally, so there is no need to use a <code>BufferedInputStream</code>.
|
||||
* </p>
|
||||
*
|
||||
* @param input the <code>InputStream</code> to read from
|
||||
* @param output the <code>OutputStream</code> to write to
|
||||
* @param bufferSize the bufferSize used to copy from the input to the output
|
||||
* @return the number of bytes copied. or {@code 0} if {@code input is null}.
|
||||
* @throws NullPointerException if the output is null
|
||||
* @throws IOException if an I/O error occurs
|
||||
* @since 2.5
|
||||
*/
|
||||
public static long copy(final InputStream input, final OutputStream output, final int bufferSize)
|
||||
throws IOException {
|
||||
return copyLarge(input, output, new byte[bufferSize]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies bytes from an <code>InputStream</code> to chars on a
|
||||
* <code>Writer</code> using the default character encoding of the platform.
|
||||
* <p>
|
||||
* This method buffers the input internally, so there is no need to use a
|
||||
* <code>BufferedInputStream</code>.
|
||||
* <p>
|
||||
* This method uses {@link InputStreamReader}.
|
||||
*
|
||||
* @param input the <code>InputStream</code> to read from
|
||||
* @param output the <code>Writer</code> to write to
|
||||
* @throws NullPointerException if the input or output is null
|
||||
* @throws IOException if an I/O error occurs
|
||||
* @since 1.1
|
||||
* @deprecated 2.5 use {@link #copy(InputStream, Writer, Charset)} instead
|
||||
*/
|
||||
@Deprecated
|
||||
public static void copy(final InputStream input, final Writer output)
|
||||
throws IOException {
|
||||
copy(input, output, Charset.defaultCharset());
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies bytes from an <code>InputStream</code> to chars on a
|
||||
* <code>Writer</code> using the specified character encoding.
|
||||
* <p>
|
||||
* This method buffers the input internally, so there is no need to use a
|
||||
* <code>BufferedInputStream</code>.
|
||||
* <p>
|
||||
* This method uses {@link InputStreamReader}.
|
||||
*
|
||||
* @param input the <code>InputStream</code> to read from
|
||||
* @param output the <code>Writer</code> to write to
|
||||
* @param inputCharset the charset to use for the input stream, null means platform default
|
||||
* @throws NullPointerException if the input or output is null
|
||||
* @throws IOException if an I/O error occurs
|
||||
* @since 2.3
|
||||
*/
|
||||
public static void copy(final InputStream input, final Writer output, final Charset inputCharset)
|
||||
throws IOException {
|
||||
final InputStreamReader in = new InputStreamReader(input, inputCharset.name());
|
||||
copy(in, output);
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies bytes from an <code>InputStream</code> to chars on a
|
||||
* <code>Writer</code> using the specified character encoding.
|
||||
* <p>
|
||||
* This method buffers the input internally, so there is no need to use a
|
||||
* <code>BufferedInputStream</code>.
|
||||
* <p>
|
||||
* Character encoding names can be found at
|
||||
* <a href="http://www.iana.org/assignments/character-sets">IANA</a>.
|
||||
* <p>
|
||||
* This method uses {@link InputStreamReader}.
|
||||
*
|
||||
* @param input the <code>InputStream</code> to read from
|
||||
* @param output the <code>Writer</code> to write to
|
||||
* @param inputCharsetName the name of the requested charset for the InputStream, null means platform default
|
||||
* @throws NullPointerException if the input or output is null
|
||||
* @throws IOException if an I/O error occurs
|
||||
* @throws java.nio.charset.UnsupportedCharsetException thrown instead of {@link java.io
|
||||
* .UnsupportedEncodingException} in version 2.2 if the
|
||||
* encoding is not supported.
|
||||
* @since 1.1
|
||||
*/
|
||||
public static void copy(final InputStream input, final Writer output, final String inputCharsetName)
|
||||
throws IOException {
|
||||
copy(input, output, Charset.forName(inputCharsetName));
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies chars from a <code>Reader</code> to a <code>Appendable</code>.
|
||||
* <p>
|
||||
* This method buffers the input internally, so there is no need to use a
|
||||
* <code>BufferedReader</code>.
|
||||
* <p>
|
||||
* Large streams (over 2GB) will return a chars copied value of
|
||||
* <code>-1</code> after the copy has completed since the correct
|
||||
* number of chars cannot be returned as an int. For large streams
|
||||
* use the <code>copyLarge(Reader, Writer)</code> method.
|
||||
*
|
||||
* @param input the <code>Reader</code> to read from
|
||||
* @param output the <code>Appendable</code> to write to
|
||||
* @return the number of characters copied, or -1 if > Integer.MAX_VALUE
|
||||
* @throws NullPointerException if the input or output is null
|
||||
* @throws IOException if an I/O error occurs
|
||||
* @since 2.7
|
||||
*/
|
||||
public static long copy(final Reader input, final Appendable output) throws IOException {
|
||||
return copy(input, output, CharBuffer.allocate(DEFAULT_BUFFER_SIZE));
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies chars from a <code>Reader</code> to an <code>Appendable</code>.
|
||||
* <p>
|
||||
* This method uses the provided buffer, so there is no need to use a
|
||||
* <code>BufferedReader</code>.
|
||||
* </p>
|
||||
*
|
||||
* @param input the <code>Reader</code> to read from
|
||||
* @param output the <code>Appendable</code> to write to
|
||||
* @param buffer the buffer to be used for the copy
|
||||
* @return the number of characters copied
|
||||
* @throws NullPointerException if the input or output is null
|
||||
* @throws IOException if an I/O error occurs
|
||||
* @since 2.7
|
||||
*/
|
||||
public static long copy(final Reader input, final Appendable output, final CharBuffer buffer) throws IOException {
|
||||
long count = 0;
|
||||
int n;
|
||||
while (EOF != (n = input.read(buffer))) {
|
||||
buffer.flip();
|
||||
output.append(buffer, 0, n);
|
||||
count += n;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies chars from a <code>Reader</code> to bytes on an
|
||||
* <code>OutputStream</code> using the default character encoding of the
|
||||
* platform, and calling flush.
|
||||
* <p>
|
||||
* This method buffers the input internally, so there is no need to use a
|
||||
* <code>BufferedReader</code>.
|
||||
* <p>
|
||||
* Due to the implementation of OutputStreamWriter, this method performs a
|
||||
* flush.
|
||||
* <p>
|
||||
* This method uses {@link OutputStreamWriter}.
|
||||
*
|
||||
* @param input the <code>Reader</code> to read from
|
||||
* @param output the <code>OutputStream</code> to write to
|
||||
* @throws NullPointerException if the input or output is null
|
||||
* @throws IOException if an I/O error occurs
|
||||
* @since 1.1
|
||||
* @deprecated 2.5 use {@link #copy(Reader, OutputStream, Charset)} instead
|
||||
*/
|
||||
@Deprecated
|
||||
public static void copy(final Reader input, final OutputStream output)
|
||||
throws IOException {
|
||||
copy(input, output, Charset.defaultCharset());
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies chars from a <code>Reader</code> to bytes on an
|
||||
* <code>OutputStream</code> using the specified character encoding, and
|
||||
* calling flush.
|
||||
* <p>
|
||||
* This method buffers the input internally, so there is no need to use a
|
||||
* <code>BufferedReader</code>.
|
||||
* </p>
|
||||
* <p>
|
||||
* Due to the implementation of OutputStreamWriter, this method performs a
|
||||
* flush.
|
||||
* </p>
|
||||
* <p>
|
||||
* This method uses {@link OutputStreamWriter}.
|
||||
* </p>
|
||||
*
|
||||
* @param input the <code>Reader</code> to read from
|
||||
* @param output the <code>OutputStream</code> to write to
|
||||
* @param outputCharset the charset to use for the OutputStream, null means platform default
|
||||
* @throws NullPointerException if the input or output is null
|
||||
* @throws IOException if an I/O error occurs
|
||||
* @since 2.3
|
||||
*/
|
||||
public static void copy(final Reader input, final OutputStream output, final Charset outputCharset)
|
||||
throws IOException {
|
||||
final OutputStreamWriter out = new OutputStreamWriter(output, outputCharset.name());
|
||||
copy(input, out);
|
||||
// XXX Unless anyone is planning on rewriting OutputStreamWriter,
|
||||
// we have to flush here.
|
||||
out.flush();
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies chars from a <code>Reader</code> to bytes on an
|
||||
* <code>OutputStream</code> using the specified character encoding, and
|
||||
* calling flush.
|
||||
* <p>
|
||||
* This method buffers the input internally, so there is no need to use a
|
||||
* <code>BufferedReader</code>.
|
||||
* <p>
|
||||
* Character encoding names can be found at
|
||||
* <a href="http://www.iana.org/assignments/character-sets">IANA</a>.
|
||||
* <p>
|
||||
* Due to the implementation of OutputStreamWriter, this method performs a
|
||||
* flush.
|
||||
* <p>
|
||||
* This method uses {@link OutputStreamWriter}.
|
||||
*
|
||||
* @param input the <code>Reader</code> to read from
|
||||
* @param output the <code>OutputStream</code> to write to
|
||||
* @param outputCharsetName the name of the requested charset for the OutputStream, null means platform default
|
||||
* @throws NullPointerException if the input or output is null
|
||||
* @throws IOException if an I/O error occurs
|
||||
* @throws java.nio.charset.UnsupportedCharsetException thrown instead of {@link java.io
|
||||
* .UnsupportedEncodingException} in version 2.2 if the
|
||||
* encoding is not supported.
|
||||
* @since 1.1
|
||||
*/
|
||||
public static void copy(final Reader input, final OutputStream output, final String outputCharsetName)
|
||||
throws IOException {
|
||||
copy(input, output, Charset.forName(outputCharsetName));
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies chars from a <code>Reader</code> to a <code>Writer</code>.
|
||||
* <p>
|
||||
* This method buffers the input internally, so there is no need to use a
|
||||
* <code>BufferedReader</code>.
|
||||
* <p>
|
||||
* Large streams (over 2GB) will return a chars copied value of
|
||||
* <code>-1</code> after the copy has completed since the correct
|
||||
* number of chars cannot be returned as an int. For large streams
|
||||
* use the <code>copyLarge(Reader, Writer)</code> method.
|
||||
*
|
||||
* @param input the <code>Reader</code> to read from
|
||||
* @param output the <code>Writer</code> to write to
|
||||
* @return the number of characters copied, or -1 if > Integer.MAX_VALUE
|
||||
* @throws NullPointerException if the input or output is null
|
||||
* @throws IOException if an I/O error occurs
|
||||
* @since 1.1
|
||||
*/
|
||||
public static int copy(final Reader input, final Writer output) throws IOException {
|
||||
final long count = copyLarge(input, output);
|
||||
if (count > Integer.MAX_VALUE) {
|
||||
return -1;
|
||||
}
|
||||
return (int) count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies bytes from a large (over 2GB) <code>InputStream</code> to an
|
||||
* <code>OutputStream</code>.
|
||||
* <p>
|
||||
* This method buffers the input internally, so there is no need to use a
|
||||
* <code>BufferedInputStream</code>.
|
||||
* </p>
|
||||
* <p>
|
||||
* The buffer size is given by {@link #DEFAULT_BUFFER_SIZE}.
|
||||
* </p>
|
||||
*
|
||||
* @param input the <code>InputStream</code> to read from
|
||||
* @param output the <code>OutputStream</code> to write to
|
||||
* @return the number of bytes copied. or {@code 0} if {@code input is null}.
|
||||
* @throws NullPointerException if the output is null
|
||||
* @throws IOException if an I/O error occurs
|
||||
* @since 1.3
|
||||
*/
|
||||
public static long copyLarge(final InputStream input, final OutputStream output)
|
||||
throws IOException {
|
||||
return copy(input, output, DEFAULT_BUFFER_SIZE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies bytes from a large (over 2GB) <code>InputStream</code> to an
|
||||
* <code>OutputStream</code>.
|
||||
* <p>
|
||||
* This method uses the provided buffer, so there is no need to use a
|
||||
* <code>BufferedInputStream</code>.
|
||||
* </p>
|
||||
*
|
||||
* @param input the <code>InputStream</code> to read from
|
||||
* @param output the <code>OutputStream</code> to write to
|
||||
* @param buffer the buffer to use for the copy
|
||||
* @return the number of bytes copied. or {@code 0} if {@code input is null}.
|
||||
* @throws IOException if an I/O error occurs
|
||||
* @since 2.2
|
||||
*/
|
||||
public static long copyLarge(final InputStream input, final OutputStream output, final byte[] buffer)
|
||||
throws IOException {
|
||||
long count = 0;
|
||||
if (input != null) {
|
||||
int n;
|
||||
while (EOF != (n = input.read(buffer))) {
|
||||
output.write(buffer, 0, n);
|
||||
count += n;
|
||||
}
|
||||
//input.close();
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies some or all bytes from a large (over 2GB) <code>InputStream</code> to an
|
||||
* <code>OutputStream</code>, optionally skipping input bytes.
|
||||
* <p>
|
||||
* This method buffers the input internally, so there is no need to use a
|
||||
* <code>BufferedInputStream</code>.
|
||||
* </p>
|
||||
* <p>
|
||||
* Note that the implementation uses {@link #skip(InputStream, long)}.
|
||||
* This means that the method may be considerably less efficient than using the actual skip implementation,
|
||||
* this is done to guarantee that the correct number of characters are skipped.
|
||||
* </p>
|
||||
* The buffer size is given by {@link #DEFAULT_BUFFER_SIZE}.
|
||||
*
|
||||
* @param input the <code>InputStream</code> to read from
|
||||
* @param output the <code>OutputStream</code> to write to
|
||||
* @param inputOffset : number of bytes to skip from input before copying
|
||||
* -ve values are ignored
|
||||
* @param length : number of bytes to copy. -ve means all
|
||||
* @return the number of bytes copied
|
||||
* @throws NullPointerException if the input or output is null
|
||||
* @throws IOException if an I/O error occurs
|
||||
* @since 2.2
|
||||
*/
|
||||
public static long copyLarge(final InputStream input, final OutputStream output, final long inputOffset,
|
||||
final long length) throws IOException {
|
||||
return copyLarge(input, output, inputOffset, length, new byte[DEFAULT_BUFFER_SIZE]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies some or all bytes from a large (over 2GB) <code>InputStream</code> to an
|
||||
* <code>OutputStream</code>, optionally skipping input bytes.
|
||||
* <p>
|
||||
* This method uses the provided buffer, so there is no need to use a
|
||||
* <code>BufferedInputStream</code>.
|
||||
* </p>
|
||||
* <p>
|
||||
* Note that the implementation uses {@link #skip(InputStream, long)}.
|
||||
* This means that the method may be considerably less efficient than using the actual skip implementation,
|
||||
* this is done to guarantee that the correct number of characters are skipped.
|
||||
* </p>
|
||||
*
|
||||
* @param input the <code>InputStream</code> to read from
|
||||
* @param output the <code>OutputStream</code> to write to
|
||||
* @param inputOffset : number of bytes to skip from input before copying
|
||||
* -ve values are ignored
|
||||
* @param length : number of bytes to copy. -ve means all
|
||||
* @param buffer the buffer to use for the copy
|
||||
* @return the number of bytes copied
|
||||
* @throws NullPointerException if the input or output is null
|
||||
* @throws IOException if an I/O error occurs
|
||||
* @since 2.2
|
||||
*/
|
||||
public static long copyLarge(final InputStream input, final OutputStream output,
|
||||
final long inputOffset, final long length, final byte[] buffer) throws IOException {
|
||||
if (inputOffset > 0) {
|
||||
skipFully(input, inputOffset);
|
||||
}
|
||||
if (length == 0) {
|
||||
return 0;
|
||||
}
|
||||
final int bufferLength = buffer.length;
|
||||
int bytesToRead = bufferLength;
|
||||
if (length > 0 && length < bufferLength) {
|
||||
bytesToRead = (int) length;
|
||||
}
|
||||
int read;
|
||||
long totalRead = 0;
|
||||
while (bytesToRead > 0 && EOF != (read = input.read(buffer, 0, bytesToRead))) {
|
||||
output.write(buffer, 0, read);
|
||||
totalRead += read;
|
||||
if (length > 0) { // only adjust length if not reading to the end
|
||||
// Note the cast must work because buffer.length is an integer
|
||||
bytesToRead = (int) Math.min(length - totalRead, bufferLength);
|
||||
}
|
||||
}
|
||||
return totalRead;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies chars from a large (over 2GB) <code>Reader</code> to a <code>Writer</code>.
|
||||
* <p>
|
||||
* This method buffers the input internally, so there is no need to use a
|
||||
* <code>BufferedReader</code>.
|
||||
* <p>
|
||||
* The buffer size is given by {@link #DEFAULT_BUFFER_SIZE}.
|
||||
*
|
||||
* @param input the <code>Reader</code> to read from
|
||||
* @param output the <code>Writer</code> to write to
|
||||
* @return the number of characters copied
|
||||
* @throws NullPointerException if the input or output is null
|
||||
* @throws IOException if an I/O error occurs
|
||||
* @since 1.3
|
||||
*/
|
||||
public static long copyLarge(final Reader input, final Writer output) throws IOException {
|
||||
return copyLarge(input, output, new char[DEFAULT_BUFFER_SIZE]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies chars from a large (over 2GB) <code>Reader</code> to a <code>Writer</code>.
|
||||
* <p>
|
||||
* This method uses the provided buffer, so there is no need to use a
|
||||
* <code>BufferedReader</code>.
|
||||
* <p>
|
||||
*
|
||||
* @param input the <code>Reader</code> to read from
|
||||
* @param output the <code>Writer</code> to write to
|
||||
* @param buffer the buffer to be used for the copy
|
||||
* @return the number of characters copied
|
||||
* @throws NullPointerException if the input or output is null
|
||||
* @throws IOException if an I/O error occurs
|
||||
* @since 2.2
|
||||
*/
|
||||
public static long copyLarge(final Reader input, final Writer output, final char[] buffer) throws IOException {
|
||||
long count = 0;
|
||||
int n;
|
||||
while (EOF != (n = input.read(buffer))) {
|
||||
output.write(buffer, 0, n);
|
||||
count += n;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies some or all chars from a large (over 2GB) <code>InputStream</code> to an
|
||||
* <code>OutputStream</code>, optionally skipping input chars.
|
||||
* <p>
|
||||
* This method buffers the input internally, so there is no need to use a
|
||||
* <code>BufferedReader</code>.
|
||||
* <p>
|
||||
* The buffer size is given by {@link #DEFAULT_BUFFER_SIZE}.
|
||||
*
|
||||
* @param input the <code>Reader</code> to read from
|
||||
* @param output the <code>Writer</code> to write to
|
||||
* @param inputOffset : number of chars to skip from input before copying
|
||||
* -ve values are ignored
|
||||
* @param length : number of chars to copy. -ve means all
|
||||
* @return the number of chars copied
|
||||
* @throws NullPointerException if the input or output is null
|
||||
* @throws IOException if an I/O error occurs
|
||||
* @since 2.2
|
||||
*/
|
||||
public static long copyLarge(final Reader input, final Writer output, final long inputOffset, final long length)
|
||||
throws IOException {
|
||||
return copyLarge(input, output, inputOffset, length, new char[DEFAULT_BUFFER_SIZE]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies some or all chars from a large (over 2GB) <code>InputStream</code> to an
|
||||
* <code>OutputStream</code>, optionally skipping input chars.
|
||||
* <p>
|
||||
* This method uses the provided buffer, so there is no need to use a
|
||||
* <code>BufferedReader</code>.
|
||||
* <p>
|
||||
*
|
||||
* @param input the <code>Reader</code> to read from
|
||||
* @param output the <code>Writer</code> to write to
|
||||
* @param inputOffset : number of chars to skip from input before copying
|
||||
* -ve values are ignored
|
||||
* @param length : number of chars to copy. -ve means all
|
||||
* @param buffer the buffer to be used for the copy
|
||||
* @return the number of chars copied
|
||||
* @throws NullPointerException if the input or output is null
|
||||
* @throws IOException if an I/O error occurs
|
||||
* @since 2.2
|
||||
*/
|
||||
public static long copyLarge(final Reader input, final Writer output, final long inputOffset, final long length,
|
||||
final char[] buffer)
|
||||
throws IOException {
|
||||
if (inputOffset > 0) {
|
||||
skipFully(input, inputOffset);
|
||||
}
|
||||
if (length == 0) {
|
||||
return 0;
|
||||
}
|
||||
int bytesToRead = buffer.length;
|
||||
if (length > 0 && length < buffer.length) {
|
||||
bytesToRead = (int) length;
|
||||
}
|
||||
int read;
|
||||
long totalRead = 0;
|
||||
while (bytesToRead > 0 && EOF != (read = input.read(buffer, 0, bytesToRead))) {
|
||||
output.write(buffer, 0, read);
|
||||
totalRead += read;
|
||||
if (length > 0) { // only adjust length if not reading to the end
|
||||
// Note the cast must work because buffer.length is an integer
|
||||
bytesToRead = (int) Math.min(length - totalRead, buffer.length);
|
||||
}
|
||||
}
|
||||
return totalRead;
|
||||
}
|
||||
|
||||
/**
|
||||
* Skips bytes from an input byte stream.
|
||||
* This implementation guarantees that it will read as many bytes
|
||||
* as possible before giving up; this may not always be the case for
|
||||
* skip() implementations in subclasses of {@link InputStream}.
|
||||
* <p>
|
||||
* Note that the implementation uses {@link InputStream#read(byte[], int, int)} rather
|
||||
* than delegating to {@link InputStream#skip(long)}.
|
||||
* This means that the method may be considerably less efficient than using the actual skip implementation,
|
||||
* this is done to guarantee that the correct number of bytes are skipped.
|
||||
* </p>
|
||||
*
|
||||
* @param input byte stream to skip
|
||||
* @param toSkip number of bytes to skip.
|
||||
* @return number of bytes actually skipped.
|
||||
* @throws IOException if there is a problem reading the file
|
||||
* @throws IllegalArgumentException if toSkip is negative
|
||||
* @see InputStream#skip(long)
|
||||
* @see <a href="https://issues.apache.org/jira/browse/IO-203">IO-203 - Add skipFully() method for InputStreams</a>
|
||||
* @since 2.0
|
||||
*/
|
||||
public static long skip(final InputStream input, final long toSkip) throws IOException {
|
||||
if (toSkip < 0) {
|
||||
throw new IllegalArgumentException("Skip count must be non-negative, actual: " + toSkip);
|
||||
}
|
||||
/*
|
||||
* N.B. no need to synchronize access to SKIP_BYTE_BUFFER: - we don't care if the buffer is created multiple
|
||||
* times (the data is ignored) - we always use the same size buffer, so if it it is recreated it will still be
|
||||
* OK (if the buffer size were variable, we would need to synch. to ensure some other thread did not create a
|
||||
* smaller one)
|
||||
*/
|
||||
long remain = toSkip;
|
||||
while (remain > 0) {
|
||||
// See https://issues.apache.org/jira/browse/IO-203 for why we use read() rather than delegating to skip()
|
||||
final long n = input.read(SKIP_BYTE_BUFFER, 0, (int) Math.min(remain, SKIP_BYTE_BUFFER.length));
|
||||
if (n < 0) { // EOF
|
||||
break;
|
||||
}
|
||||
remain -= n;
|
||||
}
|
||||
return toSkip - remain;
|
||||
}
|
||||
|
||||
/**
|
||||
* Skips bytes from a ReadableByteChannel.
|
||||
* This implementation guarantees that it will read as many bytes
|
||||
* as possible before giving up.
|
||||
*
|
||||
* @param input ReadableByteChannel to skip
|
||||
* @param toSkip number of bytes to skip.
|
||||
* @return number of bytes actually skipped.
|
||||
* @throws IOException if there is a problem reading the ReadableByteChannel
|
||||
* @throws IllegalArgumentException if toSkip is negative
|
||||
* @since 2.5
|
||||
*/
|
||||
public static long skip(final ReadableByteChannel input, final long toSkip) throws IOException {
|
||||
if (toSkip < 0) {
|
||||
throw new IllegalArgumentException("Skip count must be non-negative, actual: " + toSkip);
|
||||
}
|
||||
final ByteBuffer skipByteBuffer = ByteBuffer.allocate((int) Math.min(toSkip, SKIP_BYTE_BUFFER.length));
|
||||
long remain = toSkip;
|
||||
while (remain > 0) {
|
||||
skipByteBuffer.position(0);
|
||||
skipByteBuffer.limit((int) Math.min(remain, SKIP_BYTE_BUFFER.length));
|
||||
final int n = input.read(skipByteBuffer);
|
||||
if (n == EOF) {
|
||||
break;
|
||||
}
|
||||
remain -= n;
|
||||
}
|
||||
return toSkip - remain;
|
||||
}
|
||||
|
||||
/**
|
||||
* Skips characters from an input character stream.
|
||||
* This implementation guarantees that it will read as many characters
|
||||
* as possible before giving up; this may not always be the case for
|
||||
* skip() implementations in subclasses of {@link Reader}.
|
||||
* <p>
|
||||
* Note that the implementation uses {@link Reader#read(char[], int, int)} rather
|
||||
* than delegating to {@link Reader#skip(long)}.
|
||||
* This means that the method may be considerably less efficient than using the actual skip implementation,
|
||||
* this is done to guarantee that the correct number of characters are skipped.
|
||||
* </p>
|
||||
*
|
||||
* @param input character stream to skip
|
||||
* @param toSkip number of characters to skip.
|
||||
* @return number of characters actually skipped.
|
||||
* @throws IOException if there is a problem reading the file
|
||||
* @throws IllegalArgumentException if toSkip is negative
|
||||
* @see Reader#skip(long)
|
||||
* @see <a href="https://issues.apache.org/jira/browse/IO-203">IO-203 - Add skipFully() method for InputStreams</a>
|
||||
* @since 2.0
|
||||
*/
|
||||
public static long skip(final Reader input, final long toSkip) throws IOException {
|
||||
if (toSkip < 0) {
|
||||
throw new IllegalArgumentException("Skip count must be non-negative, actual: " + toSkip);
|
||||
}
|
||||
/*
|
||||
* N.B. no need to synchronize this because: - we don't care if the buffer is created multiple times (the data
|
||||
* is ignored) - we always use the same size buffer, so if it it is recreated it will still be OK (if the buffer
|
||||
* size were variable, we would need to synch. to ensure some other thread did not create a smaller one)
|
||||
*/
|
||||
if (SKIP_CHAR_BUFFER == null) {
|
||||
SKIP_CHAR_BUFFER = new char[SKIP_BYTE_BUFFER.length];
|
||||
}
|
||||
long remain = toSkip;
|
||||
while (remain > 0) {
|
||||
// See https://issues.apache.org/jira/browse/IO-203 for why we use read() rather than delegating to skip()
|
||||
final long n = input.read(SKIP_CHAR_BUFFER, 0, (int) Math.min(remain, SKIP_BYTE_BUFFER.length));
|
||||
if (n < 0) { // EOF
|
||||
break;
|
||||
}
|
||||
remain -= n;
|
||||
}
|
||||
return toSkip - remain;
|
||||
}
|
||||
|
||||
/**
|
||||
* Skips the requested number of bytes or fail if there are not enough left.
|
||||
* <p>
|
||||
* This allows for the possibility that {@link InputStream#skip(long)} may
|
||||
* not skip as many bytes as requested (most likely because of reaching EOF).
|
||||
* <p>
|
||||
* Note that the implementation uses {@link #skip(InputStream, long)}.
|
||||
* This means that the method may be considerably less efficient than using the actual skip implementation,
|
||||
* this is done to guarantee that the correct number of characters are skipped.
|
||||
* </p>
|
||||
*
|
||||
* @param input stream to skip
|
||||
* @param toSkip the number of bytes to skip
|
||||
* @throws IOException if there is a problem reading the file
|
||||
* @throws IllegalArgumentException if toSkip is negative
|
||||
* @throws EOFException if the number of bytes skipped was incorrect
|
||||
* @see InputStream#skip(long)
|
||||
* @since 2.0
|
||||
*/
|
||||
public static void skipFully(final InputStream input, final long toSkip) throws IOException {
|
||||
if (toSkip < 0) {
|
||||
throw new IllegalArgumentException("Bytes to skip must not be negative: " + toSkip);
|
||||
}
|
||||
final long skipped = skip(input, toSkip);
|
||||
if (skipped != toSkip) {
|
||||
throw new EOFException("Bytes to skip: " + toSkip + " actual: " + skipped);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Skips the requested number of bytes or fail if there are not enough left.
|
||||
*
|
||||
* @param input ReadableByteChannel to skip
|
||||
* @param toSkip the number of bytes to skip
|
||||
* @throws IOException if there is a problem reading the ReadableByteChannel
|
||||
* @throws IllegalArgumentException if toSkip is negative
|
||||
* @throws EOFException if the number of bytes skipped was incorrect
|
||||
* @since 2.5
|
||||
*/
|
||||
public static void skipFully(final ReadableByteChannel input, final long toSkip) throws IOException {
|
||||
if (toSkip < 0) {
|
||||
throw new IllegalArgumentException("Bytes to skip must not be negative: " + toSkip);
|
||||
}
|
||||
final long skipped = skip(input, toSkip);
|
||||
if (skipped != toSkip) {
|
||||
throw new EOFException("Bytes to skip: " + toSkip + " actual: " + skipped);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Skips the requested number of characters or fail if there are not enough left.
|
||||
* <p>
|
||||
* This allows for the possibility that {@link Reader#skip(long)} may
|
||||
* not skip as many characters as requested (most likely because of reaching EOF).
|
||||
* <p>
|
||||
* Note that the implementation uses {@link #skip(Reader, long)}.
|
||||
* This means that the method may be considerably less efficient than using the actual skip implementation,
|
||||
* this is done to guarantee that the correct number of characters are skipped.
|
||||
* </p>
|
||||
*
|
||||
* @param input stream to skip
|
||||
* @param toSkip the number of characters to skip
|
||||
* @throws IOException if there is a problem reading the file
|
||||
* @throws IllegalArgumentException if toSkip is negative
|
||||
* @throws EOFException if the number of characters skipped was incorrect
|
||||
* @see Reader#skip(long)
|
||||
* @since 2.0
|
||||
*/
|
||||
public static void skipFully(final Reader input, final long toSkip) throws IOException {
|
||||
final long skipped = skip(input, toSkip);
|
||||
if (skipped != toSkip) {
|
||||
throw new EOFException("Chars to skip: " + toSkip + " actual: " + skipped);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the length of the given array in a null-safe manner.
|
||||
*
|
||||
* @param array an array or null
|
||||
* @return the array length -- or 0 if the given array is null.
|
||||
* @since 2.7
|
||||
*/
|
||||
public static int length(final byte[] array) {
|
||||
return array == null ? 0 : array.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the length of the given array in a null-safe manner.
|
||||
*
|
||||
* @param array an array or null
|
||||
* @return the array length -- or 0 if the given array is null.
|
||||
* @since 2.7
|
||||
*/
|
||||
public static int length(final char[] array) {
|
||||
return array == null ? 0 : array.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the length of the given CharSequence in a null-safe manner.
|
||||
*
|
||||
* @param csq a CharSequence or null
|
||||
* @return the CharSequence length -- or 0 if the given CharSequence is null.
|
||||
* @since 2.7
|
||||
*/
|
||||
public static int length(final CharSequence csq) {
|
||||
return csq == null ? 0 : csq.length();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the length of the given array in a null-safe manner.
|
||||
*
|
||||
* @param array an array or null
|
||||
* @return the array length -- or 0 if the given array is null.
|
||||
* @since 2.7
|
||||
*/
|
||||
public static int length(final Object[] array) {
|
||||
return array == null ? 0 : array.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the given {@link Closeable} as a null-safe operation.
|
||||
*
|
||||
* @param closeable The resource to close, may be null.
|
||||
* @throws IOException if an I/O error occurs.
|
||||
* @since 2.7
|
||||
*/
|
||||
public static void close(final Closeable closeable) throws IOException {
|
||||
if (closeable != null) {
|
||||
closeable.close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the given {@link Closeable} as a null-safe operation.
|
||||
*
|
||||
* @param closeables The resource(s) to close, may be null.
|
||||
* @throws IOException if an I/O error occurs.
|
||||
* @since 2.8.0
|
||||
*/
|
||||
public static void close(final Closeable... closeables) throws IOException {
|
||||
if (closeables != null) {
|
||||
for (final Closeable closeable : closeables) {
|
||||
close(closeable);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the given {@link Closeable} as a null-safe operation.
|
||||
*
|
||||
* @param closeable The resource to close, may be null.
|
||||
* @param consumer Consume the IOException thrown by {@link Closeable#close()}.
|
||||
* @throws IOException if an I/O error occurs.
|
||||
* @since 2.7
|
||||
*/
|
||||
public static void close(final Closeable closeable, final IOConsumer<IOException> consumer) throws IOException {
|
||||
if (closeable != null) {
|
||||
try {
|
||||
closeable.close();
|
||||
} catch (final IOException e) {
|
||||
if (consumer != null) {
|
||||
consumer.accept(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes a URLConnection.
|
||||
*
|
||||
* @param conn the connection to close.
|
||||
* @since 2.4
|
||||
*/
|
||||
public static void close(final URLConnection conn) {
|
||||
if (conn instanceof HttpURLConnection) {
|
||||
((HttpURLConnection) conn).disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
public static String Stream2String(InputStream inputStream) {
|
||||
ByteArrayOutputStream result = new ByteArrayOutputStream();
|
||||
try {
|
||||
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
|
||||
int length;
|
||||
while ((length = inputStream.read(buffer)) != -1) {
|
||||
result.write(buffer, 0, length);
|
||||
}
|
||||
return result.toString();
|
||||
} catch (Exception e) {
|
||||
return e.getLocalizedMessage();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package me.ag2s.epublib.util;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
|
||||
/**
|
||||
* OutputStream with the close() disabled.
|
||||
* We write multiple documents to a ZipOutputStream.
|
||||
* Some of the formatters call a close() after writing their data.
|
||||
* We don't want them to do that, so we wrap regular OutputStreams in this NoCloseOutputStream.
|
||||
*
|
||||
* @author paul
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
public class NoCloseOutputStream extends OutputStream {
|
||||
|
||||
private final OutputStream outputStream;
|
||||
|
||||
public NoCloseOutputStream(OutputStream outputStream) {
|
||||
this.outputStream = outputStream;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(int b) throws IOException {
|
||||
outputStream.write(b);
|
||||
}
|
||||
|
||||
/**
|
||||
* A close() that does not call it's parent's close()
|
||||
*/
|
||||
public void close() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package me.ag2s.epublib.util;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.Writer;
|
||||
|
||||
/**
|
||||
* Writer with the close() disabled.
|
||||
* We write multiple documents to a ZipOutputStream.
|
||||
* Some of the formatters call a close() after writing their data.
|
||||
* We don't want them to do that, so we wrap regular Writers in this NoCloseWriter.
|
||||
*
|
||||
* @author paul
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
public class NoCloseWriter extends Writer {
|
||||
|
||||
private final Writer writer;
|
||||
|
||||
public NoCloseWriter(Writer writer) {
|
||||
this.writer = writer;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void flush() throws IOException {
|
||||
writer.flush();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(char[] cbuf, int off, int len) throws IOException {
|
||||
writer.write(cbuf, off, len);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
package me.ag2s.epublib.util;
|
||||
|
||||
import org.w3c.dom.Document;
|
||||
import org.xml.sax.InputSource;
|
||||
import org.xml.sax.SAXException;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.Reader;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.util.zip.ZipInputStream;
|
||||
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
|
||||
import me.ag2s.epublib.Constants;
|
||||
import me.ag2s.epublib.domain.MediaType;
|
||||
import me.ag2s.epublib.domain.MediaTypes;
|
||||
import me.ag2s.epublib.domain.Resource;
|
||||
import me.ag2s.epublib.epub.EpubProcessorSupport;
|
||||
|
||||
/**
|
||||
* Various resource utility methods
|
||||
*
|
||||
* @author paul
|
||||
*/
|
||||
public class ResourceUtil {
|
||||
/**
|
||||
* 快速创建HTML类型的Resource
|
||||
*
|
||||
* @param title 章节的标题
|
||||
* @param txt 章节的正文
|
||||
* @param model html模板
|
||||
* @return 返回Resource
|
||||
*/
|
||||
public static Resource createChapterResource(String title, String txt, String model, String href) {
|
||||
//String[] title_list = title.split("\\s+", 2);
|
||||
//String title_part1 = title_list[0];
|
||||
//String title_part2 = "";
|
||||
//if (title_list.length == 2) {
|
||||
// title_part2 = title_list[1];
|
||||
//}
|
||||
String ori_title = title;
|
||||
title = title.replaceFirst("\\s+", "</span><br />");
|
||||
if (title.contains("</span>")) {
|
||||
title = "<span class=\"chapter-sequence-number\">" + title;
|
||||
}
|
||||
String html = model.replace("{title}", title)
|
||||
.replace("{ori_title}", ori_title)
|
||||
//.replace("{title_part1}", title_part1)
|
||||
//.replace("{title_part2}", title_part2)
|
||||
.replace("{content}", StringUtil.formatHtml(txt));
|
||||
return new Resource(html.getBytes(), href);
|
||||
}
|
||||
|
||||
public static Resource createPublicResource(String name, String author, String intro, String kind, String wordCount, String model, String href) {
|
||||
String html = model.replace("{name}", name)
|
||||
.replace("{author}", author)
|
||||
.replace("{kind}", kind == null ? "" : kind)
|
||||
.replace("{wordCount}", wordCount == null ? "" : wordCount)
|
||||
.replace("{intro}", StringUtil.formatHtml(intro == null ? "" : intro));
|
||||
return new Resource(html.getBytes(), href);
|
||||
}
|
||||
|
||||
/**
|
||||
* 快速从File创建Resource
|
||||
*
|
||||
* @param file File
|
||||
* @return Resource
|
||||
* @throws IOException IOException
|
||||
*/
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
public static Resource createResource(File file) throws IOException {
|
||||
if (file == null) {
|
||||
return null;
|
||||
}
|
||||
MediaType mediaType = MediaTypes.determineMediaType(file.getName());
|
||||
byte[] data = IOUtil.toByteArray(new FileInputStream(file));
|
||||
return new Resource(data, mediaType);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 创建一个只带标题的HTMl类型的Resource,常用于封面页,大卷页
|
||||
*
|
||||
* @param title v
|
||||
* @param href v
|
||||
* @return a resource with as contents a html page with the given title.
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
public static Resource createResource(String title, String href) {
|
||||
String content =
|
||||
"<html><head><title>" + title + "</title></head><body><h1>" + title
|
||||
+ "</h1></body></html>";
|
||||
return new Resource(null, content.getBytes(), href, MediaTypes.XHTML,
|
||||
Constants.CHARACTER_ENCODING);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a resource out of the given zipEntry and zipInputStream.
|
||||
*
|
||||
* @param name v
|
||||
* @param zipInputStream v
|
||||
* @return a resource created out of the given zipEntry and zipInputStream.
|
||||
* @throws IOException v
|
||||
*/
|
||||
public static Resource createResource(String name,
|
||||
ZipInputStream zipInputStream) throws IOException {
|
||||
return new Resource(zipInputStream, name);
|
||||
|
||||
}
|
||||
|
||||
public static Resource createResource(String name,
|
||||
InputStream zipInputStream) throws IOException {
|
||||
return new Resource(zipInputStream, name);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a given string from given input character encoding to the requested output character encoding.
|
||||
*
|
||||
* @param inputEncoding v
|
||||
* @param outputEncoding v
|
||||
* @param input v
|
||||
* @return the string from given input character encoding converted to the requested output character encoding.
|
||||
* @throws UnsupportedEncodingException v
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
public static byte[] recode(String inputEncoding, String outputEncoding,
|
||||
byte[] input) throws UnsupportedEncodingException {
|
||||
return new String(input, inputEncoding).getBytes(outputEncoding);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the contents of the Resource as an InputSource in a null-safe manner.
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
public static InputSource getInputSource(Resource resource)
|
||||
throws IOException {
|
||||
if (resource == null) {
|
||||
return null;
|
||||
}
|
||||
Reader reader = resource.getReader();
|
||||
if (reader == null) {
|
||||
return null;
|
||||
}
|
||||
return new InputSource(reader);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Reads parses the xml therein and returns the result as a Document
|
||||
*/
|
||||
public static Document getAsDocument(Resource resource)
|
||||
throws SAXException, IOException {
|
||||
return getAsDocument(resource,
|
||||
EpubProcessorSupport.createDocumentBuilder());
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the given resources inputstream, parses the xml therein and returns the result as a Document
|
||||
*
|
||||
* @param resource v
|
||||
* @param documentBuilder v
|
||||
* @return the document created from the given resource
|
||||
* @throws UnsupportedEncodingException v
|
||||
* @throws SAXException v
|
||||
* @throws IOException v
|
||||
*/
|
||||
public static Document getAsDocument(Resource resource,
|
||||
DocumentBuilder documentBuilder)
|
||||
throws UnsupportedEncodingException, SAXException, IOException {
|
||||
InputSource inputSource = getInputSource(resource);
|
||||
if (inputSource == null) {
|
||||
return null;
|
||||
}
|
||||
return documentBuilder.parse(inputSource);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
package me.ag2s.epublib.util;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Various String utility functions.
|
||||
* <p>
|
||||
* Most of the functions herein are re-implementations of the ones in apache
|
||||
* commons StringUtils. The reason for re-implementing this is that the
|
||||
* functions are fairly simple and using my own implementation saves the
|
||||
* inclusion of a 200Kb jar file.
|
||||
*
|
||||
* @author paul.siegmann
|
||||
*/
|
||||
public class StringUtil {
|
||||
|
||||
/**
|
||||
* Changes a path containing '..', '.' and empty dirs into a path that
|
||||
* doesn't. X/foo/../Y is changed into 'X/Y', etc. Does not handle invalid
|
||||
* paths like "../".
|
||||
*
|
||||
* @param path path
|
||||
* @return the normalized path
|
||||
*/
|
||||
public static String collapsePathDots(String path) {
|
||||
String[] stringParts = path.split("/");
|
||||
List<String> parts = new ArrayList<>(Arrays.asList(stringParts));
|
||||
for (int i = 0; i < parts.size() - 1; i++) {
|
||||
String currentDir = parts.get(i);
|
||||
if (currentDir.length() == 0 || currentDir.equals(".")) {
|
||||
parts.remove(i);
|
||||
i--;
|
||||
} else if (currentDir.equals("..")) {
|
||||
parts.remove(i - 1);
|
||||
parts.remove(i - 1);
|
||||
i -= 2;
|
||||
}
|
||||
}
|
||||
StringBuilder result = new StringBuilder();
|
||||
if (path.startsWith("/")) {
|
||||
result.append('/');
|
||||
}
|
||||
for (int i = 0; i < parts.size(); i++) {
|
||||
result.append(parts.get(i));
|
||||
if (i < (parts.size() - 1)) {
|
||||
result.append('/');
|
||||
}
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the String is not null, not zero-length and does not contain of
|
||||
* only whitespace.
|
||||
*
|
||||
* @param text text
|
||||
* @return Whether the String is not null, not zero-length and does not contain of
|
||||
*/
|
||||
public static boolean isNotBlank(String text) {
|
||||
return !isBlank(text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the String is null, zero-length and does contain only whitespace.
|
||||
*
|
||||
* @return Whether the String is null, zero-length and does contain only whitespace.
|
||||
*/
|
||||
public static boolean isBlank(String text) {
|
||||
if (isEmpty(text)) {
|
||||
return true;
|
||||
}
|
||||
for (int i = 0; i < text.length(); i++) {
|
||||
if (!Character.isWhitespace(text.charAt(i))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the given string is null or zero-length.
|
||||
*
|
||||
* @param text the input for this method
|
||||
* @return Whether the given string is null or zero-length.
|
||||
*/
|
||||
public static boolean isEmpty(String text) {
|
||||
return (text == null) || (text.length() == 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the given source string ends with the given suffix, ignoring
|
||||
* case.
|
||||
*
|
||||
* @param source source
|
||||
* @param suffix suffix
|
||||
* @return Whether the given source string ends with the given suffix, ignoring case.
|
||||
*/
|
||||
public static boolean endsWithIgnoreCase(String source, String suffix) {
|
||||
if (isEmpty(suffix)) {
|
||||
return true;
|
||||
}
|
||||
if (isEmpty(source)) {
|
||||
return false;
|
||||
}
|
||||
if (suffix.length() > source.length()) {
|
||||
return false;
|
||||
}
|
||||
return source.substring(source.length() - suffix.length())
|
||||
.toLowerCase().endsWith(suffix.toLowerCase());
|
||||
}
|
||||
|
||||
/**
|
||||
* If the given text is null return "", the original text otherwise.
|
||||
*
|
||||
* @param text text
|
||||
* @return If the given text is null "", the original text otherwise.
|
||||
*/
|
||||
public static String defaultIfNull(String text) {
|
||||
return defaultIfNull(text, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* If the given text is null return "", the given defaultValue otherwise.
|
||||
*
|
||||
* @param text d
|
||||
* @param defaultValue d
|
||||
* @return If the given text is null "", the given defaultValue otherwise.
|
||||
*/
|
||||
public static String defaultIfNull(String text, String defaultValue) {
|
||||
if (text == null) {
|
||||
return defaultValue;
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
/**
|
||||
* Null-safe string comparator
|
||||
*
|
||||
* @param text1 d
|
||||
* @param text2 d
|
||||
* @return whether the two strings are equal
|
||||
*/
|
||||
public static boolean equals(String text1, String text2) {
|
||||
if (text1 == null) {
|
||||
return (text2 == null);
|
||||
}
|
||||
return text1.equals(text2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pretty toString printer.
|
||||
*
|
||||
* @param keyValues d
|
||||
* @return a string representation of the input values
|
||||
*/
|
||||
public static String toString(Object... keyValues) {
|
||||
StringBuilder result = new StringBuilder();
|
||||
result.append('[');
|
||||
for (int i = 0; i < keyValues.length; i += 2) {
|
||||
if (i > 0) {
|
||||
result.append(", ");
|
||||
}
|
||||
result.append(keyValues[i]);
|
||||
result.append(": ");
|
||||
Object value = null;
|
||||
if ((i + 1) < keyValues.length) {
|
||||
value = keyValues[i + 1];
|
||||
}
|
||||
if (value == null) {
|
||||
result.append("<null>");
|
||||
} else {
|
||||
result.append('\'');
|
||||
result.append(value);
|
||||
result.append('\'');
|
||||
}
|
||||
}
|
||||
result.append(']');
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
public static int hashCode(String... values) {
|
||||
int result = 31;
|
||||
for (String value : values) {
|
||||
result ^= String.valueOf(value).hashCode();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gives the substring of the given text before the given separator.
|
||||
* <p>
|
||||
* If the text does not contain the given separator then the given text is
|
||||
* returned.
|
||||
*
|
||||
* @param text d
|
||||
* @param separator d
|
||||
* @return the substring of the given text before the given separator.
|
||||
*/
|
||||
public static String substringBefore(String text, char separator) {
|
||||
if (isEmpty(text)) {
|
||||
return text;
|
||||
}
|
||||
int sepPos = text.indexOf(separator);
|
||||
if (sepPos < 0) {
|
||||
return text;
|
||||
}
|
||||
return text.substring(0, sepPos);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gives the substring of the given text before the last occurrence of the
|
||||
* given separator.
|
||||
* <p>
|
||||
* If the text does not contain the given separator then the given text is
|
||||
* returned.
|
||||
*
|
||||
* @param text d
|
||||
* @param separator d
|
||||
* @return the substring of the given text before the last occurrence of the given separator.
|
||||
*/
|
||||
public static String substringBeforeLast(String text, char separator) {
|
||||
if (isEmpty(text)) {
|
||||
return text;
|
||||
}
|
||||
int cPos = text.lastIndexOf(separator);
|
||||
if (cPos < 0) {
|
||||
return text;
|
||||
}
|
||||
return text.substring(0, cPos);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gives the substring of the given text after the last occurrence of the
|
||||
* given separator.
|
||||
* <p>
|
||||
* If the text does not contain the given separator then "" is returned.
|
||||
*
|
||||
* @param text d
|
||||
* @param separator d
|
||||
* @return the substring of the given text after the last occurrence of the given separator.
|
||||
*/
|
||||
public static String substringAfterLast(String text, char separator) {
|
||||
if (isEmpty(text)) {
|
||||
return text;
|
||||
}
|
||||
int cPos = text.lastIndexOf(separator);
|
||||
if (cPos < 0) {
|
||||
return "";
|
||||
}
|
||||
return text.substring(cPos + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gives the substring of the given text after the given separator.
|
||||
* <p>
|
||||
* If the text does not contain the given separator then "" is returned.
|
||||
*
|
||||
* @param text the input text
|
||||
* @param c the separator char
|
||||
* @return the substring of the given text after the given separator.
|
||||
*/
|
||||
public static String substringAfter(String text, char c) {
|
||||
if (isEmpty(text)) {
|
||||
return text;
|
||||
}
|
||||
int cPos = text.indexOf(c);
|
||||
if (cPos < 0) {
|
||||
return "";
|
||||
}
|
||||
return text.substring(cPos + 1);
|
||||
}
|
||||
|
||||
public static String formatHtml(String text) {
|
||||
StringBuilder body = new StringBuilder();
|
||||
for (String s : text.split("\\r?\\n")) {
|
||||
s = s.replaceAll("^\\s+|\\s+$", "");
|
||||
if (s.length() > 0) {
|
||||
//段落为一张图片才认定为图片章节/漫画并启用多看单图优化,否则认定为普通文字夹杂着的图片文字。
|
||||
if (s.matches("(?i)^<img\\s([^>]+)/?>$")) {
|
||||
body.append(s.replaceAll("(?i)^<img\\s([^>]+)/?>$",
|
||||
"<div class=\"duokan-image-single\"><img class=\"picture-80\" $1/></div>"));
|
||||
} else {
|
||||
body.append("<p>").append(s).append("</p>");
|
||||
}
|
||||
}
|
||||
}
|
||||
return body.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,383 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF licenses this file to You under the Apache License, Version 2.0
|
||||
* (the "License"); you may not use this file except in compliance with
|
||||
* the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package me.ag2s.epublib.util.commons.io;
|
||||
|
||||
|
||||
import static me.ag2s.epublib.util.IOUtil.EOF;
|
||||
|
||||
import android.os.Build;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
|
||||
import me.ag2s.epublib.util.IOUtil;
|
||||
|
||||
|
||||
/**
|
||||
* This class is used to wrap a stream that includes an encoded {@link ByteOrderMark} as its first bytes.
|
||||
* <p>
|
||||
* This class detects these bytes and, if required, can automatically skip them and return the subsequent byte as the
|
||||
* first byte in the stream.
|
||||
* <p>
|
||||
* The {@link ByteOrderMark} implementation has the following pre-defined BOMs:
|
||||
* <ul>
|
||||
* <li>UTF-8 - {@link ByteOrderMark#UTF_8}</li>
|
||||
* <li>UTF-16BE - {@link ByteOrderMark#UTF_16LE}</li>
|
||||
* <li>UTF-16LE - {@link ByteOrderMark#UTF_16BE}</li>
|
||||
* <li>UTF-32BE - {@link ByteOrderMark#UTF_32LE}</li>
|
||||
* <li>UTF-32LE - {@link ByteOrderMark#UTF_32BE}</li>
|
||||
* </ul>
|
||||
*
|
||||
*
|
||||
* <h2>Example 1 - Detect and exclude a UTF-8 BOM</h2>
|
||||
*
|
||||
* <pre>
|
||||
* BOMInputStream bomIn = new BOMInputStream(in);
|
||||
* if (bomIn.hasBOM()) {
|
||||
* // has a UTF-8 BOM
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* <h2>Example 2 - Detect a UTF-8 BOM (but don't exclude it)</h2>
|
||||
*
|
||||
* <pre>
|
||||
* boolean include = true;
|
||||
* BOMInputStream bomIn = new BOMInputStream(in, include);
|
||||
* if (bomIn.hasBOM()) {
|
||||
* // has a UTF-8 BOM
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* <h2>Example 3 - Detect Multiple BOMs</h2>
|
||||
*
|
||||
* <pre>
|
||||
* BOMInputStream bomIn = new BOMInputStream(in,
|
||||
* ByteOrderMark.UTF_16LE, ByteOrderMark.UTF_16BE,
|
||||
* ByteOrderMark.UTF_32LE, ByteOrderMark.UTF_32BE
|
||||
* );
|
||||
* if (bomIn.hasBOM() == false) {
|
||||
* // No BOM found
|
||||
* } else if (bomIn.hasBOM(ByteOrderMark.UTF_16LE)) {
|
||||
* // has a UTF-16LE BOM
|
||||
* } else if (bomIn.hasBOM(ByteOrderMark.UTF_16BE)) {
|
||||
* // has a UTF-16BE BOM
|
||||
* } else if (bomIn.hasBOM(ByteOrderMark.UTF_32LE)) {
|
||||
* // has a UTF-32LE BOM
|
||||
* } else if (bomIn.hasBOM(ByteOrderMark.UTF_32BE)) {
|
||||
* // has a UTF-32BE BOM
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* @see ByteOrderMark
|
||||
* @see <a href="http://en.wikipedia.org/wiki/Byte_order_mark">Wikipedia - Byte Order Mark</a>
|
||||
* @since 2.0
|
||||
*/
|
||||
public class BOMInputStream extends ProxyInputStream {
|
||||
private final boolean include;
|
||||
/**
|
||||
* BOMs are sorted from longest to shortest.
|
||||
*/
|
||||
private final List<ByteOrderMark> boms;
|
||||
private ByteOrderMark byteOrderMark;
|
||||
private int[] firstBytes;
|
||||
private int fbLength;
|
||||
private int fbIndex;
|
||||
private int markFbIndex;
|
||||
private boolean markedAtStart;
|
||||
|
||||
/**
|
||||
* Constructs a new BOM InputStream that excludes a {@link ByteOrderMark#UTF_8} BOM.
|
||||
*
|
||||
* @param delegate the InputStream to delegate to
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
public BOMInputStream(final InputStream delegate) {
|
||||
this(delegate, false, ByteOrderMark.UTF_8);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a new BOM InputStream that detects a a {@link ByteOrderMark#UTF_8} and optionally includes it.
|
||||
*
|
||||
* @param delegate the InputStream to delegate to
|
||||
* @param include true to include the UTF-8 BOM or false to exclude it
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
public BOMInputStream(final InputStream delegate, final boolean include) {
|
||||
this(delegate, include, ByteOrderMark.UTF_8);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a new BOM InputStream that excludes the specified BOMs.
|
||||
*
|
||||
* @param delegate the InputStream to delegate to
|
||||
* @param boms The BOMs to detect and exclude
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
public BOMInputStream(final InputStream delegate, final ByteOrderMark... boms) {
|
||||
this(delegate, false, boms);
|
||||
}
|
||||
|
||||
/**
|
||||
* Compares ByteOrderMark objects in descending length order.
|
||||
*/
|
||||
private static final Comparator<ByteOrderMark> ByteOrderMarkLengthComparator = (bom1, bom2) -> {
|
||||
final int len1 = bom1.length();
|
||||
final int len2 = bom2.length();
|
||||
return Integer.compare(len2, len1);
|
||||
};
|
||||
|
||||
/**
|
||||
* Constructs a new BOM InputStream that detects the specified BOMs and optionally includes them.
|
||||
*
|
||||
* @param delegate the InputStream to delegate to
|
||||
* @param include true to include the specified BOMs or false to exclude them
|
||||
* @param boms The BOMs to detect and optionally exclude
|
||||
*/
|
||||
public BOMInputStream(final InputStream delegate, final boolean include, final ByteOrderMark... boms) {
|
||||
super(delegate);
|
||||
if (IOUtil.length(boms) == 0) {
|
||||
throw new IllegalArgumentException("No BOMs specified");
|
||||
}
|
||||
this.include = include;
|
||||
final List<ByteOrderMark> list = Arrays.asList(boms);
|
||||
// Sort the BOMs to match the longest BOM first because some BOMs have the same starting two bytes.
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
|
||||
list.sort(ByteOrderMarkLengthComparator);
|
||||
}
|
||||
this.boms = list;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates whether the stream contains one of the specified BOMs.
|
||||
*
|
||||
* @return true if the stream has one of the specified BOMs, otherwise false if it does not
|
||||
* @throws IOException if an error reading the first bytes of the stream occurs
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
public boolean hasBOM() throws IOException {
|
||||
return getBOM() != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates whether the stream contains the specified BOM.
|
||||
*
|
||||
* @param bom The BOM to check for
|
||||
* @return true if the stream has the specified BOM, otherwise false if it does not
|
||||
* @throws IllegalArgumentException if the BOM is not one the stream is configured to detect
|
||||
* @throws IOException if an error reading the first bytes of the stream occurs
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
public boolean hasBOM(final ByteOrderMark bom) throws IOException {
|
||||
if (!boms.contains(bom)) {
|
||||
throw new IllegalArgumentException("Stream not configure to detect " + bom);
|
||||
}
|
||||
getBOM();
|
||||
return byteOrderMark != null && byteOrderMark.equals(bom);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the BOM (Byte Order Mark).
|
||||
*
|
||||
* @return The BOM or null if none
|
||||
* @throws IOException if an error reading the first bytes of the stream occurs
|
||||
*/
|
||||
public ByteOrderMark getBOM() throws IOException {
|
||||
if (firstBytes == null) {
|
||||
fbLength = 0;
|
||||
// BOMs are sorted from longest to shortest
|
||||
final int maxBomSize = boms.get(0).length();
|
||||
firstBytes = new int[maxBomSize];
|
||||
// Read first maxBomSize bytes
|
||||
for (int i = 0; i < firstBytes.length; i++) {
|
||||
firstBytes[i] = in.read();
|
||||
fbLength++;
|
||||
if (firstBytes[i] < 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// match BOM in firstBytes
|
||||
byteOrderMark = find();
|
||||
if (byteOrderMark != null) {
|
||||
if (!include) {
|
||||
if (byteOrderMark.length() < firstBytes.length) {
|
||||
fbIndex = byteOrderMark.length();
|
||||
} else {
|
||||
fbLength = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return byteOrderMark;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the BOM charset Name - {@link ByteOrderMark#getCharsetName()}.
|
||||
*
|
||||
* @return The BOM charset Name or null if no BOM found
|
||||
* @throws IOException if an error reading the first bytes of the stream occurs
|
||||
*/
|
||||
public String getBOMCharsetName() throws IOException {
|
||||
getBOM();
|
||||
return byteOrderMark == null ? null : byteOrderMark.getCharsetName();
|
||||
}
|
||||
|
||||
/**
|
||||
* This method reads and either preserves or skips the first bytes in the stream. It behaves like the single-byte
|
||||
* <code>read()</code> method, either returning a valid byte or -1 to indicate that the initial bytes have been
|
||||
* processed already.
|
||||
*
|
||||
* @return the byte read (excluding BOM) or -1 if the end of stream
|
||||
* @throws IOException if an I/O error occurs
|
||||
*/
|
||||
private int readFirstBytes() throws IOException {
|
||||
getBOM();
|
||||
return fbIndex < fbLength ? firstBytes[fbIndex++] : EOF;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a BOM with the specified bytes.
|
||||
*
|
||||
* @return The matched BOM or null if none matched
|
||||
*/
|
||||
private ByteOrderMark find() {
|
||||
for (final ByteOrderMark bom : boms) {
|
||||
if (matches(bom)) {
|
||||
return bom;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the bytes match a BOM.
|
||||
*
|
||||
* @param bom The BOM
|
||||
* @return true if the bytes match the bom, otherwise false
|
||||
*/
|
||||
private boolean matches(final ByteOrderMark bom) {
|
||||
// if (bom.length() != fbLength) {
|
||||
// return false;
|
||||
// }
|
||||
// firstBytes may be bigger than the BOM bytes
|
||||
for (int i = 0; i < bom.length(); i++) {
|
||||
if (bom.get(i) != firstBytes[i]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
// Implementation of InputStream
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Invokes the delegate's <code>read()</code> method, detecting and optionally skipping BOM.
|
||||
*
|
||||
* @return the byte read (excluding BOM) or -1 if the end of stream
|
||||
* @throws IOException if an I/O error occurs
|
||||
*/
|
||||
@Override
|
||||
public int read() throws IOException {
|
||||
final int b = readFirstBytes();
|
||||
return b >= 0 ? b : in.read();
|
||||
}
|
||||
|
||||
/**
|
||||
* Invokes the delegate's <code>read(byte[], int, int)</code> method, detecting and optionally skipping BOM.
|
||||
*
|
||||
* @param buf the buffer to read the bytes into
|
||||
* @param off The start offset
|
||||
* @param len The number of bytes to read (excluding BOM)
|
||||
* @return the number of bytes read or -1 if the end of stream
|
||||
* @throws IOException if an I/O error occurs
|
||||
*/
|
||||
@Override
|
||||
public int read(final 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++;
|
||||
}
|
||||
}
|
||||
final int secondCount = in.read(buf, off, len);
|
||||
return secondCount < 0 ? firstCount > 0 ? firstCount : EOF : firstCount + secondCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* Invokes the delegate's <code>read(byte[])</code> method, detecting and optionally skipping BOM.
|
||||
*
|
||||
* @param buf the buffer to read the bytes into
|
||||
* @return the number of bytes read (excluding BOM) or -1 if the end of stream
|
||||
* @throws IOException if an I/O error occurs
|
||||
*/
|
||||
@Override
|
||||
public int read(final byte[] buf) throws IOException {
|
||||
return read(buf, 0, buf.length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Invokes the delegate's <code>mark(int)</code> method.
|
||||
*
|
||||
* @param readlimit read ahead limit
|
||||
*/
|
||||
@Override
|
||||
public synchronized void mark(final int readlimit) {
|
||||
markFbIndex = fbIndex;
|
||||
markedAtStart = firstBytes == null;
|
||||
in.mark(readlimit);
|
||||
}
|
||||
|
||||
/**
|
||||
* Invokes the delegate's <code>reset()</code> method.
|
||||
*
|
||||
* @throws IOException if an I/O error occurs
|
||||
*/
|
||||
@Override
|
||||
public synchronized void reset() throws IOException {
|
||||
fbIndex = markFbIndex;
|
||||
if (markedAtStart) {
|
||||
firstBytes = null;
|
||||
}
|
||||
|
||||
in.reset();
|
||||
}
|
||||
|
||||
/**
|
||||
* Invokes the delegate's <code>skip(long)</code> method, detecting and optionally skipping BOM.
|
||||
*
|
||||
* @param n the number of bytes to skip
|
||||
* @return the number of bytes to skipped or -1 if the end of stream
|
||||
* @throws IOException if an I/O error occurs
|
||||
*/
|
||||
@Override
|
||||
public long skip(final long n) throws IOException {
|
||||
int skipped = 0;
|
||||
while ((n > skipped) && (readFirstBytes() >= 0)) {
|
||||
skipped++;
|
||||
}
|
||||
return in.skip(n - skipped) + skipped;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
package me.ag2s.epublib.util.commons.io;
|
||||
|
||||
/*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* Byte Order Mark (BOM) representation - see {@link BOMInputStream}.
|
||||
*
|
||||
* @see BOMInputStream
|
||||
* @see <a href="http://en.wikipedia.org/wiki/Byte_order_mark">Wikipedia: Byte Order Mark</a>
|
||||
* @see <a href="http://www.w3.org/TR/2006/REC-xml-20060816/#sec-guessing">W3C: Autodetection of Character Encodings
|
||||
* (Non-Normative)</a>
|
||||
* @since 2.0
|
||||
*/
|
||||
public class ByteOrderMark implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* UTF-8 BOM
|
||||
*/
|
||||
public static final ByteOrderMark UTF_8 = new ByteOrderMark("UTF-8", 0xEF, 0xBB, 0xBF);
|
||||
|
||||
/**
|
||||
* UTF-16BE BOM (Big-Endian)
|
||||
*/
|
||||
public static final ByteOrderMark UTF_16BE = new ByteOrderMark("UTF-16BE", 0xFE, 0xFF);
|
||||
|
||||
/**
|
||||
* UTF-16LE BOM (Little-Endian)
|
||||
*/
|
||||
public static final ByteOrderMark UTF_16LE = new ByteOrderMark("UTF-16LE", 0xFF, 0xFE);
|
||||
|
||||
/**
|
||||
* UTF-32BE BOM (Big-Endian)
|
||||
*
|
||||
* @since 2.2
|
||||
*/
|
||||
public static final ByteOrderMark UTF_32BE = new ByteOrderMark("UTF-32BE", 0x00, 0x00, 0xFE, 0xFF);
|
||||
|
||||
/**
|
||||
* UTF-32LE BOM (Little-Endian)
|
||||
*
|
||||
* @since 2.2
|
||||
*/
|
||||
public static final ByteOrderMark UTF_32LE = new ByteOrderMark("UTF-32LE", 0xFF, 0xFE, 0x00, 0x00);
|
||||
|
||||
/**
|
||||
* Unicode BOM character; external form depends on the encoding.
|
||||
*
|
||||
* @see <a href="http://unicode.org/faq/utf_bom.html#BOM">Byte Order Mark (BOM) FAQ</a>
|
||||
* @since 2.5
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
public static final char UTF_BOM = '\uFEFF';
|
||||
|
||||
private final String charsetName;
|
||||
private final int[] bytes;
|
||||
|
||||
/**
|
||||
* Construct a new BOM.
|
||||
*
|
||||
* @param charsetName The name of the charset the BOM represents
|
||||
* @param bytes The BOM's bytes
|
||||
* @throws IllegalArgumentException if the charsetName is null or
|
||||
* zero length
|
||||
* @throws IllegalArgumentException if the bytes are null or zero
|
||||
* length
|
||||
*/
|
||||
public ByteOrderMark(final String charsetName, final int... bytes) {
|
||||
if (charsetName == null || charsetName.isEmpty()) {
|
||||
throw new IllegalArgumentException("No charsetName specified");
|
||||
}
|
||||
if (bytes == null || bytes.length == 0) {
|
||||
throw new IllegalArgumentException("No bytes specified");
|
||||
}
|
||||
this.charsetName = charsetName;
|
||||
this.bytes = new int[bytes.length];
|
||||
System.arraycopy(bytes, 0, this.bytes, 0, bytes.length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the name of the {@link java.nio.charset.Charset} the BOM represents.
|
||||
*
|
||||
* @return the character set name
|
||||
*/
|
||||
public String getCharsetName() {
|
||||
return charsetName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the length of the BOM's bytes.
|
||||
*
|
||||
* @return the length of the BOM's bytes
|
||||
*/
|
||||
public int length() {
|
||||
return bytes.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* The byte at the specified position.
|
||||
*
|
||||
* @param pos The position
|
||||
* @return The specified byte
|
||||
*/
|
||||
public int get(final int pos) {
|
||||
return bytes[pos];
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a copy of the BOM's bytes.
|
||||
*
|
||||
* @return a copy of the BOM's bytes
|
||||
*/
|
||||
public byte[] getBytes() {
|
||||
final byte[] copy = new byte[bytes.length];
|
||||
for (int i = 0; i < bytes.length; i++) {
|
||||
copy[i] = (byte) bytes[i];
|
||||
}
|
||||
return copy;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if this BOM's bytes equals another.
|
||||
*
|
||||
* @param obj The object to compare to
|
||||
* @return true if the bom's bytes are equal, otherwise
|
||||
* false
|
||||
*/
|
||||
@Override
|
||||
public boolean equals(final Object obj) {
|
||||
if (!(obj instanceof ByteOrderMark)) {
|
||||
return false;
|
||||
}
|
||||
final ByteOrderMark bom = (ByteOrderMark) obj;
|
||||
if (bytes.length != bom.length()) {
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < bytes.length; i++) {
|
||||
if (bytes[i] != bom.get(i)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the hashcode for this BOM.
|
||||
*
|
||||
* @return the hashcode for this BOM.
|
||||
* @see java.lang.Object#hashCode()
|
||||
*/
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int hashCode = getClass().hashCode();
|
||||
for (final int b : bytes) {
|
||||
hashCode += b;
|
||||
}
|
||||
return hashCode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Provide a String representation of the BOM.
|
||||
*
|
||||
* @return the length of the BOM's bytes
|
||||
*/
|
||||
@Override
|
||||
@SuppressWarnings("NullableProblems")
|
||||
public String toString() {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
builder.append(getClass().getSimpleName());
|
||||
builder.append('[');
|
||||
builder.append(charsetName);
|
||||
builder.append(": ");
|
||||
for (int i = 0; i < bytes.length; i++) {
|
||||
if (i > 0) {
|
||||
builder.append(",");
|
||||
}
|
||||
builder.append("0x");
|
||||
builder.append(Integer.toHexString(0xFF & bytes[i]).toUpperCase(Locale.ROOT));
|
||||
}
|
||||
builder.append(']');
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF licenses this file to You under the Apache License, Version 2.0
|
||||
* (the "License"); you may not use this file except in compliance with
|
||||
* the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package me.ag2s.epublib.util.commons.io;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* Like {@link Consumer} but throws {@link IOException}.
|
||||
*
|
||||
* @param <T> the type of the input to the operations.
|
||||
* @since 2.7
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface IOConsumer<T> {
|
||||
|
||||
/**
|
||||
* Performs this operation on the given argument.
|
||||
*
|
||||
* @param t the input argument
|
||||
* @throws IOException if an I/O error occurs.
|
||||
*/
|
||||
void accept(T t) throws IOException;
|
||||
|
||||
/**
|
||||
* Returns a composed {@code IoConsumer} that performs, in sequence, this operation followed by the {@code after}
|
||||
* operation. If performing either operation throws an exception, it is relayed to the caller of the composed
|
||||
* operation. If performing this operation throws an exception, the {@code after} operation will not be performed.
|
||||
*
|
||||
* @param after the operation to perform after this operation
|
||||
* @return a composed {@code Consumer} that performs in sequence this operation followed by the {@code after}
|
||||
* operation
|
||||
* @throws NullPointerException if {@code after} is null
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
default IOConsumer<T> andThen(final IOConsumer<? super T> after) {
|
||||
Objects.requireNonNull(after);
|
||||
return (final T t) -> {
|
||||
accept(t);
|
||||
after.accept(t);
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
package me.ag2s.epublib.util.commons.io;
|
||||
|
||||
/*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
|
||||
import static me.ag2s.epublib.util.IOUtil.EOF;
|
||||
|
||||
import java.io.FilterInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
import me.ag2s.epublib.util.IOUtil;
|
||||
|
||||
|
||||
/**
|
||||
* A Proxy stream which acts as expected, that is it passes the method
|
||||
* calls on to the proxied stream and doesn't change which methods are
|
||||
* being called.
|
||||
* <p>
|
||||
* It is an alternative base class to FilterInputStream
|
||||
* to increase reusability, because FilterInputStream changes the
|
||||
* methods being called, such as read(byte[]) to read(byte[], int, int).
|
||||
* </p>
|
||||
* <p>
|
||||
* See the protected methods for ways in which a subclass can easily decorate
|
||||
* a stream with custom pre-, post- or error processing functionality.
|
||||
* </p>
|
||||
*/
|
||||
public abstract class ProxyInputStream extends FilterInputStream {
|
||||
|
||||
/**
|
||||
* Constructs a new ProxyInputStream.
|
||||
*
|
||||
* @param proxy the InputStream to delegate to
|
||||
*/
|
||||
public ProxyInputStream(final InputStream proxy) {
|
||||
super(proxy);
|
||||
// the proxy is stored in a protected superclass variable named 'in'
|
||||
}
|
||||
|
||||
/**
|
||||
* Invokes the delegate's <code>read()</code> method.
|
||||
*
|
||||
* @return the byte read or -1 if the end of stream
|
||||
* @throws IOException if an I/O error occurs
|
||||
*/
|
||||
@Override
|
||||
public int read() throws IOException {
|
||||
try {
|
||||
beforeRead(1);
|
||||
final int b = in.read();
|
||||
afterRead(b != EOF ? 1 : EOF);
|
||||
return b;
|
||||
} catch (final IOException e) {
|
||||
handleIOException(e);
|
||||
return EOF;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Invokes the delegate's <code>read(byte[])</code> method.
|
||||
*
|
||||
* @param bts the buffer to read the bytes into
|
||||
* @return the number of bytes read or EOF if the end of stream
|
||||
* @throws IOException if an I/O error occurs
|
||||
*/
|
||||
@Override
|
||||
public int read(final byte[] bts) throws IOException {
|
||||
try {
|
||||
beforeRead(IOUtil.length(bts));
|
||||
final int n = in.read(bts);
|
||||
afterRead(n);
|
||||
return n;
|
||||
} catch (final IOException e) {
|
||||
handleIOException(e);
|
||||
return EOF;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Invokes the delegate's <code>read(byte[], int, int)</code> method.
|
||||
*
|
||||
* @param bts the buffer to read the bytes into
|
||||
* @param off The start offset
|
||||
* @param len The number of bytes to read
|
||||
* @return the number of bytes read or -1 if the end of stream
|
||||
* @throws IOException if an I/O error occurs
|
||||
*/
|
||||
@Override
|
||||
public int read(final byte[] bts, final int off, final int len) throws IOException {
|
||||
try {
|
||||
beforeRead(len);
|
||||
final int n = in.read(bts, off, len);
|
||||
afterRead(n);
|
||||
return n;
|
||||
} catch (final IOException e) {
|
||||
handleIOException(e);
|
||||
return EOF;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Invokes the delegate's <code>skip(long)</code> method.
|
||||
*
|
||||
* @param ln the number of bytes to skip
|
||||
* @return the actual number of bytes skipped
|
||||
* @throws IOException if an I/O error occurs
|
||||
*/
|
||||
@Override
|
||||
public long skip(final long ln) throws IOException {
|
||||
try {
|
||||
return in.skip(ln);
|
||||
} catch (final IOException e) {
|
||||
handleIOException(e);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Invokes the delegate's <code>available()</code> method.
|
||||
*
|
||||
* @return the number of available bytes
|
||||
* @throws IOException if an I/O error occurs
|
||||
*/
|
||||
@Override
|
||||
public int available() throws IOException {
|
||||
try {
|
||||
return super.available();
|
||||
} catch (final IOException e) {
|
||||
handleIOException(e);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Invokes the delegate's <code>close()</code> method.
|
||||
*
|
||||
* @throws IOException if an I/O error occurs
|
||||
*/
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
IOUtil.close(in, this::handleIOException);
|
||||
}
|
||||
|
||||
/**
|
||||
* Invokes the delegate's <code>mark(int)</code> method.
|
||||
*
|
||||
* @param readlimit read ahead limit
|
||||
*/
|
||||
@Override
|
||||
public synchronized void mark(final int readlimit) {
|
||||
in.mark(readlimit);
|
||||
}
|
||||
|
||||
/**
|
||||
* Invokes the delegate's <code>reset()</code> method.
|
||||
*
|
||||
* @throws IOException if an I/O error occurs
|
||||
*/
|
||||
@Override
|
||||
public synchronized void reset() throws IOException {
|
||||
try {
|
||||
in.reset();
|
||||
} catch (final IOException e) {
|
||||
handleIOException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Invokes the delegate's <code>markSupported()</code> method.
|
||||
*
|
||||
* @return true if mark is supported, otherwise false
|
||||
*/
|
||||
@Override
|
||||
public boolean markSupported() {
|
||||
return in.markSupported();
|
||||
}
|
||||
|
||||
/**
|
||||
* Invoked by the read methods before the call is proxied. The number
|
||||
* of bytes that the caller wanted to read (1 for the {@link #read()}
|
||||
* method, buffer length for {@link #read(byte[])}, etc.) is given as
|
||||
* an argument.
|
||||
* <p>
|
||||
* Subclasses can override this method to add common pre-processing
|
||||
* functionality without having to override all the read methods.
|
||||
* The default implementation does nothing.
|
||||
* <p>
|
||||
* Note this method is <em>not</em> called from {@link #skip(long)} or
|
||||
* {@link #reset()}. You need to explicitly override those methods if
|
||||
* you want to add pre-processing steps also to them.
|
||||
*
|
||||
* @param n number of bytes that the caller asked to be read
|
||||
* @since 2.0
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
|
||||
protected void beforeRead(final int n) {
|
||||
// no-op
|
||||
}
|
||||
|
||||
/**
|
||||
* Invoked by the read methods after the proxied call has returned
|
||||
* successfully. The number of bytes returned to the caller (or -1 if
|
||||
* the end of stream was reached) is given as an argument.
|
||||
* <p>
|
||||
* Subclasses can override this method to add common post-processing
|
||||
* functionality without having to override all the read methods.
|
||||
* The default implementation does nothing.
|
||||
* <p>
|
||||
* Note this method is <em>not</em> called from {@link #skip(long)} or
|
||||
* {@link #reset()}. You need to explicitly override those methods if
|
||||
* you want to add post-processing steps also to them.
|
||||
*
|
||||
* @param n number of bytes read, or -1 if the end of stream was reached
|
||||
* @since 2.0
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
protected void afterRead(final int n) {
|
||||
// no-op
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle any IOExceptions thrown.
|
||||
* <p>
|
||||
* This method provides a point to implement custom exception
|
||||
* handling. The default behavior is to re-throw the exception.
|
||||
*
|
||||
* @param e The IOException thrown
|
||||
* @throws IOException if an I/O error occurs
|
||||
* @since 2.0
|
||||
*/
|
||||
protected void handleIOException(final IOException e) throws IOException {
|
||||
throw e;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,808 @@
|
||||
package me.ag2s.epublib.util.commons.io;
|
||||
|
||||
/*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.Reader;
|
||||
import java.io.StringReader;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
import java.text.MessageFormat;
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import me.ag2s.epublib.util.IOUtil;
|
||||
|
||||
|
||||
/**
|
||||
* Character stream that handles all the necessary Voodoo to figure out the
|
||||
* charset encoding of the XML document within the stream.
|
||||
* <p>
|
||||
* IMPORTANT: This class is not related in any way to the org.xml.sax.XMLReader.
|
||||
* This one IS a character stream.
|
||||
* </p>
|
||||
* <p>
|
||||
* All this has to be done without consuming characters from the stream, if not
|
||||
* the XML parser will not recognized the document as a valid XML. This is not
|
||||
* 100% true, but it's close enough (UTF-8 BOM is not handled by all parsers
|
||||
* right now, XmlStreamReader handles it and things work in all parsers).
|
||||
* </p>
|
||||
* <p>
|
||||
* The XmlStreamReader class handles the charset encoding of XML documents in
|
||||
* Files, raw streams and HTTP streams by offering a wide set of constructors.
|
||||
* </p>
|
||||
* <p>
|
||||
* By default the charset encoding detection is lenient, the constructor with
|
||||
* the lenient flag can be used for a script (following HTTP MIME and XML
|
||||
* specifications). All this is nicely explained by Mark Pilgrim in his blog, <a
|
||||
* href="http://diveintomark.org/archives/2004/02/13/xml-media-types">
|
||||
* Determining the character encoding of a feed</a>.
|
||||
* </p>
|
||||
* <p>
|
||||
* Originally developed for <a href="http://rome.dev.java.net">ROME</a> under
|
||||
* Apache License 2.0.
|
||||
* </p>
|
||||
* <p>
|
||||
* //@seerr XmlStreamWriter
|
||||
*
|
||||
* @since 2.0
|
||||
*/
|
||||
public class XmlStreamReader extends Reader {
|
||||
private static final int BUFFER_SIZE = IOUtil.DEFAULT_BUFFER_SIZE;
|
||||
|
||||
private static final String UTF_8 = "UTF-8";
|
||||
|
||||
private static final String US_ASCII = "US-ASCII";
|
||||
|
||||
private static final String UTF_16BE = "UTF-16BE";
|
||||
|
||||
private static final String UTF_16LE = "UTF-16LE";
|
||||
|
||||
private static final String UTF_32BE = "UTF-32BE";
|
||||
|
||||
private static final String UTF_32LE = "UTF-32LE";
|
||||
|
||||
private static final String UTF_16 = "UTF-16";
|
||||
|
||||
private static final String UTF_32 = "UTF-32";
|
||||
|
||||
private static final String EBCDIC = "CP1047";
|
||||
|
||||
private static final ByteOrderMark[] BOMS = new ByteOrderMark[]{
|
||||
ByteOrderMark.UTF_8,
|
||||
ByteOrderMark.UTF_16BE,
|
||||
ByteOrderMark.UTF_16LE,
|
||||
ByteOrderMark.UTF_32BE,
|
||||
ByteOrderMark.UTF_32LE
|
||||
};
|
||||
|
||||
// UTF_16LE and UTF_32LE have the same two starting BOM bytes.
|
||||
private static final ByteOrderMark[] XML_GUESS_BYTES = new ByteOrderMark[]{
|
||||
new ByteOrderMark(UTF_8, 0x3C, 0x3F, 0x78, 0x6D),
|
||||
new ByteOrderMark(UTF_16BE, 0x00, 0x3C, 0x00, 0x3F),
|
||||
new ByteOrderMark(UTF_16LE, 0x3C, 0x00, 0x3F, 0x00),
|
||||
new ByteOrderMark(UTF_32BE, 0x00, 0x00, 0x00, 0x3C,
|
||||
0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, 0x78, 0x00, 0x00, 0x00, 0x6D),
|
||||
new ByteOrderMark(UTF_32LE, 0x3C, 0x00, 0x00, 0x00,
|
||||
0x3F, 0x00, 0x00, 0x00, 0x78, 0x00, 0x00, 0x00, 0x6D, 0x00, 0x00, 0x00),
|
||||
new ByteOrderMark(EBCDIC, 0x4C, 0x6F, 0xA7, 0x94)
|
||||
};
|
||||
|
||||
private final Reader reader;
|
||||
|
||||
private final String encoding;
|
||||
|
||||
private final String defaultEncoding;
|
||||
|
||||
/**
|
||||
* Returns the default encoding to use if none is set in HTTP content-type,
|
||||
* XML prolog and the rules based on content-type are not adequate.
|
||||
* <p>
|
||||
* If it is NULL the content-type based rules are used.
|
||||
*
|
||||
* @return the default encoding to use.
|
||||
*/
|
||||
public String getDefaultEncoding() {
|
||||
return defaultEncoding;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a Reader for a File.
|
||||
* <p>
|
||||
* It looks for the UTF-8 BOM first, if none sniffs the XML prolog charset,
|
||||
* if this is also missing defaults to UTF-8.
|
||||
* <p>
|
||||
* It does a lenient charset encoding detection, check the constructor with
|
||||
* the lenient parameter for details.
|
||||
*
|
||||
* @param file File to create a Reader from.
|
||||
* @throws IOException thrown if there is a problem reading the file.
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
public XmlStreamReader(final File file) throws IOException {
|
||||
this(new FileInputStream(Objects.requireNonNull(file)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a Reader for a raw InputStream.
|
||||
* <p>
|
||||
* It follows the same logic used for files.
|
||||
* <p>
|
||||
* It does a lenient charset encoding detection, check the constructor with
|
||||
* the lenient parameter for details.
|
||||
*
|
||||
* @param inputStream InputStream to create a Reader from.
|
||||
* @throws IOException thrown if there is a problem reading the stream.
|
||||
*/
|
||||
public XmlStreamReader(final InputStream inputStream) throws IOException {
|
||||
this(inputStream, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a Reader for a raw InputStream.
|
||||
* <p>
|
||||
* It follows the same logic used for files.
|
||||
* <p>
|
||||
* If lenient detection is indicated and the detection above fails as per
|
||||
* specifications it then attempts the following:
|
||||
* <p>
|
||||
* If the content type was 'text/html' it replaces it with 'text/xml' and
|
||||
* tries the detection again.
|
||||
* <p>
|
||||
* Else if the XML prolog had a charset encoding that encoding is used.
|
||||
* <p>
|
||||
* Else if the content type had a charset encoding that encoding is used.
|
||||
* <p>
|
||||
* Else 'UTF-8' is used.
|
||||
* <p>
|
||||
* If lenient detection is indicated an XmlStreamReaderException is never
|
||||
* thrown.
|
||||
*
|
||||
* @param inputStream InputStream to create a Reader from.
|
||||
* @param lenient indicates if the charset encoding detection should be
|
||||
* relaxed.
|
||||
* @throws IOException thrown if there is a problem reading the stream.
|
||||
* @throws XmlStreamReaderException thrown if the charset encoding could not
|
||||
* be determined according to the specs.
|
||||
*/
|
||||
public XmlStreamReader(final InputStream inputStream, final boolean lenient) throws IOException {
|
||||
this(inputStream, lenient, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a Reader for a raw InputStream.
|
||||
* <p>
|
||||
* It follows the same logic used for files.
|
||||
* <p>
|
||||
* If lenient detection is indicated and the detection above fails as per
|
||||
* specifications it then attempts the following:
|
||||
* <p>
|
||||
* If the content type was 'text/html' it replaces it with 'text/xml' and
|
||||
* tries the detection again.
|
||||
* <p>
|
||||
* Else if the XML prolog had a charset encoding that encoding is used.
|
||||
* <p>
|
||||
* Else if the content type had a charset encoding that encoding is used.
|
||||
* <p>
|
||||
* Else 'UTF-8' is used.
|
||||
* <p>
|
||||
* If lenient detection is indicated an XmlStreamReaderException is never
|
||||
* thrown.
|
||||
*
|
||||
* @param inputStream InputStream to create a Reader from.
|
||||
* @param lenient indicates if the charset encoding detection should be
|
||||
* relaxed.
|
||||
* @param defaultEncoding The default encoding
|
||||
* @throws IOException thrown if there is a problem reading the stream.
|
||||
* @throws XmlStreamReaderException thrown if the charset encoding could not
|
||||
* be determined according to the specs.
|
||||
*/
|
||||
public XmlStreamReader(final InputStream inputStream, final boolean lenient, final String defaultEncoding)
|
||||
throws IOException {
|
||||
Objects.requireNonNull(inputStream, "inputStream");
|
||||
this.defaultEncoding = defaultEncoding;
|
||||
final BOMInputStream bom = new BOMInputStream(new BufferedInputStream(inputStream, BUFFER_SIZE), false, BOMS);
|
||||
final BOMInputStream pis = new BOMInputStream(bom, true, XML_GUESS_BYTES);
|
||||
this.encoding = doRawStream(bom, pis, lenient);
|
||||
this.reader = new InputStreamReader(pis, encoding);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a Reader using the InputStream of a URL.
|
||||
* <p>
|
||||
* If the URL is not of type HTTP and there is not 'content-type' header in
|
||||
* the fetched data it uses the same logic used for Files.
|
||||
* <p>
|
||||
* If the URL is a HTTP Url or there is a 'content-type' header in the
|
||||
* fetched data it uses the same logic used for an InputStream with
|
||||
* content-type.
|
||||
* <p>
|
||||
* It does a lenient charset encoding detection, check the constructor with
|
||||
* the lenient parameter for details.
|
||||
*
|
||||
* @param url URL to create a Reader from.
|
||||
* @throws IOException thrown if there is a problem reading the stream of
|
||||
* the URL.
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
public XmlStreamReader(final URL url) throws IOException {
|
||||
this(Objects.requireNonNull(url, "url").openConnection(), null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a Reader using the InputStream of a URLConnection.
|
||||
* <p>
|
||||
* If the URLConnection is not of type HttpURLConnection and there is not
|
||||
* 'content-type' header in the fetched data it uses the same logic used for
|
||||
* files.
|
||||
* <p>
|
||||
* If the URLConnection is a HTTP Url or there is a 'content-type' header in
|
||||
* the fetched data it uses the same logic used for an InputStream with
|
||||
* content-type.
|
||||
* <p>
|
||||
* It does a lenient charset encoding detection, check the constructor with
|
||||
* the lenient parameter for details.
|
||||
*
|
||||
* @param conn URLConnection to create a Reader from.
|
||||
* @param defaultEncoding The default encoding
|
||||
* @throws IOException thrown if there is a problem reading the stream of
|
||||
* the URLConnection.
|
||||
*/
|
||||
public XmlStreamReader(final URLConnection conn, final String defaultEncoding) throws IOException {
|
||||
Objects.requireNonNull(conn, "conm");
|
||||
this.defaultEncoding = defaultEncoding;
|
||||
final boolean lenient = true;
|
||||
final String contentType = conn.getContentType();
|
||||
final InputStream inputStream = conn.getInputStream();
|
||||
final BOMInputStream bom = new BOMInputStream(new BufferedInputStream(inputStream, BUFFER_SIZE), false, BOMS);
|
||||
final BOMInputStream pis = new BOMInputStream(bom, true, XML_GUESS_BYTES);
|
||||
if (conn instanceof HttpURLConnection || contentType != null) {
|
||||
this.encoding = processHttpStream(bom, pis, contentType, lenient);
|
||||
} else {
|
||||
this.encoding = doRawStream(bom, pis, lenient);
|
||||
}
|
||||
this.reader = new InputStreamReader(pis, encoding);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a Reader using an InputStream and the associated content-type
|
||||
* header.
|
||||
* <p>
|
||||
* First it checks if the stream has BOM. If there is not BOM checks the
|
||||
* content-type encoding. If there is not content-type encoding checks the
|
||||
* XML prolog encoding. If there is not XML prolog encoding uses the default
|
||||
* encoding mandated by the content-type MIME type.
|
||||
* <p>
|
||||
* It does a lenient charset encoding detection, check the constructor with
|
||||
* the lenient parameter for details.
|
||||
*
|
||||
* @param inputStream InputStream to create the reader from.
|
||||
* @param httpContentType content-type header to use for the resolution of
|
||||
* the charset encoding.
|
||||
* @throws IOException thrown if there is a problem reading the file.
|
||||
*/
|
||||
public XmlStreamReader(final InputStream inputStream, final String httpContentType)
|
||||
throws IOException {
|
||||
this(inputStream, httpContentType, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a Reader using an InputStream and the associated content-type
|
||||
* header. This constructor is lenient regarding the encoding detection.
|
||||
* <p>
|
||||
* First it checks if the stream has BOM. If there is not BOM checks the
|
||||
* content-type encoding. If there is not content-type encoding checks the
|
||||
* XML prolog encoding. If there is not XML prolog encoding uses the default
|
||||
* encoding mandated by the content-type MIME type.
|
||||
* <p>
|
||||
* If lenient detection is indicated and the detection above fails as per
|
||||
* specifications it then attempts the following:
|
||||
* <p>
|
||||
* If the content type was 'text/html' it replaces it with 'text/xml' and
|
||||
* tries the detection again.
|
||||
* <p>
|
||||
* Else if the XML prolog had a charset encoding that encoding is used.
|
||||
* <p>
|
||||
* Else if the content type had a charset encoding that encoding is used.
|
||||
* <p>
|
||||
* Else 'UTF-8' is used.
|
||||
* <p>
|
||||
* If lenient detection is indicated an XmlStreamReaderException is never
|
||||
* thrown.
|
||||
*
|
||||
* @param inputStream InputStream to create the reader from.
|
||||
* @param httpContentType content-type header to use for the resolution of
|
||||
* the charset encoding.
|
||||
* @param lenient indicates if the charset encoding detection should be
|
||||
* relaxed.
|
||||
* @param defaultEncoding The default encoding
|
||||
* @throws IOException thrown if there is a problem reading the file.
|
||||
* @throws XmlStreamReaderException thrown if the charset encoding could not
|
||||
* be determined according to the specs.
|
||||
*/
|
||||
public XmlStreamReader(final InputStream inputStream, final String httpContentType,
|
||||
final boolean lenient, final String defaultEncoding) throws IOException {
|
||||
Objects.requireNonNull(inputStream, "inputStream");
|
||||
this.defaultEncoding = defaultEncoding;
|
||||
final BOMInputStream bom = new BOMInputStream(new BufferedInputStream(inputStream, BUFFER_SIZE), false, BOMS);
|
||||
final BOMInputStream pis = new BOMInputStream(bom, true, XML_GUESS_BYTES);
|
||||
this.encoding = processHttpStream(bom, pis, httpContentType, lenient);
|
||||
this.reader = new InputStreamReader(pis, encoding);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a Reader using an InputStream and the associated content-type
|
||||
* header. This constructor is lenient regarding the encoding detection.
|
||||
* <p>
|
||||
* First it checks if the stream has BOM. If there is not BOM checks the
|
||||
* content-type encoding. If there is not content-type encoding checks the
|
||||
* XML prolog encoding. If there is not XML prolog encoding uses the default
|
||||
* encoding mandated by the content-type MIME type.
|
||||
* <p>
|
||||
* If lenient detection is indicated and the detection above fails as per
|
||||
* specifications it then attempts the following:
|
||||
* <p>
|
||||
* If the content type was 'text/html' it replaces it with 'text/xml' and
|
||||
* tries the detection again.
|
||||
* <p>
|
||||
* Else if the XML prolog had a charset encoding that encoding is used.
|
||||
* <p>
|
||||
* Else if the content type had a charset encoding that encoding is used.
|
||||
* <p>
|
||||
* Else 'UTF-8' is used.
|
||||
* <p>
|
||||
* If lenient detection is indicated an XmlStreamReaderException is never
|
||||
* thrown.
|
||||
*
|
||||
* @param inputStream InputStream to create the reader from.
|
||||
* @param httpContentType content-type header to use for the resolution of
|
||||
* the charset encoding.
|
||||
* @param lenient indicates if the charset encoding detection should be
|
||||
* relaxed.
|
||||
* @throws IOException thrown if there is a problem reading the file.
|
||||
* @throws XmlStreamReaderException thrown if the charset encoding could not
|
||||
* be determined according to the specs.
|
||||
*/
|
||||
public XmlStreamReader(final InputStream inputStream, final String httpContentType,
|
||||
final boolean lenient) throws IOException {
|
||||
this(inputStream, httpContentType, lenient, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the charset encoding of the XmlStreamReader.
|
||||
*
|
||||
* @return charset encoding.
|
||||
*/
|
||||
public String getEncoding() {
|
||||
return encoding;
|
||||
}
|
||||
|
||||
/**
|
||||
* Invokes the underlying reader's <code>read(char[], int, int)</code> method.
|
||||
*
|
||||
* @param buf the buffer to read the characters into
|
||||
* @param offset The start offset
|
||||
* @param len The number of bytes to read
|
||||
* @return the number of characters read or -1 if the end of stream
|
||||
* @throws IOException if an I/O error occurs
|
||||
*/
|
||||
@Override
|
||||
public int read(final char[] buf, final int offset, final int len) throws IOException {
|
||||
return reader.read(buf, offset, len);
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the XmlStreamReader stream.
|
||||
*
|
||||
* @throws IOException thrown if there was a problem closing the stream.
|
||||
*/
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
reader.close();
|
||||
}
|
||||
|
||||
/**
|
||||
* Process the raw stream.
|
||||
*
|
||||
* @param bom BOMInputStream to detect byte order marks
|
||||
* @param pis BOMInputStream to guess XML encoding
|
||||
* @param lenient indicates if the charset encoding detection should be
|
||||
* relaxed.
|
||||
* @return the encoding to be used
|
||||
* @throws IOException thrown if there is a problem reading the stream.
|
||||
*/
|
||||
private String doRawStream(final BOMInputStream bom, final BOMInputStream pis, final boolean lenient)
|
||||
throws IOException {
|
||||
final String bomEnc = bom.getBOMCharsetName();
|
||||
final String xmlGuessEnc = pis.getBOMCharsetName();
|
||||
final String xmlEnc = getXmlProlog(pis, xmlGuessEnc);
|
||||
try {
|
||||
return calculateRawEncoding(bomEnc, xmlGuessEnc, xmlEnc);
|
||||
} catch (final XmlStreamReaderException ex) {
|
||||
if (lenient) {
|
||||
return doLenientDetection(null, ex);
|
||||
}
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process a HTTP stream.
|
||||
*
|
||||
* @param bom BOMInputStream to detect byte order marks
|
||||
* @param pis BOMInputStream to guess XML encoding
|
||||
* @param httpContentType The HTTP content type
|
||||
* @param lenient indicates if the charset encoding detection should be
|
||||
* relaxed.
|
||||
* @return the encoding to be used
|
||||
* @throws IOException thrown if there is a problem reading the stream.
|
||||
*/
|
||||
private String processHttpStream(final BOMInputStream bom, final BOMInputStream pis, final String httpContentType,
|
||||
final boolean lenient) throws IOException {
|
||||
final String bomEnc = bom.getBOMCharsetName();
|
||||
final String xmlGuessEnc = pis.getBOMCharsetName();
|
||||
final String xmlEnc = getXmlProlog(pis, xmlGuessEnc);
|
||||
try {
|
||||
return calculateHttpEncoding(httpContentType, bomEnc, xmlGuessEnc, xmlEnc, lenient);
|
||||
} catch (final XmlStreamReaderException ex) {
|
||||
if (lenient) {
|
||||
return doLenientDetection(httpContentType, ex);
|
||||
}
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Do lenient detection.
|
||||
*
|
||||
* @param httpContentType content-type header to use for the resolution of
|
||||
* the charset encoding.
|
||||
* @param ex The thrown exception
|
||||
* @return the encoding
|
||||
* @throws IOException thrown if there is a problem reading the stream.
|
||||
*/
|
||||
private String doLenientDetection(String httpContentType,
|
||||
XmlStreamReaderException ex) throws IOException {
|
||||
if (httpContentType != null && httpContentType.startsWith("text/html")) {
|
||||
httpContentType = httpContentType.substring("text/html".length());
|
||||
httpContentType = "text/xml" + httpContentType;
|
||||
try {
|
||||
return calculateHttpEncoding(httpContentType, ex.getBomEncoding(),
|
||||
ex.getXmlGuessEncoding(), ex.getXmlEncoding(), true);
|
||||
} catch (final XmlStreamReaderException ex2) {
|
||||
ex = ex2;
|
||||
}
|
||||
}
|
||||
String encoding = ex.getXmlEncoding();
|
||||
if (encoding == null) {
|
||||
encoding = ex.getContentTypeEncoding();
|
||||
}
|
||||
if (encoding == null) {
|
||||
encoding = defaultEncoding == null ? UTF_8 : defaultEncoding;
|
||||
}
|
||||
return encoding;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate the raw encoding.
|
||||
*
|
||||
* @param bomEnc BOM encoding
|
||||
* @param xmlGuessEnc XML Guess encoding
|
||||
* @param xmlEnc XML encoding
|
||||
* @return the raw encoding
|
||||
* @throws IOException thrown if there is a problem reading the stream.
|
||||
*/
|
||||
String calculateRawEncoding(final String bomEnc, final String xmlGuessEnc,
|
||||
final String xmlEnc) throws IOException {
|
||||
|
||||
// BOM is Null
|
||||
if (bomEnc == null) {
|
||||
if (xmlGuessEnc == null || xmlEnc == null) {
|
||||
return defaultEncoding == null ? UTF_8 : defaultEncoding;
|
||||
}
|
||||
if (xmlEnc.equals(UTF_16) &&
|
||||
(xmlGuessEnc.equals(UTF_16BE) || xmlGuessEnc.equals(UTF_16LE))) {
|
||||
return xmlGuessEnc;
|
||||
}
|
||||
return xmlEnc;
|
||||
}
|
||||
|
||||
// BOM is UTF-8
|
||||
if (bomEnc.equals(UTF_8)) {
|
||||
if (xmlGuessEnc != null && !xmlGuessEnc.equals(UTF_8)) {
|
||||
final String msg = MessageFormat.format(RAW_EX_1, bomEnc, xmlGuessEnc, xmlEnc);
|
||||
throw new XmlStreamReaderException(msg, bomEnc, xmlGuessEnc, xmlEnc);
|
||||
}
|
||||
if (xmlEnc != null && !xmlEnc.equals(UTF_8)) {
|
||||
final String msg = MessageFormat.format(RAW_EX_1, bomEnc, xmlGuessEnc, xmlEnc);
|
||||
throw new XmlStreamReaderException(msg, bomEnc, xmlGuessEnc, xmlEnc);
|
||||
}
|
||||
return bomEnc;
|
||||
}
|
||||
|
||||
// BOM is UTF-16BE or UTF-16LE
|
||||
if (bomEnc.equals(UTF_16BE) || bomEnc.equals(UTF_16LE)) {
|
||||
if (xmlGuessEnc != null && !xmlGuessEnc.equals(bomEnc)) {
|
||||
final String msg = MessageFormat.format(RAW_EX_1, bomEnc, xmlGuessEnc, xmlEnc);
|
||||
throw new XmlStreamReaderException(msg, bomEnc, xmlGuessEnc, xmlEnc);
|
||||
}
|
||||
if (xmlEnc != null && !xmlEnc.equals(UTF_16) && !xmlEnc.equals(bomEnc)) {
|
||||
final String msg = MessageFormat.format(RAW_EX_1, bomEnc, xmlGuessEnc, xmlEnc);
|
||||
throw new XmlStreamReaderException(msg, bomEnc, xmlGuessEnc, xmlEnc);
|
||||
}
|
||||
return bomEnc;
|
||||
}
|
||||
|
||||
// BOM is UTF-32BE or UTF-32LE
|
||||
if (bomEnc.equals(UTF_32BE) || bomEnc.equals(UTF_32LE)) {
|
||||
if (xmlGuessEnc != null && !xmlGuessEnc.equals(bomEnc)) {
|
||||
final String msg = MessageFormat.format(RAW_EX_1, bomEnc, xmlGuessEnc, xmlEnc);
|
||||
throw new XmlStreamReaderException(msg, bomEnc, xmlGuessEnc, xmlEnc);
|
||||
}
|
||||
if (xmlEnc != null && !xmlEnc.equals(UTF_32) && !xmlEnc.equals(bomEnc)) {
|
||||
final String msg = MessageFormat.format(RAW_EX_1, bomEnc, xmlGuessEnc, xmlEnc);
|
||||
throw new XmlStreamReaderException(msg, bomEnc, xmlGuessEnc, xmlEnc);
|
||||
}
|
||||
return bomEnc;
|
||||
}
|
||||
|
||||
// BOM is something else
|
||||
final String msg = MessageFormat.format(RAW_EX_2, bomEnc, xmlGuessEnc, xmlEnc);
|
||||
throw new XmlStreamReaderException(msg, bomEnc, xmlGuessEnc, xmlEnc);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Calculate the HTTP encoding.
|
||||
*
|
||||
* @param httpContentType The HTTP content type
|
||||
* @param bomEnc BOM encoding
|
||||
* @param xmlGuessEnc XML Guess encoding
|
||||
* @param xmlEnc XML encoding
|
||||
* @param lenient indicates if the charset encoding detection should be
|
||||
* relaxed.
|
||||
* @return the HTTP encoding
|
||||
* @throws IOException thrown if there is a problem reading the stream.
|
||||
*/
|
||||
String calculateHttpEncoding(final String httpContentType,
|
||||
final String bomEnc, final String xmlGuessEnc, final String xmlEnc,
|
||||
final boolean lenient) throws IOException {
|
||||
|
||||
// Lenient and has XML encoding
|
||||
if (lenient && xmlEnc != null) {
|
||||
return xmlEnc;
|
||||
}
|
||||
|
||||
// Determine mime/encoding content types from HTTP Content Type
|
||||
final String cTMime = getContentTypeMime(httpContentType);
|
||||
final String cTEnc = getContentTypeEncoding(httpContentType);
|
||||
final boolean appXml = isAppXml(cTMime);
|
||||
final boolean textXml = isTextXml(cTMime);
|
||||
|
||||
// Mime type NOT "application/xml" or "text/xml"
|
||||
if (!appXml && !textXml) {
|
||||
final String msg = MessageFormat.format(HTTP_EX_3, cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc);
|
||||
throw new XmlStreamReaderException(msg, cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc);
|
||||
}
|
||||
|
||||
// No content type encoding
|
||||
if (cTEnc == null) {
|
||||
if (appXml) {
|
||||
return calculateRawEncoding(bomEnc, xmlGuessEnc, xmlEnc);
|
||||
}
|
||||
return defaultEncoding == null ? US_ASCII : defaultEncoding;
|
||||
}
|
||||
|
||||
// UTF-16BE or UTF-16LE content type encoding
|
||||
if (cTEnc.equals(UTF_16BE) || cTEnc.equals(UTF_16LE)) {
|
||||
if (bomEnc != null) {
|
||||
final String msg = MessageFormat.format(HTTP_EX_1, cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc);
|
||||
throw new XmlStreamReaderException(msg, cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc);
|
||||
}
|
||||
return cTEnc;
|
||||
}
|
||||
|
||||
// UTF-16 content type encoding
|
||||
if (cTEnc.equals(UTF_16)) {
|
||||
if (bomEnc != null && bomEnc.startsWith(UTF_16)) {
|
||||
return bomEnc;
|
||||
}
|
||||
final String msg = MessageFormat.format(HTTP_EX_2, cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc);
|
||||
throw new XmlStreamReaderException(msg, cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc);
|
||||
}
|
||||
|
||||
// UTF-32BE or UTF-132E content type encoding
|
||||
if (cTEnc.equals(UTF_32BE) || cTEnc.equals(UTF_32LE)) {
|
||||
if (bomEnc != null) {
|
||||
final String msg = MessageFormat.format(HTTP_EX_1, cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc);
|
||||
throw new XmlStreamReaderException(msg, cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc);
|
||||
}
|
||||
return cTEnc;
|
||||
}
|
||||
|
||||
// UTF-32 content type encoding
|
||||
if (cTEnc.equals(UTF_32)) {
|
||||
if (bomEnc != null && bomEnc.startsWith(UTF_32)) {
|
||||
return bomEnc;
|
||||
}
|
||||
final String msg = MessageFormat.format(HTTP_EX_2, cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc);
|
||||
throw new XmlStreamReaderException(msg, cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc);
|
||||
}
|
||||
|
||||
return cTEnc;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns MIME type or NULL if httpContentType is NULL.
|
||||
*
|
||||
* @param httpContentType the HTTP content type
|
||||
* @return The mime content type
|
||||
*/
|
||||
static String getContentTypeMime(final String httpContentType) {
|
||||
String mime = null;
|
||||
if (httpContentType != null) {
|
||||
final int i = httpContentType.indexOf(";");
|
||||
if (i >= 0) {
|
||||
mime = httpContentType.substring(0, i);
|
||||
} else {
|
||||
mime = httpContentType;
|
||||
}
|
||||
mime = mime.trim();
|
||||
}
|
||||
return mime;
|
||||
}
|
||||
|
||||
private static final Pattern CHARSET_PATTERN = Pattern
|
||||
.compile("charset=[\"']?([.[^; \"']]*)[\"']?");
|
||||
|
||||
/**
|
||||
* Returns charset parameter value, NULL if not present, NULL if
|
||||
* httpContentType is NULL.
|
||||
*
|
||||
* @param httpContentType the HTTP content type
|
||||
* @return The content type encoding (upcased)
|
||||
*/
|
||||
static String getContentTypeEncoding(final String httpContentType) {
|
||||
String encoding = null;
|
||||
if (httpContentType != null) {
|
||||
final int i = httpContentType.indexOf(";");
|
||||
if (i > -1) {
|
||||
final String postMime = httpContentType.substring(i + 1);
|
||||
final Matcher m = CHARSET_PATTERN.matcher(postMime);
|
||||
encoding = m.find() ? m.group(1) : null;
|
||||
encoding = encoding != null ? encoding.toUpperCase(Locale.ROOT) : null;
|
||||
}
|
||||
}
|
||||
return encoding;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pattern capturing the encoding of the "xml" processing instruction.
|
||||
*/
|
||||
public static final Pattern ENCODING_PATTERN = Pattern.compile(
|
||||
"<\\?xml.*encoding[\\s]*=[\\s]*((?:\".[^\"]*\")|(?:'.[^']*'))",
|
||||
Pattern.MULTILINE);
|
||||
|
||||
/**
|
||||
* Returns the encoding declared in the <?xml encoding=...?>, NULL if none.
|
||||
*
|
||||
* @param inputStream InputStream to create the reader from.
|
||||
* @param guessedEnc guessed encoding
|
||||
* @return the encoding declared in the <?xml encoding=...?>
|
||||
* @throws IOException thrown if there is a problem reading the stream.
|
||||
*/
|
||||
private static String getXmlProlog(final InputStream inputStream, final String guessedEnc)
|
||||
throws IOException {
|
||||
String encoding = null;
|
||||
if (guessedEnc != null) {
|
||||
final byte[] bytes = new byte[BUFFER_SIZE];
|
||||
inputStream.mark(BUFFER_SIZE);
|
||||
int offset = 0;
|
||||
int max = BUFFER_SIZE;
|
||||
int c = inputStream.read(bytes, offset, max);
|
||||
int firstGT = -1;
|
||||
String xmlProlog = ""; // avoid possible NPE warning (cannot happen; this just silences the warning)
|
||||
while (c != -1 && firstGT == -1 && offset < BUFFER_SIZE) {
|
||||
offset += c;
|
||||
max -= c;
|
||||
c = inputStream.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");
|
||||
}
|
||||
final int bytesRead = offset;
|
||||
if (bytesRead > 0) {
|
||||
inputStream.reset();
|
||||
final BufferedReader bReader = new BufferedReader(new StringReader(
|
||||
xmlProlog.substring(0, firstGT + 1)));
|
||||
final StringBuffer prolog = new StringBuffer();
|
||||
String line;
|
||||
while ((line = bReader.readLine()) != null) {
|
||||
prolog.append(line);
|
||||
}
|
||||
final Matcher m = ENCODING_PATTERN.matcher(prolog);
|
||||
if (m.find()) {
|
||||
encoding = Objects.requireNonNull(m.group(1)).toUpperCase(Locale.ROOT);
|
||||
encoding = encoding.substring(1, encoding.length() - 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
return encoding;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if the MIME type belongs to the APPLICATION XML family.
|
||||
*
|
||||
* @param mime The mime type
|
||||
* @return true if the mime type belongs to the APPLICATION XML family,
|
||||
* otherwise false
|
||||
*/
|
||||
static boolean isAppXml(final String mime) {
|
||||
return mime != null &&
|
||||
(mime.equals("application/xml") ||
|
||||
mime.equals("application/xml-dtd") ||
|
||||
mime.equals("application/xml-external-parsed-entity") ||
|
||||
mime.startsWith("application/") && mime.endsWith("+xml"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if the MIME type belongs to the TEXT XML family.
|
||||
*
|
||||
* @param mime The mime type
|
||||
* @return true if the mime type belongs to the TEXT XML family,
|
||||
* otherwise false
|
||||
*/
|
||||
static boolean isTextXml(final String mime) {
|
||||
return mime != null &&
|
||||
(mime.equals("text/xml") ||
|
||||
mime.equals("text/xml-external-parsed-entity") ||
|
||||
mime.startsWith("text/") && mime.endsWith("+xml"));
|
||||
}
|
||||
|
||||
private static final String RAW_EX_1 =
|
||||
"Invalid encoding, BOM [{0}] XML guess [{1}] XML prolog [{2}] encoding mismatch";
|
||||
|
||||
private static final String RAW_EX_2 =
|
||||
"Invalid encoding, BOM [{0}] XML guess [{1}] XML prolog [{2}] unknown BOM";
|
||||
|
||||
private static final String HTTP_EX_1 =
|
||||
"Invalid encoding, CT-MIME [{0}] CT-Enc [{1}] BOM [{2}] XML guess [{3}] XML prolog [{4}], BOM must be NULL";
|
||||
|
||||
private static final String HTTP_EX_2 =
|
||||
"Invalid encoding, CT-MIME [{0}] CT-Enc [{1}] BOM [{2}] XML guess [{3}] XML prolog [{4}], encoding mismatch";
|
||||
|
||||
private static final String HTTP_EX_3 =
|
||||
"Invalid encoding, CT-MIME [{0}] CT-Enc [{1}] BOM [{2}] XML guess [{3}] XML prolog [{4}], Invalid MIME";
|
||||
|
||||
}
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
package me.ag2s.epublib.util.commons.io;
|
||||
|
||||
/*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* The XmlStreamReaderException is thrown by the XmlStreamReader constructors if
|
||||
* the charset encoding can not be determined according to the XML 1.0
|
||||
* specification and RFC 3023.
|
||||
* <p>
|
||||
* The exception returns the unconsumed InputStream to allow the application to
|
||||
* do an alternate processing with the stream. Note that the original
|
||||
* InputStream given to the XmlStreamReader cannot be used as that one has been
|
||||
* already read.
|
||||
* </p>
|
||||
*
|
||||
* @since 2.0
|
||||
*/
|
||||
public class XmlStreamReaderException extends IOException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private final String bomEncoding;
|
||||
|
||||
private final String xmlGuessEncoding;
|
||||
|
||||
private final String xmlEncoding;
|
||||
|
||||
private final String contentTypeMime;
|
||||
|
||||
private final String contentTypeEncoding;
|
||||
|
||||
/**
|
||||
* Creates an exception instance if the charset encoding could not be
|
||||
* determined.
|
||||
* <p>
|
||||
* Instances of this exception are thrown by the XmlStreamReader.
|
||||
* </p>
|
||||
*
|
||||
* @param msg message describing the reason for the exception.
|
||||
* @param bomEnc BOM encoding.
|
||||
* @param xmlGuessEnc XML guess encoding.
|
||||
* @param xmlEnc XML prolog encoding.
|
||||
*/
|
||||
public XmlStreamReaderException(final String msg, final String bomEnc,
|
||||
final String xmlGuessEnc, final String xmlEnc) {
|
||||
this(msg, null, null, bomEnc, xmlGuessEnc, xmlEnc);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an exception instance if the charset encoding could not be
|
||||
* determined.
|
||||
* <p>
|
||||
* Instances of this exception are thrown by the XmlStreamReader.
|
||||
* </p>
|
||||
*
|
||||
* @param msg message describing the reason for the exception.
|
||||
* @param ctMime MIME type in the content-type.
|
||||
* @param ctEnc encoding in the content-type.
|
||||
* @param bomEnc BOM encoding.
|
||||
* @param xmlGuessEnc XML guess encoding.
|
||||
* @param xmlEnc XML prolog encoding.
|
||||
*/
|
||||
public XmlStreamReaderException(final String msg, final String ctMime, final String ctEnc,
|
||||
final String bomEnc, final String xmlGuessEnc, final String xmlEnc) {
|
||||
super(msg);
|
||||
contentTypeMime = ctMime;
|
||||
contentTypeEncoding = ctEnc;
|
||||
bomEncoding = bomEnc;
|
||||
xmlGuessEncoding = xmlGuessEnc;
|
||||
xmlEncoding = xmlEnc;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the BOM encoding found in the InputStream.
|
||||
*
|
||||
* @return the BOM encoding, null if none.
|
||||
*/
|
||||
public String getBomEncoding() {
|
||||
return bomEncoding;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the encoding guess based on the first bytes of the InputStream.
|
||||
*
|
||||
* @return the encoding guess, null if it couldn't be guessed.
|
||||
*/
|
||||
public String getXmlGuessEncoding() {
|
||||
return xmlGuessEncoding;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the encoding found in the XML prolog of the InputStream.
|
||||
*
|
||||
* @return the encoding of the XML prolog, null if none.
|
||||
*/
|
||||
public String getXmlEncoding() {
|
||||
return xmlEncoding;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the MIME type in the content-type used to attempt determining the
|
||||
* encoding.
|
||||
*
|
||||
* @return the MIME type in the content-type, null if there was not
|
||||
* content-type or the encoding detection did not involve HTTP.
|
||||
*/
|
||||
public String getContentTypeMime() {
|
||||
return contentTypeMime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the encoding in the content-type used to attempt determining the
|
||||
* encoding.
|
||||
*
|
||||
* @return the encoding in the content-type, null if there was not
|
||||
* content-type, no encoding in it or the encoding detection did not
|
||||
* involve HTTP.
|
||||
*/
|
||||
public String getContentTypeEncoding() {
|
||||
return contentTypeEncoding;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,363 @@
|
||||
|
||||
|
||||
|
||||
package me.ag2s.epublib.util.zip;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
/**
|
||||
* This class represents a member of a zip archive. ZipFile and
|
||||
* ZipInputStream will give you instances of this class as information
|
||||
* about the members in an archive. On the other hand ZipOutputStream
|
||||
* needs an instance of this class to create a new member.
|
||||
*
|
||||
* @author Jochen Hoenicke
|
||||
*/
|
||||
public class AndroidZipEntry implements ZipConstants, Cloneable {
|
||||
private static final int KNOWN_SIZE = 1;
|
||||
private static final int KNOWN_CSIZE = 2;
|
||||
private static final int KNOWN_CRC = 4;
|
||||
private static final int KNOWN_TIME = 8;
|
||||
|
||||
private static Calendar cal;
|
||||
|
||||
private final String name;
|
||||
private final int nameLen;
|
||||
private int size;
|
||||
private int compressedSize;
|
||||
private int crc;
|
||||
private int dostime;
|
||||
private short known = 0;
|
||||
private short method = -1;
|
||||
private byte[] extra = null;
|
||||
private String comment = null;
|
||||
|
||||
int flags; /* used by ZipOutputStream */
|
||||
int offset; /* used by ZipFile and ZipOutputStream */
|
||||
|
||||
|
||||
/**
|
||||
* Compression method. This method doesn't compress at all.
|
||||
*/
|
||||
public final static int STORED = 0;
|
||||
/**
|
||||
* Compression method. This method uses the Deflater.
|
||||
*/
|
||||
public final static int DEFLATED = 8;
|
||||
|
||||
/**
|
||||
* Creates a zip entry with the given name.
|
||||
*
|
||||
* @param name the name. May include directory components separated
|
||||
* by '/'.
|
||||
* @throws NullPointerException when name is null.
|
||||
* @throws IllegalArgumentException when name is bigger then 65535 chars.
|
||||
*/
|
||||
public AndroidZipEntry(String name, int nameLen) {
|
||||
//int length = name.length();
|
||||
this.nameLen = nameLen;
|
||||
if (nameLen > 65535)
|
||||
throw new IllegalArgumentException("name length is " + nameLen);
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Creates a copy of the given zip entry.
|
||||
*
|
||||
* @param e the entry to copy.
|
||||
*/
|
||||
public AndroidZipEntry(AndroidZipEntry e) {
|
||||
name = e.name;
|
||||
nameLen = e.nameLen;
|
||||
known = e.known;
|
||||
size = e.size;
|
||||
compressedSize = e.compressedSize;
|
||||
crc = e.crc;
|
||||
dostime = e.dostime;
|
||||
method = e.method;
|
||||
extra = e.extra;
|
||||
comment = e.comment;
|
||||
}
|
||||
|
||||
final void setDOSTime(int dostime) {
|
||||
this.dostime = dostime;
|
||||
known |= KNOWN_TIME;
|
||||
}
|
||||
|
||||
final int getDOSTime() {
|
||||
if ((known & KNOWN_TIME) == 0)
|
||||
return 0;
|
||||
else
|
||||
return dostime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a copy of this zip entry.
|
||||
*/
|
||||
/**
|
||||
* Clones the entry.
|
||||
*/
|
||||
public Object clone() {
|
||||
try {
|
||||
// The JCL says that the `extra' field is also copied.
|
||||
AndroidZipEntry clone = (AndroidZipEntry) super.clone();
|
||||
if (extra != null)
|
||||
clone.extra = extra.clone();
|
||||
return clone;
|
||||
} catch (CloneNotSupportedException ex) {
|
||||
throw new InternalError();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the entry name. The path components in the entry are
|
||||
* always separated by slashes ('/').
|
||||
*/
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public int getNameLen() {
|
||||
return nameLen;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the time of last modification of the entry.
|
||||
*
|
||||
* @time the time of last modification of the entry.
|
||||
*/
|
||||
public void setTime(long time) {
|
||||
Calendar cal = getCalendar();
|
||||
synchronized (cal) {
|
||||
cal.setTime(new Date(time * 1000L));
|
||||
dostime = (cal.get(Calendar.YEAR) - 1980 & 0x7f) << 25
|
||||
| (cal.get(Calendar.MONTH) + 1) << 21
|
||||
| (cal.get(Calendar.DAY_OF_MONTH)) << 16
|
||||
| (cal.get(Calendar.HOUR_OF_DAY)) << 11
|
||||
| (cal.get(Calendar.MINUTE)) << 5
|
||||
| (cal.get(Calendar.SECOND)) >> 1;
|
||||
}
|
||||
dostime = (int) (dostime / 1000L);
|
||||
this.known |= KNOWN_TIME;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the time of last modification of the entry.
|
||||
*
|
||||
* @return the time of last modification of the entry, or -1 if unknown.
|
||||
*/
|
||||
public long getTime() {
|
||||
if ((known & KNOWN_TIME) == 0)
|
||||
return -1;
|
||||
|
||||
int sec = 2 * (dostime & 0x1f);
|
||||
int min = (dostime >> 5) & 0x3f;
|
||||
int hrs = (dostime >> 11) & 0x1f;
|
||||
int day = (dostime >> 16) & 0x1f;
|
||||
int mon = ((dostime >> 21) & 0xf) - 1;
|
||||
int year = ((dostime >> 25) & 0x7f) + 1980; /* since 1900 */
|
||||
|
||||
try {
|
||||
cal = getCalendar();
|
||||
synchronized (cal) {
|
||||
cal.set(year, mon, day, hrs, min, sec);
|
||||
return cal.getTime().getTime();
|
||||
}
|
||||
} catch (RuntimeException ex) {
|
||||
/* Ignore illegal time stamp */
|
||||
known &= ~KNOWN_TIME;
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
private static synchronized Calendar getCalendar() {
|
||||
if (cal == null)
|
||||
cal = Calendar.getInstance();
|
||||
|
||||
return cal;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the size of the uncompressed data.
|
||||
*
|
||||
* @throws IllegalArgumentException if size is not in 0..0xffffffffL
|
||||
*/
|
||||
public void setSize(long size) {
|
||||
if ((size & 0xffffffff00000000L) != 0)
|
||||
throw new IllegalArgumentException();
|
||||
this.size = (int) size;
|
||||
this.known |= KNOWN_SIZE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the size of the uncompressed data.
|
||||
*
|
||||
* @return the size or -1 if unknown.
|
||||
*/
|
||||
public long getSize() {
|
||||
return (known & KNOWN_SIZE) != 0 ? size & 0xffffffffL : -1L;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the size of the compressed data.
|
||||
*
|
||||
* @throws IllegalArgumentException if size is not in 0..0xffffffffL
|
||||
*/
|
||||
public void setCompressedSize(long csize) {
|
||||
if ((csize & 0xffffffff00000000L) != 0)
|
||||
throw new IllegalArgumentException();
|
||||
this.compressedSize = (int) csize;
|
||||
this.known |= KNOWN_CSIZE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the size of the compressed data.
|
||||
*
|
||||
* @return the size or -1 if unknown.
|
||||
*/
|
||||
public long getCompressedSize() {
|
||||
return (known & KNOWN_CSIZE) != 0 ? compressedSize & 0xffffffffL : -1L;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the crc of the uncompressed data.
|
||||
*
|
||||
* @throws IllegalArgumentException if crc is not in 0..0xffffffffL
|
||||
*/
|
||||
public void setCrc(long crc) {
|
||||
if ((crc & 0xffffffff00000000L) != 0)
|
||||
throw new IllegalArgumentException();
|
||||
this.crc = (int) crc;
|
||||
this.known |= KNOWN_CRC;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the crc of the uncompressed data.
|
||||
*
|
||||
* @return the crc or -1 if unknown.
|
||||
*/
|
||||
public long getCrc() {
|
||||
return (known & KNOWN_CRC) != 0 ? crc & 0xffffffffL : -1L;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the compression method. Only DEFLATED and STORED are
|
||||
* supported.
|
||||
*
|
||||
* @throws IllegalArgumentException if method is not supported.
|
||||
* @see ZipOutputStream#DEFLATED
|
||||
* @see ZipOutputStream#STORED
|
||||
*/
|
||||
public void setMethod(int method) {
|
||||
if (method != ZipOutputStream.STORED
|
||||
&& method != ZipOutputStream.DEFLATED)
|
||||
throw new IllegalArgumentException();
|
||||
this.method = (short) method;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the compression method.
|
||||
*
|
||||
* @return the compression method or -1 if unknown.
|
||||
*/
|
||||
public int getMethod() {
|
||||
return method;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the extra data.
|
||||
*
|
||||
* @throws IllegalArgumentException if extra is longer than 0xffff bytes.
|
||||
*/
|
||||
public void setExtra(byte[] extra) {
|
||||
if (extra == null) {
|
||||
this.extra = null;
|
||||
return;
|
||||
}
|
||||
|
||||
if (extra.length > 0xffff)
|
||||
throw new IllegalArgumentException();
|
||||
this.extra = extra;
|
||||
try {
|
||||
int pos = 0;
|
||||
while (pos < extra.length) {
|
||||
int sig = (extra[pos++] & 0xff)
|
||||
| (extra[pos++] & 0xff) << 8;
|
||||
int len = (extra[pos++] & 0xff)
|
||||
| (extra[pos++] & 0xff) << 8;
|
||||
if (sig == 0x5455) {
|
||||
/* extended time stamp */
|
||||
int flags = extra[pos];
|
||||
if ((flags & 1) != 0) {
|
||||
long time = ((extra[pos + 1] & 0xff)
|
||||
| (extra[pos + 2] & 0xff) << 8
|
||||
| (extra[pos + 3] & 0xff) << 16
|
||||
| (extra[pos + 4] & 0xff) << 24);
|
||||
setTime(time);
|
||||
}
|
||||
}
|
||||
pos += len;
|
||||
}
|
||||
} catch (ArrayIndexOutOfBoundsException ex) {
|
||||
/* be lenient */
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the extra data.
|
||||
*
|
||||
* @return the extra data or null if not set.
|
||||
*/
|
||||
public byte[] getExtra() {
|
||||
return extra;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the entry comment.
|
||||
*
|
||||
* @throws IllegalArgumentException if comment is longer than 0xffff.
|
||||
*/
|
||||
public void setComment(String comment) {
|
||||
if (comment != null && comment.length() > 0xffff)
|
||||
throw new IllegalArgumentException();
|
||||
this.comment = comment;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the comment.
|
||||
*
|
||||
* @return the comment or null if not set.
|
||||
*/
|
||||
public String getComment() {
|
||||
return comment;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets true, if the entry is a directory. This is solely
|
||||
* determined by the name, a trailing slash '/' marks a directory.
|
||||
*/
|
||||
public boolean isDirectory() {
|
||||
int nlen = name.length();
|
||||
return nlen > 0 && name.charAt(nlen - 1) == '/';
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the string representation of this AndroidZipEntry. This is just
|
||||
* the name as returned by getName().
|
||||
*/
|
||||
public String toString() {
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the hashCode of this AndroidZipEntry. This is just the hashCode
|
||||
* of the name. Note that the equals method isn't changed, though.
|
||||
*/
|
||||
public int hashCode() {
|
||||
return name.hashCode();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,490 @@
|
||||
|
||||
|
||||
package me.ag2s.epublib.util.zip;
|
||||
|
||||
import static me.ag2s.base.PfdHelper.seek;
|
||||
|
||||
import android.os.ParcelFileDescriptor;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.DataInput;
|
||||
import java.io.EOFException;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.zip.Inflater;
|
||||
import java.util.zip.InflaterInputStream;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
import me.ag2s.base.PfdHelper;
|
||||
|
||||
/**
|
||||
* This class represents a Zip archive. You can ask for the contained
|
||||
* entries, or get an input stream for a file entry. The entry is
|
||||
* automatically decompressed.
|
||||
* <p>
|
||||
* This class is thread safe: You can open input streams for arbitrary
|
||||
* entries in different threads.
|
||||
*
|
||||
* @author Jochen Hoenicke
|
||||
* @author Artur Biesiadowski
|
||||
*/
|
||||
public class AndroidZipFile implements ZipConstants {
|
||||
|
||||
/**
|
||||
* Mode flag to open a zip file for reading.
|
||||
*/
|
||||
public static final int OPEN_READ = 0x1;
|
||||
|
||||
/**
|
||||
* Mode flag to delete a zip file after reading.
|
||||
*/
|
||||
public static final int OPEN_DELETE = 0x4;
|
||||
|
||||
// Name of this zip file.
|
||||
private final String name;
|
||||
|
||||
// File from which zip entries are read.
|
||||
//private final RandomAccessFile raf;
|
||||
|
||||
private final ParcelFileDescriptor pfd;
|
||||
|
||||
// The entries of this zip file when initialized and not yet closed.
|
||||
private HashMap<String, AndroidZipEntry> entries;
|
||||
|
||||
private boolean closed = false;
|
||||
|
||||
/**
|
||||
* Opens a Zip file with the given name for reading.
|
||||
*
|
||||
* @throws IOException if a i/o error occured.
|
||||
* @throws ZipException if the file doesn't contain a valid zip
|
||||
* archive.
|
||||
*/
|
||||
public AndroidZipFile(@NonNull ParcelFileDescriptor pfd, String name) throws ZipException, IOException {
|
||||
this.pfd = pfd;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens a Zip file reading the given File.
|
||||
*
|
||||
* @throws IOException if a i/o error occured.
|
||||
* @throws ZipException if the file doesn't contain a valid zip
|
||||
* archive.
|
||||
*/
|
||||
public AndroidZipFile(File file) throws ZipException, IOException {
|
||||
this.pfd = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
|
||||
this.name = file.getPath();
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens a Zip file reading the given File in the given mode.
|
||||
* <p>
|
||||
* If the OPEN_DELETE mode is specified, the zip file will be deleted at
|
||||
* some time moment after it is opened. It will be deleted before the zip
|
||||
* file is closed or the Virtual Machine exits.
|
||||
* <p>
|
||||
* The contents of the zip file will be accessible until it is closed.
|
||||
* <p>
|
||||
* The OPEN_DELETE mode is currently unimplemented in this library
|
||||
*
|
||||
* @param mode Must be one of OPEN_READ or OPEN_READ | OPEN_DELETE
|
||||
* @throws IOException if a i/o error occured.
|
||||
* @throws ZipException if the file doesn't contain a valid zip
|
||||
* archive.
|
||||
* @since JDK1.3
|
||||
*/
|
||||
// public AndroidZipFile(File file, int mode) throws ZipException, IOException {
|
||||
// if ((mode & OPEN_DELETE) != 0) {
|
||||
// throw new IllegalArgumentException
|
||||
// ("OPEN_DELETE mode not supported yet in net.sf.jazzlib.AndroidZipFile");
|
||||
// }
|
||||
// this.raf = new RandomAccessFile(file, "r");
|
||||
// this.name = file.getPath();
|
||||
// }
|
||||
|
||||
/**
|
||||
* Read an unsigned short in little endian byte order from the given
|
||||
* DataInput stream using the given byte buffer.
|
||||
*
|
||||
* @param di DataInput stream to read from.
|
||||
* @param b the byte buffer to read in (must be at least 2 bytes long).
|
||||
* @return The value read.
|
||||
* @throws IOException if a i/o error occured.
|
||||
* @throws EOFException if the file ends prematurely
|
||||
*/
|
||||
private final int readLeShort(DataInput di, byte[] b) throws IOException {
|
||||
di.readFully(b, 0, 2);
|
||||
return (b[0] & 0xff) | (b[1] & 0xff) << 8;
|
||||
}
|
||||
|
||||
private final int readLeShort(ParcelFileDescriptor pfd, byte[] b) throws IOException {
|
||||
PfdHelper.readFully(pfd, b, 0, 2);//di.readFully(b, 0, 2);
|
||||
return (b[0] & 0xff) | (b[1] & 0xff) << 8;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read an int in little endian byte order from the given
|
||||
* DataInput stream using the given byte buffer.
|
||||
*
|
||||
* @param di DataInput stream to read from.
|
||||
* @param b the byte buffer to read in (must be at least 4 bytes long).
|
||||
* @return The value read.
|
||||
* @throws IOException if a i/o error occured.
|
||||
* @throws EOFException if the file ends prematurely
|
||||
*/
|
||||
private final int readLeInt(DataInput di, byte[] b) throws IOException {
|
||||
di.readFully(b, 0, 4);
|
||||
return ((b[0] & 0xff) | (b[1] & 0xff) << 8)
|
||||
| ((b[2] & 0xff) | (b[3] & 0xff) << 8) << 16;
|
||||
}
|
||||
|
||||
private final int readLeInt(ParcelFileDescriptor pfd, byte[] b) throws IOException {
|
||||
PfdHelper.readFully(pfd, b, 0, 4);//di.readFully(b, 0, 4);
|
||||
return ((b[0] & 0xff) | (b[1] & 0xff) << 8)
|
||||
| ((b[2] & 0xff) | (b[3] & 0xff) << 8) << 16;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Read an unsigned short in little endian byte order from the given
|
||||
* byte buffer at the given offset.
|
||||
*
|
||||
* @param b the byte array to read from.
|
||||
* @param off the offset to read from.
|
||||
* @return The value read.
|
||||
*/
|
||||
private final int readLeShort(byte[] b, int off) {
|
||||
return (b[off] & 0xff) | (b[off + 1] & 0xff) << 8;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read an int in little endian byte order from the given
|
||||
* byte buffer at the given offset.
|
||||
*
|
||||
* @param b the byte array to read from.
|
||||
* @param off the offset to read from.
|
||||
* @return The value read.
|
||||
*/
|
||||
private final int readLeInt(byte[] b, int off) {
|
||||
return ((b[off] & 0xff) | (b[off + 1] & 0xff) << 8)
|
||||
| ((b[off + 2] & 0xff) | (b[off + 3] & 0xff) << 8) << 16;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Read the central directory of a zip file and fill the entries
|
||||
* array. This is called exactly once when first needed. It is called
|
||||
* while holding the lock on <code>raf</code>.
|
||||
*
|
||||
* @throws IOException if a i/o error occured.
|
||||
* @throws ZipException if the central directory is malformed
|
||||
*/
|
||||
private void readEntries() throws ZipException, IOException {
|
||||
/* Search for the End Of Central Directory. When a zip comment is
|
||||
* present the directory may start earlier.
|
||||
* FIXME: This searches the whole file in a very slow manner if the
|
||||
* file isn't a zip file.
|
||||
*/
|
||||
//long pos = raf.length() - ENDHDR;
|
||||
long pos = PfdHelper.length(pfd) - ENDHDR;
|
||||
byte[] ebs = new byte[CENHDR];
|
||||
|
||||
do {
|
||||
if (pos < 0)
|
||||
throw new ZipException
|
||||
("central directory not found, probably not a zip file: " + name);
|
||||
//raf.seek(pos--);
|
||||
seek(pfd, pos--);
|
||||
}
|
||||
//while (readLeInt(raf, ebs) != ENDSIG);
|
||||
while (readLeInt(pfd, ebs) != ENDSIG);
|
||||
|
||||
if (PfdHelper.skipBytes(pfd, ENDTOT - ENDNRD) != ENDTOT - ENDNRD)
|
||||
throw new EOFException(name);
|
||||
//int count = readLeShort(raf, ebs);
|
||||
int count = readLeShort(pfd, ebs);
|
||||
if (PfdHelper.skipBytes(pfd, ENDOFF - ENDSIZ) != ENDOFF - ENDSIZ)
|
||||
throw new EOFException(name);
|
||||
int centralOffset = readLeInt(pfd, ebs);
|
||||
|
||||
entries = new HashMap<>(count + count / 2);
|
||||
//raf.seek(centralOffset);
|
||||
seek(pfd, centralOffset);
|
||||
|
||||
byte[] buffer = new byte[16];
|
||||
for (int i = 0; i < count; i++) {
|
||||
//raf.readFully(ebs);
|
||||
PfdHelper.readFully(pfd, ebs);
|
||||
if (readLeInt(ebs, 0) != CENSIG)
|
||||
throw new ZipException("Wrong Central Directory signature: " + name);
|
||||
|
||||
int method = readLeShort(ebs, CENHOW);
|
||||
int dostime = readLeInt(ebs, CENTIM);
|
||||
int crc = readLeInt(ebs, CENCRC);
|
||||
int csize = readLeInt(ebs, CENSIZ);
|
||||
int size = readLeInt(ebs, CENLEN);
|
||||
int nameLen = readLeShort(ebs, CENNAM);
|
||||
int extraLen = readLeShort(ebs, CENEXT);
|
||||
int commentLen = readLeShort(ebs, CENCOM);
|
||||
|
||||
int offset = readLeInt(ebs, CENOFF);
|
||||
|
||||
int needBuffer = Math.max(nameLen, commentLen);
|
||||
if (buffer.length < needBuffer)
|
||||
buffer = new byte[needBuffer];
|
||||
|
||||
PfdHelper.readFully(pfd, buffer, 0, nameLen);
|
||||
String name = new String(buffer, 0, nameLen);
|
||||
|
||||
AndroidZipEntry entry = new AndroidZipEntry(name, nameLen);
|
||||
entry.setMethod(method);
|
||||
entry.setCrc(crc & 0xffffffffL);
|
||||
entry.setSize(size & 0xffffffffL);
|
||||
entry.setCompressedSize(csize & 0xffffffffL);
|
||||
entry.setTime(dostime);
|
||||
if (extraLen > 0) {
|
||||
byte[] extra = new byte[extraLen];
|
||||
PfdHelper.readFully(pfd, extra);
|
||||
entry.setExtra(extra);
|
||||
}
|
||||
if (commentLen > 0) {
|
||||
PfdHelper.readFully(pfd, buffer, 0, commentLen);
|
||||
entry.setComment(new String(buffer, 0, commentLen));
|
||||
}
|
||||
entry.offset = offset;
|
||||
//ZipEntryHelper.setOffset(entry,offset);
|
||||
|
||||
//entry. = offset;
|
||||
entries.put(name, entry);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the AndroidZipFile. This also closes all input streams given by
|
||||
* this class. After this is called, no further method should be
|
||||
* called.
|
||||
*
|
||||
* @throws IOException if a i/o error occured.
|
||||
*/
|
||||
public void close() throws IOException {
|
||||
synchronized (pfd) {
|
||||
closed = true;
|
||||
entries = null;
|
||||
pfd.close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls the <code>close()</code> method when this AndroidZipFile has not yet
|
||||
* been explicitly closed.
|
||||
*/
|
||||
protected void finalize() throws IOException {
|
||||
if (!closed && pfd != null) close();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an enumeration of all Zip entries in this Zip file.
|
||||
*/
|
||||
public Enumeration<AndroidZipEntry> entries() {
|
||||
try {
|
||||
return new ZipEntryEnumeration(getEntries().values().iterator());
|
||||
} catch (IOException ioe) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks that the AndroidZipFile is still open and reads entries when necessary.
|
||||
*
|
||||
* @throws IllegalStateException when the AndroidZipFile has already been closed.
|
||||
* @throws java, IOEexception when the entries could not be read.
|
||||
*/
|
||||
private HashMap<String, AndroidZipEntry> getEntries() throws IOException {
|
||||
synchronized (pfd) {
|
||||
if (closed)
|
||||
throw new IllegalStateException("AndroidZipFile has closed: " + name);
|
||||
|
||||
if (entries == null)
|
||||
readEntries();
|
||||
|
||||
return entries;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Searches for a zip entry in this archive with the given name.
|
||||
*
|
||||
* @param name name. May contain directory components separated by
|
||||
* slashes ('/').
|
||||
* @return the zip entry, or null if no entry with that name exists.
|
||||
*/
|
||||
public AndroidZipEntry getEntry(String name) {
|
||||
try {
|
||||
HashMap<String, AndroidZipEntry> entries = getEntries();
|
||||
AndroidZipEntry entry = entries.get(name);
|
||||
return entry != null ? (AndroidZipEntry) entry.clone() : null;
|
||||
} catch (IOException ioe) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//access should be protected by synchronized(raf)
|
||||
private final byte[] locBuf = new byte[LOCHDR];
|
||||
|
||||
/**
|
||||
* Checks, if the local header of the entry at index i matches the
|
||||
* central directory, and returns the offset to the data.
|
||||
*
|
||||
* @param entry to check.
|
||||
* @return the start offset of the (compressed) data.
|
||||
* @throws IOException if a i/o error occured.
|
||||
* @throws ZipException if the local header doesn't match the
|
||||
* central directory header
|
||||
*/
|
||||
private long checkLocalHeader(AndroidZipEntry entry) throws IOException {
|
||||
synchronized (pfd) {
|
||||
seek(pfd, entry.offset);
|
||||
PfdHelper.readFully(pfd, locBuf);
|
||||
|
||||
if (readLeInt(locBuf, 0) != LOCSIG)
|
||||
throw new ZipException("Wrong Local header signature: " + name);
|
||||
|
||||
if (entry.getMethod() != readLeShort(locBuf, LOCHOW))
|
||||
throw new ZipException("Compression method mismatch: " + name);
|
||||
|
||||
if (entry.getNameLen() != readLeShort(locBuf, LOCNAM))
|
||||
throw new ZipException("file name length mismatch: " + name);
|
||||
|
||||
int extraLen = entry.getNameLen() + readLeShort(locBuf, LOCEXT);
|
||||
return entry.offset + LOCHDR + extraLen;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an input stream reading the given zip entry as
|
||||
* uncompressed data. Normally zip entry should be an entry
|
||||
* returned by getEntry() or entries().
|
||||
*
|
||||
* @param entry the entry to create an InputStream for.
|
||||
* @return the input stream.
|
||||
* @throws IOException if a i/o error occured.
|
||||
* @throws ZipException if the Zip archive is malformed.
|
||||
*/
|
||||
public InputStream getInputStream(AndroidZipEntry entry) throws IOException {
|
||||
HashMap<String, AndroidZipEntry> entries = getEntries();
|
||||
String name = entry.getName();
|
||||
AndroidZipEntry zipEntry = entries.get(name);
|
||||
if (zipEntry == null)
|
||||
throw new NoSuchElementException(name);
|
||||
|
||||
long start = checkLocalHeader(zipEntry);
|
||||
int method = zipEntry.getMethod();
|
||||
InputStream is = new BufferedInputStream(new PartialInputStream
|
||||
(pfd, start, zipEntry.getCompressedSize()));
|
||||
switch (method) {
|
||||
case ZipOutputStream.STORED:
|
||||
return is;
|
||||
case ZipOutputStream.DEFLATED:
|
||||
return new InflaterInputStream(is, new Inflater(true));
|
||||
default:
|
||||
throw new ZipException("Unknown compression method " + method);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the (path) name of this zip file.
|
||||
*/
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of entries in this zip file.
|
||||
*/
|
||||
public int size() {
|
||||
try {
|
||||
return getEntries().size();
|
||||
} catch (IOException ioe) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
private static class ZipEntryEnumeration implements Enumeration<AndroidZipEntry> {
|
||||
private final Iterator<AndroidZipEntry> elements;
|
||||
|
||||
public ZipEntryEnumeration(Iterator<AndroidZipEntry> elements) {
|
||||
this.elements = elements;
|
||||
}
|
||||
|
||||
public boolean hasMoreElements() {
|
||||
return elements.hasNext();
|
||||
}
|
||||
|
||||
public AndroidZipEntry nextElement() {
|
||||
/* We return a clone, just to be safe that the user doesn't
|
||||
* change the entry.
|
||||
*/
|
||||
return (AndroidZipEntry) (elements.next()).clone();
|
||||
}
|
||||
}
|
||||
|
||||
private static class PartialInputStream extends InputStream {
|
||||
private final ParcelFileDescriptor pfd;
|
||||
long filepos, end;
|
||||
|
||||
public PartialInputStream(ParcelFileDescriptor pfd, long start, long len) {
|
||||
this.pfd = pfd;
|
||||
filepos = start;
|
||||
end = start + len;
|
||||
}
|
||||
|
||||
public int available() {
|
||||
long amount = end - filepos;
|
||||
if (amount > Integer.MAX_VALUE)
|
||||
return Integer.MAX_VALUE;
|
||||
return (int) amount;
|
||||
}
|
||||
|
||||
public int read() throws IOException {
|
||||
if (filepos == end)
|
||||
return -1;
|
||||
synchronized (pfd) {
|
||||
seek(pfd, filepos++);
|
||||
return PfdHelper.read(pfd);
|
||||
}
|
||||
}
|
||||
|
||||
public int read(byte[] b, int off, int len) throws IOException {
|
||||
if (len > end - filepos) {
|
||||
len = (int) (end - filepos);
|
||||
if (len == 0)
|
||||
return -1;
|
||||
}
|
||||
synchronized (pfd) {
|
||||
seek(pfd, filepos);
|
||||
int count = PfdHelper.read(pfd, b, off, len);
|
||||
if (count > 0)
|
||||
filepos += len;
|
||||
return count;
|
||||
}
|
||||
}
|
||||
|
||||
public long skip(long amount) {
|
||||
if (amount < 0)
|
||||
throw new IllegalArgumentException();
|
||||
if (amount > end - filepos)
|
||||
amount = end - filepos;
|
||||
filepos += amount;
|
||||
return amount;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
|
||||
|
||||
package me.ag2s.epublib.util.zip;
|
||||
|
||||
interface ZipConstants {
|
||||
/* The local file header */
|
||||
int LOCHDR = 30;
|
||||
int LOCSIG = 'P' | ('K' << 8) | (3 << 16) | (4 << 24);
|
||||
|
||||
int LOCVER = 4;
|
||||
int LOCFLG = 6;
|
||||
int LOCHOW = 8;
|
||||
int LOCTIM = 10;
|
||||
int LOCCRC = 14;
|
||||
int LOCSIZ = 18;
|
||||
int LOCLEN = 22;
|
||||
int LOCNAM = 26;
|
||||
int LOCEXT = 28;
|
||||
|
||||
/* The Data descriptor */
|
||||
int EXTSIG = 'P' | ('K' << 8) | (7 << 16) | (8 << 24);
|
||||
int EXTHDR = 16;
|
||||
|
||||
int EXTCRC = 4;
|
||||
int EXTSIZ = 8;
|
||||
int EXTLEN = 12;
|
||||
|
||||
/* The central directory file header */
|
||||
int CENSIG = 'P' | ('K' << 8) | (1 << 16) | (2 << 24);
|
||||
int CENHDR = 46;
|
||||
|
||||
int CENVEM = 4;
|
||||
int CENVER = 6;
|
||||
int CENFLG = 8;
|
||||
int CENHOW = 10;
|
||||
int CENTIM = 12;
|
||||
int CENCRC = 16;
|
||||
int CENSIZ = 20;
|
||||
int CENLEN = 24;
|
||||
int CENNAM = 28;
|
||||
int CENEXT = 30;
|
||||
int CENCOM = 32;
|
||||
int CENDSK = 34;
|
||||
int CENATT = 36;
|
||||
int CENATX = 38;
|
||||
int CENOFF = 42;
|
||||
|
||||
/* The entries in the end of central directory */
|
||||
int ENDSIG = 'P' | ('K' << 8) | (5 << 16) | (6 << 24);
|
||||
int ENDHDR = 22;
|
||||
|
||||
/* The following two fields are missing in SUN JDK */
|
||||
int ENDNRD = 4;
|
||||
int ENDDCD = 6;
|
||||
int ENDSUB = 8;
|
||||
int ENDTOT = 10;
|
||||
int ENDSIZ = 12;
|
||||
int ENDOFF = 16;
|
||||
int ENDCOM = 20;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
package me.ag2s.epublib.util.zip;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
|
||||
import java.util.zip.ZipEntry;
|
||||
|
||||
public class ZipEntryWrapper {
|
||||
@NonNull
|
||||
private final Object zipEntry;
|
||||
|
||||
public void checkType() {
|
||||
|
||||
if (zipEntry instanceof java.util.zip.ZipEntry || zipEntry instanceof AndroidZipEntry) {
|
||||
} else {
|
||||
throw new RuntimeException("使用了不支持的类");
|
||||
}
|
||||
}
|
||||
|
||||
public ZipEntryWrapper(@NonNull ZipEntry zipEntry) {
|
||||
this.zipEntry = zipEntry;
|
||||
}
|
||||
|
||||
public ZipEntryWrapper(@NonNull AndroidZipEntry zipEntry) {
|
||||
this.zipEntry = zipEntry;
|
||||
}
|
||||
|
||||
public ZipEntryWrapper(@NonNull Object element) {
|
||||
|
||||
this.zipEntry = element;
|
||||
checkType();
|
||||
}
|
||||
|
||||
public boolean isDirectory() {
|
||||
checkType();
|
||||
if (zipEntry instanceof ZipEntry) {
|
||||
return ((ZipEntry) zipEntry).isDirectory();
|
||||
}
|
||||
if (zipEntry instanceof AndroidZipEntry) {
|
||||
return ((AndroidZipEntry) zipEntry).isDirectory();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public ZipEntry getZipEntry() {
|
||||
return (ZipEntry) zipEntry;
|
||||
}
|
||||
|
||||
public AndroidZipEntry getAndroidZipEntry() {
|
||||
return (AndroidZipEntry) zipEntry;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
checkType();
|
||||
if (zipEntry instanceof ZipEntry) {
|
||||
return ((ZipEntry) zipEntry).getName();
|
||||
}
|
||||
if (zipEntry instanceof AndroidZipEntry) {
|
||||
return ((AndroidZipEntry) zipEntry).getName();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public long getSize() {
|
||||
checkType();
|
||||
if (zipEntry instanceof ZipEntry) {
|
||||
return ((ZipEntry) zipEntry).getSize();
|
||||
}
|
||||
if (zipEntry instanceof AndroidZipEntry) {
|
||||
return ((AndroidZipEntry) zipEntry).getSize();
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
|
||||
|
||||
package me.ag2s.epublib.util.zip;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* Thrown during the creation or input of a zip file.
|
||||
*
|
||||
* @author Jochen Hoenicke
|
||||
* @author Per Bothner
|
||||
* @status updated to 1.4
|
||||
*/
|
||||
public class ZipException extends IOException {
|
||||
/**
|
||||
* Compatible with JDK 1.0+.
|
||||
*/
|
||||
private static final long serialVersionUID = 8000196834066748623L;
|
||||
|
||||
/**
|
||||
* Create an exception without a message.
|
||||
*/
|
||||
public ZipException() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an exception with a message.
|
||||
*
|
||||
* @param msg the message
|
||||
*/
|
||||
public ZipException(String msg) {
|
||||
super(msg);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package me.ag2s.epublib.util.zip;
|
||||
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.Enumeration;
|
||||
import java.util.zip.ZipFile;
|
||||
|
||||
/**
|
||||
* 对ZipFile的包装
|
||||
*/
|
||||
|
||||
public class ZipFileWrapper {
|
||||
@NonNull
|
||||
private final Object zipFile;
|
||||
|
||||
|
||||
public void checkType() {
|
||||
if (zipFile instanceof java.util.zip.ZipFile || zipFile instanceof AndroidZipFile) {
|
||||
} else {
|
||||
throw new RuntimeException("使用了不支持的类");
|
||||
}
|
||||
}
|
||||
|
||||
public ZipFileWrapper(@NonNull ZipFile zipFile) {
|
||||
this.zipFile = zipFile;
|
||||
checkType();
|
||||
}
|
||||
|
||||
public ZipFileWrapper(@NonNull AndroidZipFile zipFile) {
|
||||
this.zipFile = zipFile;
|
||||
checkType();
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
checkType();
|
||||
if (zipFile instanceof java.util.zip.ZipFile) {
|
||||
return ((ZipFile) zipFile).getName();
|
||||
} else if (zipFile instanceof AndroidZipFile) {
|
||||
return ((AndroidZipFile) zipFile).getName();
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public String getComment() {
|
||||
checkType();
|
||||
if (zipFile instanceof java.util.zip.ZipFile) {
|
||||
return ((ZipFile) zipFile).getComment();
|
||||
} else if (zipFile instanceof AndroidZipFile) {
|
||||
return ((AndroidZipFile) zipFile).getName();
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public ZipEntryWrapper getEntry(String name) {
|
||||
checkType();
|
||||
if (zipFile instanceof java.util.zip.ZipFile) {
|
||||
return new ZipEntryWrapper(((ZipFile) zipFile).getEntry(name));
|
||||
} else if (zipFile instanceof AndroidZipFile) {
|
||||
return new ZipEntryWrapper(((AndroidZipFile) zipFile).getEntry(name));
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public Enumeration entries() {
|
||||
checkType();
|
||||
if (zipFile instanceof java.util.zip.ZipFile) {
|
||||
return ((ZipFile) zipFile).entries();
|
||||
|
||||
} else if (zipFile instanceof AndroidZipFile) {
|
||||
return ((AndroidZipFile) zipFile).entries();
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public InputStream getInputStream(ZipEntryWrapper entry) throws IOException {
|
||||
checkType();
|
||||
if (zipFile instanceof java.util.zip.ZipFile) {
|
||||
return ((ZipFile) zipFile).getInputStream(entry.getZipEntry());
|
||||
} else if (zipFile instanceof AndroidZipFile) {
|
||||
return ((AndroidZipFile) zipFile).getInputStream(entry.getAndroidZipEntry());
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public void close() throws IOException {
|
||||
checkType();
|
||||
if (zipFile instanceof java.util.zip.ZipFile) {
|
||||
((ZipFile) zipFile).close();
|
||||
} else if (zipFile instanceof AndroidZipFile) {
|
||||
((AndroidZipFile) zipFile).close();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
Reference in new issue
Block a user