From 79b6b02e31510663a44c5c1b0991bcba845162da Mon Sep 17 00:00:00 2001 From: Armin Braun Date: Tue, 4 Aug 2020 11:20:22 +0200 Subject: [PATCH] Fix Java11 Streams Class Copy In https://github.com/elastic/elasticsearch/pull/60608 we missed aligning the Java11 version of this class and this is breaking BwC tests now. This commit aligns Java11 and Java8 versions of it again. --- .../core/internal/io/Streams.java | 45 ++++++++++++++++--- 1 file changed, 38 insertions(+), 7 deletions(-) diff --git a/libs/core/src/main/java11/org/elasticsearch/core/internal/io/Streams.java b/libs/core/src/main/java11/org/elasticsearch/core/internal/io/Streams.java index 34b3785765d87..1fc8392609d82 100644 --- a/libs/core/src/main/java11/org/elasticsearch/core/internal/io/Streams.java +++ b/libs/core/src/main/java11/org/elasticsearch/core/internal/io/Streams.java @@ -32,26 +32,57 @@ */ public abstract class Streams { + private static final ThreadLocal buffer = ThreadLocal.withInitial(() -> new byte[8 * 1024]); + /** - * Copy the contents of the given InputStream to the given OutputStream. - * Closes both streams when done. + * Copy the contents of the given InputStream to the given OutputStream. Optionally, closes both streams when done. * - * @param in the stream to copy from - * @param out the stream to copy to + * @param in the stream to copy from + * @param out the stream to copy to + * @param close whether to close both streams after copying + * @param buffer buffer to use for copying * @return the number of bytes copied * @throws IOException in case of I/O errors */ - public static long copy(final InputStream in, final OutputStream out) throws IOException { + public static long copy(final InputStream in, final OutputStream out, byte[] buffer, boolean close) throws IOException { Exception err = null; try { - final long byteCount = in.transferTo(out); + long byteCount = 0; + int bytesRead; + while ((bytesRead = in.read(buffer)) != -1) { + out.write(buffer, 0, bytesRead); + byteCount += bytesRead; + } out.flush(); return byteCount; } catch (IOException | RuntimeException e) { err = e; throw e; } finally { - IOUtils.close(err, in, out); + if (close) { + IOUtils.close(err, in, out); + } } } + + /** + * @see #copy(InputStream, OutputStream, byte[], boolean) + */ + public static long copy(final InputStream in, final OutputStream out, boolean close) throws IOException { + return copy(in, out, buffer.get(), close); + } + + /** + * @see #copy(InputStream, OutputStream, byte[], boolean) + */ + public static long copy(final InputStream in, final OutputStream out, byte[] buffer) throws IOException { + return copy(in, out, buffer, true); + } + + /** + * @see #copy(InputStream, OutputStream, byte[], boolean) + */ + public static long copy(final InputStream in, final OutputStream out) throws IOException { + return copy(in, out, buffer.get(), true); + } }