Created
March 7, 2016 01:55
-
-
Save alancnet/68f6e787e1ab96bd1c4a to your computer and use it in GitHub Desktop.
Use Play Framework as a component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
libraryDependencies ++= Seq( | |
"org.scala-lang" % "scala-swing" % "2.11.0-M7", | |
"com.typesafe.play" %% "play" % "2.4.3", | |
"com.typesafe.play" %% "play-netty-server" % "2.4.3", | |
"org.scalaj" %% "scalaj-http" % "2.2.0" | |
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.File | |
import play.api.ApplicationLoader.Context | |
import play.api._ | |
import play.api.routing.Router | |
import play.core.server.{ServerConfig, NettyServer} | |
abstract class LocalWebServer { | |
val environment = new Environment( | |
new File("."), | |
getClass.getClassLoader, | |
play.api.Mode.Dev | |
) | |
val context = ApplicationLoader.createContext(environment) | |
def routes:Router.Routes | |
if (routes == null) throw new Exception("Routes is null") | |
val components = new BuiltInComponentsFromContext(context) { | |
override def router: Router = Router.from(routes) | |
} | |
val applicationLoader = new ApplicationLoader { | |
override def load(context: Context): Application = components.application | |
} | |
val application = applicationLoader.load(context) | |
Play.start(application) | |
private object CausedBy { | |
def unapply(e: Throwable): Option[Throwable] = Option(e.getCause) | |
} | |
private def startFindPort(port:Int): (Int, NettyServer) = { | |
try { | |
(port, NettyServer.fromApplication(application, ServerConfig(port = Some(port)))) | |
} catch { | |
case CausedBy(e : java.net.BindException) => { | |
startFindPort(port + 1) | |
} | |
} | |
} | |
val (port, server) = startFindPort(21000) | |
def stop() = server.stop() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment