Skip to content

Commit

Permalink
Fix DelegateReader: Close the delegate reader only if it has not been…
Browse files Browse the repository at this point in the history
… created yet

This avoids swallowing exceptions in cases when the creation of the delegate reader will consume the entire contents of the inner reader, and close it. In that case a client of the delegate reader will call "close" which would trigger the creation of the delegate reader again, but the inner reader is already closed at that point, reporting IOException "stream closed" and hiding the original exception.
  • Loading branch information
Till Krullmann committed Nov 9, 2021
1 parent cf4cd3a commit ad7a652
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,25 @@ import java.nio.CharBuffer
/**
* Implementation of [FilterReader] that delegates all [Reader] methods to another reader.
*/
@Suppress("LeakingThis")
abstract class DelegateReader(input: Reader) : FilterReader(input) {

/**
* Creates the delegate [Reader].
*
* @param input the input [Reader]
* @return the delegate [Reader]
*/
protected abstract fun createDelegateReader(input: Reader): Reader

private val lazyDelegate = lazy(LazyThreadSafetyMode.NONE) {
createDelegateReader(`in`)
}

/**
* The delegate [Reader].
*/
protected abstract val delegate: Reader
private val delegate: Reader by lazyDelegate


override fun read(): Int =
Expand Down Expand Up @@ -52,6 +65,11 @@ abstract class DelegateReader(input: Reader) : FilterReader(input) {
delegate.reset()


override fun close() =
delegate.close()
override fun close() {
if (lazyDelegate.isInitialized()) {
delegate.close()
} else {
`in`.close()
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@ package org.unbrokendome.gradle.pluginutils.io
import groovy.text.SimpleTemplateEngine
import org.gradle.api.file.ContentFilterable
import org.unbrokendome.gradle.pluginutils.io.DelegateReader
import java.io.Reader
import java.io.StringReader
import java.io.StringWriter
import java.io.*


/**
Expand Down Expand Up @@ -43,18 +41,17 @@ internal class SimpleTemplateEngineFilterReader(
var properties: Map<String, *> = emptyMap<String, Any?>()
var escapeBackslash: Boolean = false

override fun createDelegateReader(input: Reader): Reader {

override val delegate: Reader by lazy(LazyThreadSafetyMode.NONE) {

val template = `in`.use { input ->
val template = input.buffered().use {
val engine = SimpleTemplateEngine()
engine.isEscapeBackslash = escapeBackslash
engine.createTemplate(input)
engine.createTemplate(it)
}

val writer = StringWriter()
template.make(properties).writeTo(writer)

StringReader(writer.toString())
return StringReader(writer.toString())
}
}

0 comments on commit ad7a652

Please sign in to comment.