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 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  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.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. private 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. /** If {@link #inCoreLimit} has been reached, remainder goes here. */
  75. private OutputStream overflow;
  76. /**
  77. * Create a new empty temporary buffer.
  78. *
  79. * @param limit
  80. * maximum number of bytes to store in memory before entering the
  81. * overflow output path.
  82. */
  83. protected TemporaryBuffer(final int limit) {
  84. inCoreLimit = limit;
  85. reset();
  86. }
  87. @Override
  88. public void write(final int b) throws IOException {
  89. if (overflow != null) {
  90. overflow.write(b);
  91. return;
  92. }
  93. Block s = last();
  94. if (s.isFull()) {
  95. if (reachedInCoreLimit()) {
  96. overflow.write(b);
  97. return;
  98. }
  99. s = new Block();
  100. blocks.add(s);
  101. }
  102. s.buffer[s.count++] = (byte) b;
  103. }
  104. @Override
  105. public void write(final byte[] b, int off, int len) throws IOException {
  106. if (overflow == null) {
  107. while (len > 0) {
  108. Block s = last();
  109. if (s.isFull()) {
  110. if (reachedInCoreLimit())
  111. break;
  112. s = new Block();
  113. blocks.add(s);
  114. }
  115. final int n = Math.min(Block.SZ - s.count, len);
  116. System.arraycopy(b, off, s.buffer, s.count, n);
  117. s.count += n;
  118. len -= n;
  119. off += n;
  120. }
  121. }
  122. if (len > 0)
  123. overflow.write(b, off, len);
  124. }
  125. /**
  126. * Dumps the entire buffer into the overflow stream, and flushes it.
  127. *
  128. * @throws IOException
  129. * the overflow stream cannot be started, or the buffer contents
  130. * cannot be written to it, or it failed to flush.
  131. */
  132. protected void doFlush() throws IOException {
  133. if (overflow == null)
  134. switchToOverflow();
  135. overflow.flush();
  136. }
  137. /**
  138. * Copy all bytes remaining on the input stream into this buffer.
  139. *
  140. * @param in
  141. * the stream to read from, until EOF is reached.
  142. * @throws IOException
  143. * an error occurred reading from the input stream, or while
  144. * writing to a local temporary file.
  145. */
  146. public void copy(final InputStream in) throws IOException {
  147. if (blocks != null) {
  148. for (;;) {
  149. Block s = last();
  150. if (s.isFull()) {
  151. if (reachedInCoreLimit())
  152. break;
  153. s = new Block();
  154. blocks.add(s);
  155. }
  156. final int n = in.read(s.buffer, s.count, Block.SZ - s.count);
  157. if (n < 1)
  158. return;
  159. s.count += n;
  160. }
  161. }
  162. final byte[] tmp = new byte[Block.SZ];
  163. int n;
  164. while ((n = in.read(tmp)) > 0)
  165. overflow.write(tmp, 0, n);
  166. }
  167. /**
  168. * Obtain the length (in bytes) of the buffer.
  169. * <p>
  170. * The length is only accurate after {@link #close()} has been invoked.
  171. *
  172. * @return total length of the buffer, in bytes.
  173. */
  174. public long length() {
  175. final Block last = last();
  176. return ((long) blocks.size()) * Block.SZ - (Block.SZ - last.count);
  177. }
  178. /**
  179. * Convert this buffer's contents into a contiguous byte array.
  180. * <p>
  181. * The buffer is only complete after {@link #close()} has been invoked.
  182. *
  183. * @return the complete byte array; length matches {@link #length()}.
  184. * @throws IOException
  185. * an error occurred reading from a local temporary file
  186. * @throws OutOfMemoryError
  187. * the buffer cannot fit in memory
  188. */
  189. public byte[] toByteArray() throws IOException {
  190. final long len = length();
  191. if (Integer.MAX_VALUE < len)
  192. throw new OutOfMemoryError(JGitText.get().lengthExceedsMaximumArraySize);
  193. final byte[] out = new byte[(int) len];
  194. int outPtr = 0;
  195. for (final Block b : blocks) {
  196. System.arraycopy(b.buffer, 0, out, outPtr, b.count);
  197. outPtr += b.count;
  198. }
  199. return out;
  200. }
  201. /**
  202. * Send this buffer to an output stream.
  203. * <p>
  204. * This method may only be invoked after {@link #close()} has completed
  205. * normally, to ensure all data is completely transferred.
  206. *
  207. * @param os
  208. * stream to send this buffer's complete content to.
  209. * @param pm
  210. * if not null progress updates are sent here. Caller should
  211. * initialize the task and the number of work units to <code>
  212. * {@link #length()}/1024</code>.
  213. * @throws IOException
  214. * an error occurred reading from a temporary file on the local
  215. * system, or writing to the output stream.
  216. */
  217. public void writeTo(final OutputStream os, ProgressMonitor pm)
  218. throws IOException {
  219. if (pm == null)
  220. pm = NullProgressMonitor.INSTANCE;
  221. for (final Block b : blocks) {
  222. os.write(b.buffer, 0, b.count);
  223. pm.update(b.count / 1024);
  224. }
  225. }
  226. /** Reset this buffer for reuse, purging all buffered content. */
  227. public void reset() {
  228. if (overflow != null) {
  229. destroy();
  230. }
  231. blocks = new ArrayList<Block>(inCoreLimit / Block.SZ);
  232. blocks.add(new Block());
  233. }
  234. /**
  235. * Open the overflow output stream, so the remaining output can be stored.
  236. *
  237. * @return the output stream to receive the buffered content, followed by
  238. * the remaining output.
  239. * @throws IOException
  240. * the buffer cannot create the overflow stream.
  241. */
  242. protected abstract OutputStream overflow() throws IOException;
  243. private Block last() {
  244. return blocks.get(blocks.size() - 1);
  245. }
  246. private boolean reachedInCoreLimit() throws IOException {
  247. if (blocks.size() * Block.SZ < inCoreLimit)
  248. return false;
  249. switchToOverflow();
  250. return true;
  251. }
  252. private void switchToOverflow() throws IOException {
  253. overflow = overflow();
  254. final Block last = blocks.remove(blocks.size() - 1);
  255. for (final Block b : blocks)
  256. overflow.write(b.buffer, 0, b.count);
  257. blocks = null;
  258. overflow = new BufferedOutputStream(overflow, Block.SZ);
  259. overflow.write(last.buffer, 0, last.count);
  260. }
  261. public void close() throws IOException {
  262. if (overflow != null) {
  263. try {
  264. overflow.close();
  265. } finally {
  266. overflow = null;
  267. }
  268. }
  269. }
  270. /** Clear this buffer so it has no data, and cannot be used again. */
  271. public void destroy() {
  272. blocks = null;
  273. if (overflow != null) {
  274. try {
  275. overflow.close();
  276. } catch (IOException err) {
  277. // We shouldn't encounter an error closing the file.
  278. } finally {
  279. overflow = null;
  280. }
  281. }
  282. }
  283. /**
  284. * A fully buffered output stream using local disk storage for large data.
  285. * <p>
  286. * Initially this output stream buffers to memory and is therefore similar
  287. * to ByteArrayOutputStream, but it shifts to using an on disk temporary
  288. * file if the output gets too large.
  289. * <p>
  290. * The content of this buffered stream may be sent to another OutputStream
  291. * only after this stream has been properly closed by {@link #close()}.
  292. */
  293. public static class LocalFile extends TemporaryBuffer {
  294. /**
  295. * Location of our temporary file if we are on disk; otherwise null.
  296. * <p>
  297. * If we exceeded the {@link #inCoreLimit} we nulled out {@link #blocks}
  298. * and created this file instead. All output goes here through
  299. * {@link #overflow}.
  300. */
  301. private File onDiskFile;
  302. /** Create a new temporary buffer. */
  303. public LocalFile() {
  304. this(DEFAULT_IN_CORE_LIMIT);
  305. }
  306. /**
  307. * Create a new temporary buffer, limiting memory usage.
  308. *
  309. * @param inCoreLimit
  310. * maximum number of bytes to store in memory. Storage beyond
  311. * this limit will use the local file.
  312. */
  313. public LocalFile(final int inCoreLimit) {
  314. super(inCoreLimit);
  315. }
  316. protected OutputStream overflow() throws IOException {
  317. onDiskFile = File.createTempFile("jgit_", ".buffer");
  318. return new FileOutputStream(onDiskFile);
  319. }
  320. public long length() {
  321. if (onDiskFile == null) {
  322. return super.length();
  323. }
  324. return onDiskFile.length();
  325. }
  326. public byte[] toByteArray() throws IOException {
  327. if (onDiskFile == null) {
  328. return super.toByteArray();
  329. }
  330. final long len = length();
  331. if (Integer.MAX_VALUE < len)
  332. throw new OutOfMemoryError(JGitText.get().lengthExceedsMaximumArraySize);
  333. final byte[] out = new byte[(int) len];
  334. final FileInputStream in = new FileInputStream(onDiskFile);
  335. try {
  336. IO.readFully(in, out, 0, (int) len);
  337. } finally {
  338. in.close();
  339. }
  340. return out;
  341. }
  342. public void writeTo(final OutputStream os, ProgressMonitor pm)
  343. throws IOException {
  344. if (onDiskFile == null) {
  345. super.writeTo(os, pm);
  346. return;
  347. }
  348. if (pm == null)
  349. pm = NullProgressMonitor.INSTANCE;
  350. final FileInputStream in = new FileInputStream(onDiskFile);
  351. try {
  352. int cnt;
  353. final byte[] buf = new byte[Block.SZ];
  354. while ((cnt = in.read(buf)) >= 0) {
  355. os.write(buf, 0, cnt);
  356. pm.update(cnt / 1024);
  357. }
  358. } finally {
  359. in.close();
  360. }
  361. }
  362. @Override
  363. public void destroy() {
  364. super.destroy();
  365. if (onDiskFile != null) {
  366. try {
  367. if (!onDiskFile.delete())
  368. onDiskFile.deleteOnExit();
  369. } finally {
  370. onDiskFile = null;
  371. }
  372. }
  373. }
  374. }
  375. /**
  376. * A temporary buffer that will never exceed its in-memory limit.
  377. * <p>
  378. * If the in-memory limit is reached an IOException is thrown, rather than
  379. * attempting to spool to local disk.
  380. */
  381. public static class Heap extends TemporaryBuffer {
  382. /**
  383. * Create a new heap buffer with a maximum storage limit.
  384. *
  385. * @param limit
  386. * maximum number of bytes that can be stored in this buffer.
  387. * Storing beyond this many will cause an IOException to be
  388. * thrown during write.
  389. */
  390. public Heap(final int limit) {
  391. super(limit);
  392. }
  393. @Override
  394. protected OutputStream overflow() throws IOException {
  395. throw new IOException(JGitText.get().inMemoryBufferLimitExceeded);
  396. }
  397. }
  398. static class Block {
  399. static final int SZ = 8 * 1024;
  400. final byte[] buffer = new byte[SZ];
  401. int count;
  402. boolean isFull() {
  403. return count == SZ;
  404. }
  405. }
  406. }