From 1884f5155e67a271f06f70925c2cd8d655fca07c Mon Sep 17 00:00:00 2001
From: Vojtech Moravec <vojtech.moravec.st@vsb.cz>
Date: Fri, 25 Sep 2020 09:11:36 +0200
Subject: [PATCH] Don't close input stream in readCacheFileImpl.

readCacheFileImpl would close the input stream, which caused the next read from that same stream to fail.

Generally we shouldn't close stream which we didn't create.
---
 .../cache/QuantizationCacheManager.java       | 25 +++++++++++++++----
 1 file changed, 20 insertions(+), 5 deletions(-)

diff --git a/src/main/java/azgracompress/cache/QuantizationCacheManager.java b/src/main/java/azgracompress/cache/QuantizationCacheManager.java
index 02c083a..0224eb7 100644
--- a/src/main/java/azgracompress/cache/QuantizationCacheManager.java
+++ b/src/main/java/azgracompress/cache/QuantizationCacheManager.java
@@ -349,17 +349,32 @@ public class QuantizationCacheManager {
      * @return Cache file or null, if exception occurs.
      */
     private static ICacheFile readCacheFileImpl(final InputStream inputStream) {
-        try (final DataInputStream dis = new DataInputStream(inputStream)) {
-            final CacheFileHeader header = new CacheFileHeader();
+        final DataInputStream dis;
+        if (inputStream instanceof DataInputStream) {
+            dis = (DataInputStream) inputStream;
+        } else {
+            dis = new DataInputStream(inputStream);
+        }
+
+        final CacheFileHeader header = new CacheFileHeader();
+        try {
             header.readFromStream(dis);
+        } catch (final IOException e) {
+            System.err.println("Failed to read CacheFileHeader from input stream");
+            e.printStackTrace();
+            return null;
+        }
 
-            final ICacheFile cacheFile = getCacheFile(header.getQuantizationType());
-            assert (cacheFile != null);
+        final ICacheFile cacheFile = getCacheFile(header.getQuantizationType());
+        assert (cacheFile != null);
+        try {
             cacheFile.readFromStream(dis, header);
-            return cacheFile;
         } catch (final IOException e) {
+            System.err.println("Failed to read cache file from input stream.");
+            e.printStackTrace();
             return null;
         }
+        return cacheFile;
     }
 
     /**
-- 
GitLab