You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

DocumentInputStream.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. /* ====================================================================
  2. Licensed to the Apache Software Foundation (ASF) under one or more
  3. contributor license agreements. See the NOTICE file distributed with
  4. this work for additional information regarding copyright ownership.
  5. The ASF licenses this file to You under the Apache License, Version 2.0
  6. (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.poifs.filesystem;
  16. import static org.apache.poi.util.LittleEndianConsts.INT_SIZE;
  17. import static org.apache.poi.util.LittleEndianConsts.LONG_SIZE;
  18. import static org.apache.poi.util.LittleEndianConsts.SHORT_SIZE;
  19. import java.io.IOException;
  20. import java.io.InputStream;
  21. import java.nio.ByteBuffer;
  22. import java.util.Iterator;
  23. import org.apache.poi.poifs.property.DocumentProperty;
  24. import org.apache.poi.util.IOUtils;
  25. import org.apache.poi.util.LittleEndian;
  26. import org.apache.poi.util.LittleEndianInput;
  27. /**
  28. * This class provides methods to read a DocumentEntry managed by a
  29. * {@link POIFSFileSystem} instance.
  30. */
  31. public final class DocumentInputStream extends InputStream implements LittleEndianInput {
  32. /** returned by read operations if we're at end of document */
  33. private static final int EOF = -1;
  34. /** current offset into the Document */
  35. private int _current_offset;
  36. /** current block count */
  37. private int _current_block_count;
  38. /** current marked offset into the Document (used by mark and reset) */
  39. private int _marked_offset;
  40. /** and the block count for it */
  41. private int _marked_offset_count;
  42. /** the Document's size */
  43. private final int _document_size;
  44. /** have we been closed? */
  45. private boolean _closed;
  46. /** the actual Document */
  47. private final POIFSDocument _document;
  48. private Iterator<ByteBuffer> _data;
  49. private ByteBuffer _buffer;
  50. /**
  51. * Create an InputStream from the specified DocumentEntry
  52. *
  53. * @param document the DocumentEntry to be read
  54. *
  55. * @throws IOException if the DocumentEntry cannot be opened (like, maybe it has
  56. * been deleted?)
  57. */
  58. public DocumentInputStream(DocumentEntry document) throws IOException {
  59. if (!(document instanceof DocumentNode)) {
  60. throw new IOException("Cannot open internal document storage, " + document + " not a Document Node");
  61. }
  62. _current_offset = 0;
  63. _current_block_count = 0;
  64. _marked_offset = 0;
  65. _marked_offset_count = 0;
  66. _document_size = document.getSize();
  67. _closed = false;
  68. // can't be asserted ... see bug 61300
  69. // assert (_document_size >= 0) : "Document size can't be < 0";
  70. DocumentNode doc = (DocumentNode)document;
  71. DocumentProperty property = (DocumentProperty)doc.getProperty();
  72. _document = new POIFSDocument(
  73. property,
  74. ((DirectoryNode)doc.getParent()).getFileSystem()
  75. );
  76. _data = _document.getBlockIterator();
  77. }
  78. /**
  79. * Create an InputStream from the specified Document
  80. *
  81. * @param document the Document to be read
  82. */
  83. public DocumentInputStream(POIFSDocument document) {
  84. _current_offset = 0;
  85. _current_block_count = 0;
  86. _marked_offset = 0;
  87. _marked_offset_count = 0;
  88. _document_size = document.getSize();
  89. _closed = false;
  90. _document = document;
  91. _data = _document.getBlockIterator();
  92. }
  93. @Override
  94. public int available() {
  95. return remainingBytes();
  96. }
  97. /**
  98. * Helper methods for forbidden api calls
  99. *
  100. * @return the bytes remaining until the end of the stream
  101. */
  102. private int remainingBytes() {
  103. if (_closed) {
  104. throw new IllegalStateException("cannot perform requested operation on a closed stream");
  105. }
  106. return _document_size - _current_offset;
  107. }
  108. @Override
  109. public void close() {
  110. _closed = true;
  111. }
  112. /**
  113. * Tests if this input stream supports the mark and reset methods.
  114. *
  115. * @return {@code true} always
  116. */
  117. @Override
  118. public boolean markSupported() {
  119. return true;
  120. }
  121. @Override
  122. public synchronized void mark(int ignoredReadlimit) {
  123. _marked_offset = _current_offset;
  124. _marked_offset_count = Math.max(0, _current_block_count - 1);
  125. }
  126. @Override
  127. public int read() throws IOException {
  128. dieIfClosed();
  129. if (atEOD()) {
  130. return EOF;
  131. }
  132. byte[] b = new byte[1];
  133. int result = read(b, 0, 1);
  134. return (result == EOF) ? EOF : (b[0] & 0xFF);
  135. }
  136. @Override
  137. public int read(byte[] b) throws IOException {
  138. return read(b, 0, b.length);
  139. }
  140. @Override
  141. public int read(byte[] b, int off, int len) throws IOException {
  142. dieIfClosed();
  143. if (b == null) {
  144. throw new IllegalArgumentException("buffer must not be null");
  145. }
  146. if (off < 0 || len < 0 || b.length < off + len) {
  147. throw new IndexOutOfBoundsException("can't read past buffer boundaries");
  148. }
  149. if (len == 0) {
  150. return 0;
  151. }
  152. if (atEOD()) {
  153. return EOF;
  154. }
  155. int limit = Math.min(remainingBytes(), len);
  156. readFully(b, off, limit);
  157. return limit;
  158. }
  159. /**
  160. * Repositions this stream to the position at the time the mark() method was
  161. * last called on this input stream. If mark() has not been called this
  162. * method repositions the stream to its beginning.
  163. */
  164. @Override
  165. public synchronized void reset() {
  166. // Special case for reset to the start
  167. if(_marked_offset == 0 && _marked_offset_count == 0) {
  168. _current_block_count = _marked_offset_count;
  169. _current_offset = _marked_offset;
  170. _data = _document.getBlockIterator();
  171. _buffer = null;
  172. return;
  173. }
  174. // Start again, then wind on to the required block
  175. _data = _document.getBlockIterator();
  176. _current_offset = 0;
  177. for(int i=0; i<_marked_offset_count; i++) {
  178. _buffer = _data.next();
  179. _current_offset += _buffer.remaining();
  180. }
  181. _current_block_count = _marked_offset_count;
  182. // Do we need to position within it?
  183. if(_current_offset != _marked_offset) {
  184. // Grab the right block
  185. _buffer = _data.next();
  186. _current_block_count++;
  187. // Skip to the right place in it
  188. // (It should be positioned already at the start of the block,
  189. // we need to move further inside the block)
  190. int skipBy = _marked_offset - _current_offset;
  191. _buffer.position(_buffer.position() + skipBy);
  192. }
  193. // All done
  194. _current_offset = _marked_offset;
  195. }
  196. @Override
  197. public long skip(long n) throws IOException {
  198. dieIfClosed();
  199. if (n < 0) {
  200. return 0;
  201. }
  202. long new_offset = _current_offset + n;
  203. if (new_offset < _current_offset) {
  204. // wrap around in converting a VERY large long to an int
  205. new_offset = _document_size;
  206. } else if (new_offset > _document_size) {
  207. new_offset = _document_size;
  208. }
  209. long rval = new_offset - _current_offset;
  210. // TODO Do this better
  211. byte[] skip = IOUtils.safelyAllocate(rval, Integer.MAX_VALUE);
  212. readFully(skip);
  213. return rval;
  214. }
  215. private void dieIfClosed() throws IOException {
  216. if (_closed) {
  217. throw new IOException("cannot perform requested operation on a closed stream");
  218. }
  219. }
  220. private boolean atEOD() {
  221. return _current_offset == _document_size;
  222. }
  223. private void checkAvaliable(int requestedSize) {
  224. if (_closed) {
  225. throw new IllegalStateException("cannot perform requested operation on a closed stream");
  226. }
  227. if (requestedSize > _document_size - _current_offset) {
  228. throw new RuntimeException("Buffer underrun - requested " + requestedSize
  229. + " bytes but " + (_document_size - _current_offset) + " was available");
  230. }
  231. }
  232. @Override
  233. public void readFully(byte[] buf) {
  234. readFully(buf, 0, buf.length);
  235. }
  236. @Override
  237. public void readFully(byte[] buf, int off, int len) {
  238. if (len < 0) {
  239. throw new RuntimeException("Can't read negative number of bytes");
  240. }
  241. checkAvaliable(len);
  242. int read = 0;
  243. while(read < len) {
  244. if(_buffer == null || _buffer.remaining() == 0) {
  245. _current_block_count++;
  246. _buffer = _data.next();
  247. }
  248. int limit = Math.min(len-read, _buffer.remaining());
  249. _buffer.get(buf, off+read, limit);
  250. _current_offset += limit;
  251. read += limit;
  252. }
  253. }
  254. @Override
  255. public void readPlain(byte[] buf, int off, int len) {
  256. readFully(buf, off, len);
  257. }
  258. @Override
  259. public byte readByte() {
  260. return (byte) readUByte();
  261. }
  262. @Override
  263. public double readDouble() {
  264. return Double.longBitsToDouble(readLong());
  265. }
  266. @Override
  267. public long readLong() {
  268. checkAvaliable(LONG_SIZE);
  269. byte[] data = new byte[LONG_SIZE];
  270. readFully(data, 0, LONG_SIZE);
  271. return LittleEndian.getLong(data, 0);
  272. }
  273. @Override
  274. public short readShort() {
  275. checkAvaliable(SHORT_SIZE);
  276. byte[] data = new byte[SHORT_SIZE];
  277. readFully(data, 0, SHORT_SIZE);
  278. return LittleEndian.getShort(data);
  279. }
  280. @Override
  281. public int readInt() {
  282. checkAvaliable(INT_SIZE);
  283. byte[] data = new byte[INT_SIZE];
  284. readFully(data, 0, INT_SIZE);
  285. return LittleEndian.getInt(data);
  286. }
  287. public long readUInt() {
  288. int i = readInt();
  289. return i & 0xFFFFFFFFL;
  290. }
  291. @Override
  292. public int readUShort() {
  293. checkAvaliable(SHORT_SIZE);
  294. byte[] data = new byte[SHORT_SIZE];
  295. readFully(data, 0, SHORT_SIZE);
  296. return LittleEndian.getUShort(data);
  297. }
  298. @Override
  299. public int readUByte() {
  300. checkAvaliable(1);
  301. byte[] data = new byte[1];
  302. readFully(data, 0, 1);
  303. if (data[0] >= 0)
  304. return data[0];
  305. return data[0] + 256;
  306. }
  307. }