From 77604d40785847b775155c0e75b663a3c7336aa3 Mon Sep 17 00:00:00 2001 From: oSumAtrIX Date: Mon, 18 Jul 2022 01:13:14 +0200 Subject: [PATCH] fix: close stream when closing `DomFileEditor` --- .../revanced/patcher/data/impl/ResourceData.kt | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/src/main/kotlin/app/revanced/patcher/data/impl/ResourceData.kt b/src/main/kotlin/app/revanced/patcher/data/impl/ResourceData.kt index 573cd0aa..b5296f6a 100644 --- a/src/main/kotlin/app/revanced/patcher/data/impl/ResourceData.kt +++ b/src/main/kotlin/app/revanced/patcher/data/impl/ResourceData.kt @@ -26,17 +26,24 @@ class ResourceData(private val resourceCacheDirectory: File) : Data, Iterable) : Closeable { +class DomFileEditor internal constructor( + private val inputStream: InputStream, + private val outputStream: Lazy, +) : Closeable { + val file: Document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream) + .also(Document::normalize) // lazily open an output stream // this is required because when constructing a DomFileEditor the output stream is created along with the input stream, which is not allowed // the workaround is to lazily create the output stream. This way it would be used after the input stream is closed, which happens in the constructor constructor(file: File) : this(file.inputStream(), lazy { file.outputStream() }) - val file: Document = - DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream).also(Document::normalize) + override fun close() { + val result = StreamResult(outputStream.value) + TransformerFactory.newInstance().newTransformer().transform(DOMSource(file), result) - override fun close() = - TransformerFactory.newInstance().newTransformer().transform(DOMSource(file), StreamResult(outputStream.value)) + inputStream.close() + outputStream.value.close() + } }