Skip to content

Instantly share code, notes, and snippets.

@GeePawHill
Created June 13, 2021 19:02
Show Gist options
  • Select an option

  • Save GeePawHill/6ad3617399f61d48db23e74d8fa796d7 to your computer and use it in GitHub Desktop.

Select an option

Save GeePawHill/6ad3617399f61d48db23e74d8fa796d7 to your computer and use it in GitHub Desktop.
Humble Object Example
package org.geepawhill.rws
import java.io.*
import java.net.Socket
class SocketWrapper(val input: InputStream, val output: OutputStream, val machine: String) {
constructor(socket: Socket) : this(socket.getInputStream(), socket.getOutputStream(), socket.inetAddress.toString())
}
class Channel(socket: SocketWrapper, private val listener: Listener) : Talker, Runnable {
private val input: BufferedReader = BufferedReader(
InputStreamReader(
socket.input
)
)
private val output: PrintStream = PrintStream(socket.output, true)
init {
println("Channel: ${socket.machine}")
listener.birth(this)
println("Waiting for client...")
}
override fun run() {
try {
while (true) {
val message = input.readLine()
if (message != null) listener.hear(this, message)
break
}
} finally {
closeQuietly()
}
}
private fun closeQuietly() {
try {
listener.death(this)
input.close()
output.close()
} catch (ex: IOException) {
}
}
@Synchronized
override fun say(message: String) {
output.println(message)
}
}
package org.geepawhill.rws
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import java.io.ByteArrayOutputStream
class ChannelTest {
val listener = TestingListener()
val inputStream = "This is a string".byteInputStream()
val outputStream = ByteArrayOutputStream()
val socket = SocketWrapper(inputStream, outputStream, "TEST")
@Test
fun `gives birth message`() {
val channel = Channel(socket, listener)
assertThat(listener.talkers).containsExactly(channel)
}
@Test
fun `passes message on`() {
val channel = Channel(socket, listener)
channel.run()
assertThat(listener.messages).containsExactly(ReceivedSay(channel, "This is a string"))
}
@Test
fun `dies on eof`() {
// The input has one line, read during the run, and then has the same effect as the user closing the socket.
val channel = Channel(socket, listener)
channel.run()
assertThat(listener.talkers).isEmpty()
}
@Test
fun `says to output`() {
val channel = Channel(socket, listener)
channel.say("Hi mom!")
channel.run()
assertThat(outputStream.toByteArray()).isEqualTo("Hi mom!\r\n".toByteArray())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment