From d72a2bc805cba63f7680e04152601a7e9a8b826c Mon Sep 17 00:00:00 2001 From: jzl Date: Wed, 17 May 2023 02:06:13 +0800 Subject: [PATCH] Fix: workaround io error 'stream closed' caused by bugs in URLClassloader (#412) --- .../java/org/xerial/snappy/SnappyLoader.java | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/xerial/snappy/SnappyLoader.java b/src/main/java/org/xerial/snappy/SnappyLoader.java index 8f6e625d..f1d555cc 100644 --- a/src/main/java/org/xerial/snappy/SnappyLoader.java +++ b/src/main/java/org/xerial/snappy/SnappyLoader.java @@ -25,7 +25,9 @@ package org.xerial.snappy; import java.io.*; +import java.net.JarURLConnection; import java.net.URL; +import java.net.URLConnection; import java.util.Enumeration; import java.util.Properties; import java.util.UUID; @@ -235,7 +237,7 @@ private static File extractLibraryFile(String libFolderForCurrentOS, String libr InputStream reader = null; FileOutputStream writer = null; try { - reader = SnappyLoader.class.getResourceAsStream(nativeLibraryFilePath); + reader = getResourceAsInputStream(nativeLibraryFilePath); try { writer = new FileOutputStream(extractedLibFile); @@ -273,7 +275,7 @@ private static File extractLibraryFile(String libFolderForCurrentOS, String libr InputStream nativeIn = null; InputStream extractedLibIn = null; try { - nativeIn = SnappyLoader.class.getResourceAsStream(nativeLibraryFilePath); + nativeIn = getResourceAsInputStream(nativeLibraryFilePath); extractedLibIn = new FileInputStream(extractedLibFile); if (!contentsEquals(nativeIn, extractedLibIn)) { @@ -394,4 +396,16 @@ public static String getVersion() } return version; } + + private static InputStream getResourceAsInputStream(String resourcePath) throws IOException { + URL url = SnappyLoader.class.getResource(resourcePath); + URLConnection connection = url.openConnection(); + if (connection instanceof JarURLConnection) { + JarURLConnection jarConnection = (JarURLConnection) connection; + jarConnection.setUseCaches(false); // workaround for https://bugs.openjdk.org/browse/JDK-8205976 + return jarConnection.getInputStream(); + } else { + return connection.getInputStream(); + } + } }