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.

TemporaryBuffer.java 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  1. /*
  2. * Copyright (C) 2008-2009, Google Inc.
  3. * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
  4. * and other copyright owners as documented in the project's IP log.
  5. *
  6. * This program and the accompanying materials are made available
  7. * under the terms of the Eclipse Distribution License v1.0 which
  8. * accompanies this distribution, is reproduced below, and is
  9. * available at http://www.eclipse.org/org/documents/edl-v10.php
  10. *
  11. * All rights reserved.
  12. *
  13. * Redistribution and use in source and binary forms, with or
  14. * without modification, are permitted provided that the following
  15. * conditions are met:
  16. *
  17. * - Redistributions of source code must retain the above copyright
  18. * notice, this list of conditions and the following disclaimer.
  19. *
  20. * - Redistributions in binary form must reproduce the above
  21. * copyright notice, this list of conditions and the following
  22. * disclaimer in the documentation and/or other materials provided
  23. * with the distribution.
  24. *
  25. * - Neither the name of the Eclipse Foundation, Inc. nor the
  26. * names of its contributors may be used to endorse or promote
  27. * products derived from this software without specific prior
  28. * written permission.
  29. *
  30. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  31. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  32. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  33. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  34. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  35. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  36. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  37. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  38. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  39. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  40. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  41. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  42. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  43. */
  44. package org.eclipse.jgit.util;
  45. import java.io.BufferedOutputStream;
  46. import java.io.File;
  47. import java.io.FileInputStream;
  48. import java.io.FileOutputStream;
  49. import java.io.IOException;
  50. import java.io.InputStream;
  51. import java.io.OutputStream;
  52. import java.util.ArrayList;
  53. import org.eclipse.jgit.internal.JGitText;
  54. import org.eclipse.jgit.lib.NullProgressMonitor;
  55. import org.eclipse.jgit.lib.ProgressMonitor;
  56. /**
  57. * A fully buffered output stream.
  58. * <p>
  59. * Subclasses determine the behavior when the in-memory buffer capacity has been
  60. * exceeded and additional bytes are still being received for output.
  61. */
  62. public abstract class TemporaryBuffer extends OutputStream {
  63. /** Default limit for in-core storage. */
  64. protected static final int DEFAULT_IN_CORE_LIMIT = 1024 * 1024;
  65. /** Chain of data, if we are still completely in-core; otherwise null. */
  66. ArrayList<Block> blocks;
  67. /**
  68. * Maximum number of bytes we will permit storing in memory.
  69. * <p>
  70. * When this limit is reached the data will be shifted to a file on disk,
  71. * preventing the JVM heap from growing out of control.
  72. */
  73. private int inCoreLimit;
  74. /** Initial size of block list. */
  75. private int initialBlocks;
  76. /** If {@link #inCoreLimit} has been reached, remainder goes here. */
  77. private OutputStream overflow;
  78. /**
  79. * Create a new empty temporary buffer.
  80. *
  81. * @param limit
  82. * maximum number of bytes to store in memory before entering the
  83. * overflow output path; also used as the estimated size.
  84. */
  85. protected TemporaryBuffer(final int limit) {
  86. this(limit, limit);
  87. }
  88. /**
  89. * Create a new empty temporary buffer.
  90. *
  91. * @param estimatedSize
  92. * estimated size of storage used, to size the initial list of
  93. * block pointers.
  94. * @param limit
  95. * maximum number of bytes to store in memory before entering the
  96. * overflow output path.
  97. * @since 4.0
  98. */
  99. protected TemporaryBuffer(final int estimatedSize, final int limit) {
  100. if (estimatedSize > limit)
  101. throw new IllegalArgumentException();
  102. this.inCoreLimit = limit;
  103. this.initialBlocks = (estimatedSize - 1) / Block.SZ + 1;
  104. reset();
  105. }
  106. /** {@inheritDoc} */
  107. @Override
  108. public void write(final int b) throws IOException {
  109. if (overflow != null) {
  110. overflow.write(b);
  111. return;
  112. }
  113. Block s = last();
  114. if (s.isFull()) {
  115. if (reachedInCoreLimit()) {
  116. overflow.write(b);
  117. return;
  118. }
  119. s = new Block();
  120. blocks.add(s);
  121. }
  122. s.buffer[s.count++] = (byte) b;
  123. }
  124. /** {@inheritDoc} */
  125. @Override
  126. public void write(final byte[] b, int off, int len) throws IOException {
  127. if (overflow == null) {
  128. while (len > 0) {
  129. Block s = last();
  130. if (s.isFull()) {
  131. if (reachedInCoreLimit())
  132. break;
  133. s = new Block();
  134. blocks.add(s);
  135. }
  136. final int n = Math.min(s.buffer.length - s.count, len);
  137. System.arraycopy(b, off, s.buffer, s.count, n);
  138. s.count += n;
  139. len -= n;
  140. off += n;
  141. }
  142. }
  143. if (len > 0)
  144. overflow.write(b, off, len);
  145. }
  146. /**
  147. * Dumps the entire buffer into the overflow stream, and flushes it.
  148. *
  149. * @throws java.io.IOException
  150. * the overflow stream cannot be started, or the buffer contents
  151. * cannot be written to it, or it failed to flush.
  152. */
  153. protected void doFlush() throws IOException {
  154. if (overflow == null)
  155. switchToOverflow();
  156. overflow.flush();
  157. }
  158. /**
  159. * Copy all bytes remaining on the input stream into this buffer.
  160. *
  161. * @param in
  162. * the stream to read from, until EOF is reached.
  163. * @throws java.io.IOException
  164. * an error occurred reading from the input stream, or while
  165. * writing to a local temporary file.
  166. */
  167. public void copy(final InputStream in) throws IOException {
  168. if (blocks != null) {
  169. for (;;) {
  170. Block s = last();
  171. if (s.isFull()) {
  172. if (reachedInCoreLimit())
  173. break;
  174. s = new Block();
  175. blocks.add(s);
  176. }
  177. int n = in.read(s.buffer, s.count, s.buffer.length - s.count);
  178. if (n < 1)
  179. return;
  180. s.count += n;
  181. }
  182. }
  183. final byte[] tmp = new byte[Block.SZ];
  184. int n;
  185. while ((n = in.read(tmp)) > 0)
  186. overflow.write(tmp, 0, n);
  187. }
  188. /**
  189. * Obtain the length (in bytes) of the buffer.
  190. * <p>
  191. * The length is only accurate after {@link #close()} has been invoked.
  192. *
  193. * @return total length of the buffer, in bytes.
  194. */
  195. public long length() {
  196. return inCoreLength();
  197. }
  198. private long inCoreLength() {
  199. final Block last = last();
  200. return ((long) blocks.size() - 1) * Block.SZ + last.count;
  201. }
  202. /**
  203. * Convert this buffer's contents into a contiguous byte array.
  204. * <p>
  205. * The buffer is only complete after {@link #close()} has been invoked.
  206. *
  207. * @return the complete byte array; length matches {@link #length()}.
  208. * @throws java.io.IOException
  209. * an error occurred reading from a local temporary file
  210. */
  211. public byte[] toByteArray() throws IOException {
  212. final long len = length();
  213. if (Integer.MAX_VALUE < len)
  214. throw new OutOfMemoryError(JGitText.get().lengthExceedsMaximumArraySize);
  215. final byte[] out = new byte[(int) len];
  216. int outPtr = 0;
  217. for (final Block b : blocks) {
  218. System.arraycopy(b.buffer, 0, out, outPtr, b.count);
  219. outPtr += b.count;
  220. }
  221. return out;
  222. }
  223. /**
  224. * Convert this buffer's contents into a contiguous byte array. If this size
  225. * of the buffer exceeds the limit only return the first {@code limit} bytes
  226. * <p>
  227. * The buffer is only complete after {@link #close()} has been invoked.
  228. *
  229. * @param limit
  230. * the maximum number of bytes to be returned
  231. * @return the byte array limited to {@code limit} bytes.
  232. * @throws java.io.IOException
  233. * an error occurred reading from a local temporary file
  234. * @since 4.2
  235. */
  236. public byte[] toByteArray(int limit) throws IOException {
  237. final long len = Math.min(length(), limit);
  238. if (Integer.MAX_VALUE < len)
  239. throw new OutOfMemoryError(
  240. JGitText.get().lengthExceedsMaximumArraySize);
  241. final byte[] out = new byte[(int) len];
  242. int outPtr = 0;
  243. for (final Block b : blocks) {
  244. System.arraycopy(b.buffer, 0, out, outPtr, b.count);
  245. outPtr += b.count;
  246. }
  247. return out;
  248. }
  249. /**
  250. * Send this buffer to an output stream.
  251. * <p>
  252. * This method may only be invoked after {@link #close()} has completed
  253. * normally, to ensure all data is completely transferred.
  254. *
  255. * @param os
  256. * stream to send this buffer's complete content to.
  257. * @param pm
  258. * if not null progress updates are sent here. Caller should
  259. * initialize the task and the number of work units to <code>
  260. * {@link #length()}/1024</code>.
  261. * @throws java.io.IOException
  262. * an error occurred reading from a temporary file on the local
  263. * system, or writing to the output stream.
  264. */
  265. public void writeTo(final OutputStream os, ProgressMonitor pm)
  266. throws IOException {
  267. if (pm == null)
  268. pm = NullProgressMonitor.INSTANCE;
  269. for (final Block b : blocks) {
  270. os.write(b.buffer, 0, b.count);
  271. pm.update(b.count / 1024);
  272. }
  273. }
  274. /**
  275. * Open an input stream to read from the buffered data.
  276. * <p>
  277. * This method may only be invoked after {@link #close()} has completed
  278. * normally, to ensure all data is completely transferred.
  279. *
  280. * @return a stream to read from the buffer. The caller must close the
  281. * stream when it is no longer useful.
  282. * @throws java.io.IOException
  283. * an error occurred opening the temporary file.
  284. */
  285. public InputStream openInputStream() throws IOException {
  286. return new BlockInputStream();
  287. }
  288. /**
  289. * Same as {@link #openInputStream()} but handling destruction of any
  290. * associated resources automatically when closing the returned stream.
  291. *
  292. * @return an InputStream which will automatically destroy any associated
  293. * temporary file on {@link #close()}
  294. * @throws IOException
  295. * in case of an error.
  296. * @since 4.11
  297. */
  298. public InputStream openInputStreamWithAutoDestroy() throws IOException {
  299. return new BlockInputStream() {
  300. @Override
  301. public void close() throws IOException {
  302. super.close();
  303. destroy();
  304. }
  305. };
  306. }
  307. /**
  308. * Reset this buffer for reuse, purging all buffered content.
  309. */
  310. public void reset() {
  311. if (overflow != null) {
  312. destroy();
  313. }
  314. if (blocks != null)
  315. blocks.clear();
  316. else
  317. blocks = new ArrayList<>(initialBlocks);
  318. blocks.add(new Block(Math.min(inCoreLimit, Block.SZ)));
  319. }
  320. /**
  321. * Open the overflow output stream, so the remaining output can be stored.
  322. *
  323. * @return the output stream to receive the buffered content, followed by
  324. * the remaining output.
  325. * @throws java.io.IOException
  326. * the buffer cannot create the overflow stream.
  327. */
  328. protected abstract OutputStream overflow() throws IOException;
  329. private Block last() {
  330. return blocks.get(blocks.size() - 1);
  331. }
  332. private boolean reachedInCoreLimit() throws IOException {
  333. if (inCoreLength() < inCoreLimit)
  334. return false;
  335. switchToOverflow();
  336. return true;
  337. }
  338. private void switchToOverflow() throws IOException {
  339. overflow = overflow();
  340. final Block last = blocks.remove(blocks.size() - 1);
  341. for (final Block b : blocks)
  342. overflow.write(b.buffer, 0, b.count);
  343. blocks = null;
  344. overflow = new BufferedOutputStream(overflow, Block.SZ);
  345. overflow.write(last.buffer, 0, last.count);
  346. }
  347. /** {@inheritDoc} */
  348. @Override
  349. public void close() throws IOException {
  350. if (overflow != null) {
  351. try {
  352. overflow.close();
  353. } finally {
  354. overflow = null;
  355. }
  356. }
  357. }
  358. /**
  359. * Clear this buffer so it has no data, and cannot be used again.
  360. */
  361. public void destroy() {
  362. blocks = null;
  363. if (overflow != null) {
  364. try {
  365. overflow.close();
  366. } catch (IOException err) {
  367. // We shouldn't encounter an error closing the file.
  368. } finally {
  369. overflow = null;
  370. }
  371. }
  372. }
  373. /**
  374. * A fully buffered output stream using local disk storage for large data.
  375. * <p>
  376. * Initially this output stream buffers to memory and is therefore similar
  377. * to ByteArrayOutputStream, but it shifts to using an on disk temporary
  378. * file if the output gets too large.
  379. * <p>
  380. * The content of this buffered stream may be sent to another OutputStream
  381. * only after this stream has been properly closed by {@link #close()}.
  382. */
  383. public static class LocalFile extends TemporaryBuffer {
  384. /** Directory to store the temporary file under. */
  385. private final File directory;
  386. /**
  387. * Location of our temporary file if we are on disk; otherwise null.
  388. * <p>
  389. * If we exceeded the {@link #inCoreLimit} we nulled out {@link #blocks}
  390. * and created this file instead. All output goes here through
  391. * {@link #overflow}.
  392. */
  393. private File onDiskFile;
  394. /**
  395. * Create a new temporary buffer, limiting memory usage.
  396. *
  397. * @param directory
  398. * if the buffer has to spill over into a temporary file, the
  399. * directory where the file should be saved. If null the
  400. * system default temporary directory (for example /tmp) will
  401. * be used instead.
  402. */
  403. public LocalFile(final File directory) {
  404. this(directory, DEFAULT_IN_CORE_LIMIT);
  405. }
  406. /**
  407. * Create a new temporary buffer, limiting memory usage.
  408. *
  409. * @param directory
  410. * if the buffer has to spill over into a temporary file, the
  411. * directory where the file should be saved. If null the
  412. * system default temporary directory (for example /tmp) will
  413. * be used instead.
  414. * @param inCoreLimit
  415. * maximum number of bytes to store in memory. Storage beyond
  416. * this limit will use the local file.
  417. */
  418. public LocalFile(final File directory, final int inCoreLimit) {
  419. super(inCoreLimit);
  420. this.directory = directory;
  421. }
  422. @Override
  423. protected OutputStream overflow() throws IOException {
  424. onDiskFile = File.createTempFile("jgit_", ".buf", directory); //$NON-NLS-1$ //$NON-NLS-2$
  425. return new BufferedOutputStream(new FileOutputStream(onDiskFile));
  426. }
  427. @Override
  428. public long length() {
  429. if (onDiskFile == null) {
  430. return super.length();
  431. }
  432. return onDiskFile.length();
  433. }
  434. @Override
  435. public byte[] toByteArray() throws IOException {
  436. if (onDiskFile == null) {
  437. return super.toByteArray();
  438. }
  439. final long len = length();
  440. if (Integer.MAX_VALUE < len)
  441. throw new OutOfMemoryError(JGitText.get().lengthExceedsMaximumArraySize);
  442. final byte[] out = new byte[(int) len];
  443. final FileInputStream in = new FileInputStream(onDiskFile);
  444. try {
  445. IO.readFully(in, out, 0, (int) len);
  446. } finally {
  447. in.close();
  448. }
  449. return out;
  450. }
  451. @Override
  452. public void writeTo(final OutputStream os, ProgressMonitor pm)
  453. throws IOException {
  454. if (onDiskFile == null) {
  455. super.writeTo(os, pm);
  456. return;
  457. }
  458. if (pm == null)
  459. pm = NullProgressMonitor.INSTANCE;
  460. final FileInputStream in = new FileInputStream(onDiskFile);
  461. try {
  462. int cnt;
  463. final byte[] buf = new byte[Block.SZ];
  464. while ((cnt = in.read(buf)) >= 0) {
  465. os.write(buf, 0, cnt);
  466. pm.update(cnt / 1024);
  467. }
  468. } finally {
  469. in.close();
  470. }
  471. }
  472. @Override
  473. public InputStream openInputStream() throws IOException {
  474. if (onDiskFile == null)
  475. return super.openInputStream();
  476. return new FileInputStream(onDiskFile);
  477. }
  478. @Override
  479. public InputStream openInputStreamWithAutoDestroy() throws IOException {
  480. if (onDiskFile == null) {
  481. return super.openInputStreamWithAutoDestroy();
  482. }
  483. return new FileInputStream(onDiskFile) {
  484. @Override
  485. public void close() throws IOException {
  486. super.close();
  487. destroy();
  488. }
  489. };
  490. }
  491. @Override
  492. public void destroy() {
  493. super.destroy();
  494. if (onDiskFile != null) {
  495. try {
  496. if (!onDiskFile.delete())
  497. onDiskFile.deleteOnExit();
  498. } finally {
  499. onDiskFile = null;
  500. }
  501. }
  502. }
  503. }
  504. /**
  505. * A temporary buffer that will never exceed its in-memory limit.
  506. * <p>
  507. * If the in-memory limit is reached an IOException is thrown, rather than
  508. * attempting to spool to local disk.
  509. */
  510. public static class Heap extends TemporaryBuffer {
  511. /**
  512. * Create a new heap buffer with a maximum storage limit.
  513. *
  514. * @param limit
  515. * maximum number of bytes that can be stored in this buffer;
  516. * also used as the estimated size. Storing beyond this many
  517. * will cause an IOException to be thrown during write.
  518. */
  519. public Heap(final int limit) {
  520. super(limit);
  521. }
  522. /**
  523. * Create a new heap buffer with a maximum storage limit.
  524. *
  525. * @param estimatedSize
  526. * estimated size of storage used, to size the initial list of
  527. * block pointers.
  528. * @param limit
  529. * maximum number of bytes that can be stored in this buffer.
  530. * Storing beyond this many will cause an IOException to be
  531. * thrown during write.
  532. * @since 4.0
  533. */
  534. public Heap(final int estimatedSize, final int limit) {
  535. super(estimatedSize, limit);
  536. }
  537. @Override
  538. protected OutputStream overflow() throws IOException {
  539. throw new IOException(JGitText.get().inMemoryBufferLimitExceeded);
  540. }
  541. }
  542. static class Block {
  543. static final int SZ = 8 * 1024;
  544. final byte[] buffer;
  545. int count;
  546. Block() {
  547. buffer = new byte[SZ];
  548. }
  549. Block(int sz) {
  550. buffer = new byte[sz];
  551. }
  552. boolean isFull() {
  553. return count == buffer.length;
  554. }
  555. }
  556. private class BlockInputStream extends InputStream {
  557. private byte[] singleByteBuffer;
  558. private int blockIndex;
  559. private Block block;
  560. private int blockPos;
  561. BlockInputStream() {
  562. block = blocks.get(blockIndex);
  563. }
  564. @Override
  565. public int read() throws IOException {
  566. if (singleByteBuffer == null)
  567. singleByteBuffer = new byte[1];
  568. int n = read(singleByteBuffer);
  569. return n == 1 ? singleByteBuffer[0] & 0xff : -1;
  570. }
  571. @Override
  572. public long skip(long cnt) throws IOException {
  573. long skipped = 0;
  574. while (0 < cnt) {
  575. int n = (int) Math.min(block.count - blockPos, cnt);
  576. if (0 < n) {
  577. blockPos += n;
  578. skipped += n;
  579. cnt -= n;
  580. } else if (nextBlock())
  581. continue;
  582. else
  583. break;
  584. }
  585. return skipped;
  586. }
  587. @Override
  588. public int read(byte[] b, int off, int len) throws IOException {
  589. if (len == 0)
  590. return 0;
  591. int copied = 0;
  592. while (0 < len) {
  593. int c = Math.min(block.count - blockPos, len);
  594. if (0 < c) {
  595. System.arraycopy(block.buffer, blockPos, b, off, c);
  596. blockPos += c;
  597. off += c;
  598. len -= c;
  599. copied += c;
  600. } else if (nextBlock())
  601. continue;
  602. else
  603. break;
  604. }
  605. return 0 < copied ? copied : -1;
  606. }
  607. private boolean nextBlock() {
  608. if (++blockIndex < blocks.size()) {
  609. block = blocks.get(blockIndex);
  610. blockPos = 0;
  611. return true;
  612. }
  613. return false;
  614. }
  615. }
  616. }