[sbt]DropwizardフレームワークをScalaで動かしてみる

2014.01.15

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

Scala + sbtでDropwizard

ここではDropWizardというフレームワークをJavaで動かしてみましたが、Scalaで実装し、sbtでビルドすることもできます。
DropWizard + Scalaのサンプルがここにありますので、これを参考に動かしてみましょう。

環境構築方法

今回使用した動作環境は以下のとおりです。

  • OS : MacOS X 10.9
  • Java : 1.7.0_45

まだインストールしていなければ、sbtとgiter8をHomebrewでインストールします。

% brew install sbt giter8

sbtプロジェクト作成

最近はgiter8テンプレートはここで探すようです。
今回はシンプルなプロジェクトでいいので、「basic-scala-project」を指定してsbtプロジェクトのひな形を作成します。
下記コマンドを実行すると、プロジェクト名などいくつか聞かれますので、適当に回答しましょう。

% g8 pmandera/basic-scala-project
% cd path/your/scala-project
% sbt

もしEclipseでscalaファイルを編集する場合、pluginを追加してsbtpプロジェクトをeclipse対応させます。
projectディレクトリにplugins.sbtファイルを作成し、下記記述を追加します。

addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "2.4.0")

設定ファイルを読み込み直し、eclipseコマンドを実行します。
その後Eclipseからプロジェクトをimportしましょう。

> reload
> eclipse

Dropwizardを使用するための設定を追加

sbtを使ってjarファイルを作成するため、sbt-assemblyプラグインを追加します。
projectディレクトリにassembly.sbtファイルを作成し、下記内容を記述します。

addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.10.2")

build.sbtでビルド用設定も修正します。
importとlibraryDependencies、assemblySettingsの記述を追加しましょう。

import AssemblyKeys._ 

name := "MyScalaProject"

organization := "com.example"

version := "0.0.1"

scalaVersion := "2.10.3"

libraryDependencies ++= Seq(
  "org.specs2" %% "specs2" % "2.3.7" % "test",
  "com.massrelevance" %% "dropwizard-scala" % "0.6.2-1"
)

scalacOptions in Test ++= Seq("-Yrangepos")

// Read here for optional dependencies:
// http://etorreborre.github.io/specs2/guide/org.specs2.guide.Runners.html#Dependencies

resolvers ++= Seq("snapshots", "releases").map(Resolver.sonatypeRepo)

initialCommands := "import com.example.myscalaproject._"

assemblySettings

プログラムの修正

設定ができたらプログラムの修正を行います。
すでにHelloWorld.scalaがあるはずなので、全部このファイルに必要なオブジェクトをまとめて書いてしまいましょう。

package com.example.myscalaproject

import com.yammer.dropwizard.ScalaService
import com.yammer.dropwizard.config.{ Configuration, Environment }
import com.fasterxml.jackson.annotation.JsonProperty
import java.util.concurrent.atomic.AtomicLong
import javax.ws.rs.{ Path, Produces, GET, QueryParam }
import com.yammer.metrics.annotation.Timed
import org.hibernate.validator.constraints.NotEmpty
import com.sun.jersey.spi.container.servlet.ServletContainer
import com.yammer.dropwizard.config.Bootstrap
import com.yammer.dropwizard.bundles.ScalaBundle

object App extends ScalaService[ExampleConfiguration] {

  def initialize(bootstrap: Bootstrap[ExampleConfiguration]) {
    bootstrap.setName("example")
    bootstrap.addBundle(new ScalaBundle)
  }

  def run(configuration: ExampleConfiguration, environment: Environment) {
    environment.addResource(new ExampleResource(configuration.defaultName, configuration.template))
  }

}

class ExampleConfiguration extends Configuration {
  @NotEmpty
  @JsonProperty
  val defaultName: String = "Hans"

  @NotEmpty
  @JsonProperty
  val template: String = "Hello %s"
}

@Path("/hello-world")
@Produces(Array("application/json"))
class ExampleResource(val defaultName: String, val template: String) {
  val counter = new AtomicLong(0)

  @GET
  @Timed
  def sayHello(@QueryParam("name") name: Option[String]): String = {
    counter.incrementAndGet()
    return String.format(template, name.getOrElse(defaultName))
  }
}

ファイルを修正したらassemblyコマンドでjarファイルを作成します。

>assembly
・
・

targetディレクトリ以下にjarファイルが作成されるので、前と同じく実行しましょう、
今回はymlファイルを使用していないので、指定する必要はありません。

% java -jar target/scala-2.10/MyScalaProject-assembly-0.0.1.jar server

アプリ起動後、http://localhost:8080/hello-worldにブラウザでアクセスすると文字列が返されます。

まとめ

Scala + sbtでもJava + Mavenのときと同じように、簡単にアプリの作成ができました。
Mavenよりsbtのほうが簡単に設定できる感じがしますね。
Dropwizardはどれでも問題なく使用できるので、お好みのビルドツールを使用してください。

参考サイトなど