diff --git a/jvm/src/main/scala/cs214/webapp/server/web/WebServer.scala b/jvm/src/main/scala/cs214/webapp/server/web/WebServer.scala index 27dffdd13502d076adeb832a396412ff76604c93..5906c37c26b5a1785b4b40f5ecea8b32b69686ca 100644 --- a/jvm/src/main/scala/cs214/webapp/server/web/WebServer.scala +++ b/jvm/src/main/scala/cs214/webapp/server/web/WebServer.scala @@ -4,18 +4,22 @@ package web import scala.collection.{concurrent, mutable} import scala.util.{Failure, Success, Try} +import scala.io.{Source} + import cask.endpoints.WsChannelActor +private def withResource[T](fname: String)(body: Option[Source] => T) = + Option(this.getClass.getResourceAsStream(f"/$fname")) match + case Some(stream) => + try body(Some(Source.fromInputStream(stream)(scala.io.Codec.UTF8))) + finally stream.close() + case None => body(None) + private case class Wordlist(fname: String): val words: Seq[String] = - import scala.io.{Source, Codec} - val wordstream = - Option(this.getClass.getResourceAsStream(f"/$fname")) - .getOrElse(sys.error(f"File not found: $fname")) - try - Source.fromInputStream(wordstream)(Codec.UTF8) - .getLines().map(_.split("\t").last).to(Vector) - finally wordstream.close() + withResource(fname): src => + src.getOrElse(sys.error(f"File not found: $fname")) + .getLines().map(_.split("\t").last).to(Seq) def randomWord: String = import scala.util.Random @@ -27,9 +31,8 @@ class TooManyInstances extends Exception("Too many instances.") object WebServer: val MAX_INSTANCES = 64000 - private val instanceIdsFileName = "eff_short_wordlist_1.txt" // Where to find the list of possible instance ids private val instanceIdLength = 4 // How many words do we concatenate for the instance id - private val instanceIdWords = Wordlist(instanceIdsFileName) + private val instanceIdWords = Wordlist("eff_short_wordlist_1.txt") private[web] val debug = false