Skip to content

Commit

Permalink
fix: DomFileEditor opening in- and output streams on the same file
Browse files Browse the repository at this point in the history
  • Loading branch information
oSumAtrIX committed Jul 2, 2022
1 parent 79d70cf commit 83187c9
Showing 1 changed file with 8 additions and 4 deletions.
12 changes: 8 additions & 4 deletions src/main/kotlin/app/revanced/patcher/data/impl/ResourceData.kt
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,23 @@ class ResourceData(private val resourceCacheDirectory: File) : Data, Iterable<Fi

inner class XmlFileHolder {
operator fun get(inputStream: InputStream, outputStream: OutputStream) =
DomFileEditor(inputStream, outputStream)
DomFileEditor(inputStream, lazyOf(outputStream))

operator fun get(path: String) = DomFileEditor(this@ResourceData[path])
}
}

class DomFileEditor internal constructor(inputStream: InputStream, private val outputStream: OutputStream) : Closeable {
constructor(file: File) : this(file.inputStream(), file.outputStream())
class DomFileEditor internal constructor(inputStream: InputStream, private val outputStream: Lazy<OutputStream>) : Closeable {

// 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() =
TransformerFactory.newInstance().newTransformer().transform(DOMSource(file), StreamResult(outputStream))
TransformerFactory.newInstance().newTransformer().transform(DOMSource(file), StreamResult(outputStream.value))

}

0 comments on commit 83187c9

Please sign in to comment.