Skip to content

Commit

Permalink
iss #24: use universal config in webapp
Browse files Browse the repository at this point in the history
  • Loading branch information
maizy committed Feb 3, 2017
1 parent 7a9c43a commit bf7308d
Show file tree
Hide file tree
Showing 24 changed files with 225 additions and 218 deletions.
6 changes: 3 additions & 3 deletions ambient7-webapp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@

```
cd ambient7/
sbt '~ambient7WebApp/jetty:start'
sbt 'ambient7WebApp/run --config=config/ambient7.conf'
```

or with additional settings:
```
sbt -Dconfig.file=/path/application.conf -Dlogback.configurationFile=src/etc/logback.dev.xml \
'~ambient7WebApp/jetty:start'
sbt -Dlogback.configurationFile=ambient7-webapp/src/etc/logback.dev.xml \
'ambient7WebApp/run --config=config/ambient7.conf'
```

Open [http://localhost:22480/](http://localhost:22480/) in your browser.
Expand Down
21 changes: 0 additions & 21 deletions ambient7-webapp/src/main/resources/application.conf

This file was deleted.

6 changes: 3 additions & 3 deletions ambient7-webapp/src/main/scala/ScalatraBootstrap.scala
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,17 @@

import org.scalatra._
import javax.servlet.ServletContext
import ru.maizy.ambient7.webapp.bootstrap.{ AppConfigInit, ScalikeJdbcInit }
import ru.maizy.ambient7.webapp.WebAppLauncher
import ru.maizy.ambient7.webapp.bootstrap.ScalikeJdbcInit
import ru.maizy.ambient7.webapp.servlet.{ Co2ReportServlet, DevicesServlet, RootServlet }

class ScalatraBootstrap
extends LifeCycle
with ScalikeJdbcInit
with AppConfigInit
{

override def init(context: ServletContext): Unit = {
val appConfig = loadAppConfig()
val appConfig = WebAppLauncher.options
setupDbConnectionPool(appConfig)
context.mount(new Co2ReportServlet(appConfig), "/co2_report")
context.mount(new DevicesServlet(appConfig), "/devices")
Expand Down

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,52 @@ package ru.maizy.ambient7.webapp
* See LICENSE.txt for details.
*/

import ru.maizy.ambient7.core.config.reader.{ MainDbConfigReader, UniversalConfigReader }
import ru.maizy.ambient7.core.config.{ Ambient7Options, WebAppSpecificOptions }
import ru.maizy.ambient7.core.config.reader.{ DevicesConfigReader, MainDbConfigReader, UniversalConfigReader }

object WebAppConfigReader
extends UniversalConfigReader
with MainDbConfigReader
with DevicesConfigReader
{
import UniversalConfigReader._

val DEFAULT_PORT = 22480

private def webAppOpts(opts: Ambient7Options)(
save: WebAppSpecificOptions => WebAppSpecificOptions): Ambient7Options =
{
val currentOpts = opts.webAppSpecificOptions.getOrElse(WebAppSpecificOptions())
opts.copy(webAppSpecificOptions = Some(save(currentOpts)))
}

override def appName: String = "java -jar ambient7-webapp.jar"

override def fillReader(): Unit = {
fillConfigOptions(requireConfig = true)
fillDbOptions()
fillDevicesOptions()

cliParser.opt[Int]("port")
.abbr("p")
.valueName(s"<$DEFAULT_PORT>")
.action { (value, opts) => webAppOpts(opts)(_.copy(port = value)) }
.text(s"web app listen port")

appendSimpleOptionalConfigRule[Int]("webapp.port") { (value, opts) =>
webAppOpts(opts)(_.copy(port = value))
}

appendCheck { opts =>
if (opts.webAppSpecificOptions.isEmpty) {
failure("webapp options are required")
} else if (opts.webAppSpecificOptions.exists(_.port <= 0)) {
failure("webapp port should be positive int")
} else {
success
}
}
}

fillReader()
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,26 +5,52 @@ package ru.maizy.ambient7.webapp
* See LICENSE.txt for details.
*/

import scala.util.{ Try, Failure, Success }
import org.eclipse.jetty.server.Server
import org.eclipse.jetty.servlet.DefaultServlet
import org.eclipse.jetty.webapp.WebAppContext
import org.scalatra.servlet.ScalatraListener
import ru.maizy.ambient7.core.config.{ Ambient7Options, ParsingError }

object WebAppLauncher extends App {

val config = WebAppConfigReader
config.fillReader()
val eitherAppConfig = config.readAppConfig(args.toIndexedSeq)
// TODO: how to send options to servlet context
private var _options: Option[Ambient7Options] = None

val eitherAppConfig = WebAppConfigReader.readAppConfig(args.toIndexedSeq)

eitherAppConfig match {
case Left(parsingError) =>
// TODO: extract to core
val sep = "\n * "
val errors = if (parsingError.messages.nonEmpty) {
s"Errors:$sep${parsingError.messages.mkString(sep)}\n"
} else {
""
webAppLogger.error(ParsingError.formatErrorsForLog(parsingError))
Console.err.println(ParsingError.formatErrorsAndUsage(parsingError))

case Right(opts) if opts.webAppSpecificOptions.isDefined =>
_options = Some(opts)

val port = opts.webAppSpecificOptions.map(_.port).getOrElse(WebAppConfigReader.DEFAULT_PORT)
val server = new Server(port)
val context = new WebAppContext()
context setContextPath "/"
context.setResourceBase("src/main/webapp")
context.addEventListener(new ScalatraListener)
context.addServlet(classOf[DefaultServlet], "/")

server.setHandler(context)

Try(server.start()) match {
case Success(_) => server.join()
case Failure(e) =>
webAppLogger.error("unable to launch jetty server", e)
server.stop()
}
val usage = parsingError.usage.map(u => s"Usage: $u").getOrElse("")
val userResult = List(errors, usage).filterNot(_ == "").mkString("\n")
Console.err.println(userResult)
case Right(opts) =>
println(s"Success: $opts")

case _ => webAppLogger.error("unknown error on launching webapp")
}

// TODO: launch jetty app (merge with JettyLauncher)
def options: Ambient7Options = {
_options match {
case None => throw new RuntimeException("options haven't loaded yet")
case Some(opts) => opts
}
}
}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,27 @@ package ru.maizy.ambient7.webapp.bootstrap

import com.typesafe.scalalogging.LazyLogging
import scalikejdbc.{ ConnectionPool, ConnectionPoolSettings }
import ru.maizy.ambient7.webapp.AppConfig
import ru.maizy.ambient7.core.config.Ambient7Options

trait ScalikeJdbcInit extends LazyLogging {

def setupDbConnectionPool(config: AppConfig): ConnectionPool = {
def setupDbConnectionPool(opts: Ambient7Options): ConnectionPool = {
logger.info("setup scalike jdbc connection pool")

if (opts.mainDb.isEmpty || opts.mainDb.exists(_.url.isEmpty)) {
throw new RuntimeException("main db options missing")
}

val dbOptions = opts.mainDb.get

Class.forName("org.h2.Driver")

val settings = ConnectionPoolSettings(
initialSize = 2
)

// TODO: use exlicit named connection
ConnectionPool.singleton(config.dbUrl, config.dbUser, config.dbPassword, settings)
ConnectionPool.singleton(dbOptions.url.get, dbOptions.user, dbOptions.password, settings)
ConnectionPool.get()
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package ru.maizy.ambient7

/**
* Copyright (c) Nikita Kovaliov, maizy.ru, 2017
* See LICENSE.txt for details.
*/

import com.typesafe.scalalogging.Logger

package object webapp {
val webAppLogger = Logger("ru.maizy.ambient7.webapp")
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,16 @@ package ru.maizy.ambient7.webapp.servlet
import java.time.ZonedDateTime
import scalikejdbc._
import spray.json.{ JsNumber, JsObject, JsString, JsValue, pimpAny }
import ru.maizy.ambient7.core.config.Ambient7Options
import ru.maizy.ambient7.core.data.Co2Device
import ru.maizy.ambient7.rdbms.Co2Service
import ru.maizy.ambient7.webapp.servlet.helper.{ AppConfigSupport, DateParamsSupport, DeviceParamSupport }
import ru.maizy.ambient7.webapp.servlet.helper.{ AppOptionsSupport, DateParamsSupport, DeviceParamSupport }
import ru.maizy.ambient7.webapp.servlet.helper.{ PrimitiveParamsSupport, SprayJsonSupport, TimeZoneSupport }
import ru.maizy.ambient7.webapp.{ Ambient7WebAppStack, AppConfig }
import ru.maizy.ambient7.webapp.Ambient7WebAppStack

class Co2ReportServlet(val appConfig: AppConfig)
class Co2ReportServlet(val appOptions: Ambient7Options)
extends Ambient7WebAppStack
with AppConfigSupport
with AppOptionsSupport
with DateParamsSupport
with PrimitiveParamsSupport
with DeviceParamSupport
Expand Down
Loading

0 comments on commit bf7308d

Please sign in to comment.