11
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Spark FrameworkをGroovyで動かす

Last updated at Posted at 2015-03-03

Spark」はJavaで書かれたSinatraライクなWebフレームワーク。
Java8で導入されたラムダ式を取り入れてシンプルな記述でサービスが作成できる。

Groovyのクロージャを、ラムダ式が期待される部分に当て嵌めたところ、期待通りに動いたのでここに記録する。

  • Gradle 2.3
  • Java 1.8.0_11
  • Groovy 2.4.1
初期設定
$ mkdir SparkGroovyExample
$ cd SparkGroovyExample
$ gradle init --type groovy-library

build.gradleを編集。
dependenciesにsparkを追加。
"gradlew run"が使いたかったので、applicationプラグインを追加し、mainClassNameを指定している。

build.gradle
apply plugin: 'groovy'
apply plugin: 'application'

mainClassName = 'ExampleService' // パッケージ名も必要に応じて指定 foo.bar.ExampleService等

repositories {
    jcenter()
}

dependencies {
    compile 'org.codehaus.groovy:groovy-all:2.4.0'

    testCompile 'org.spockframework:spock-core:0.7-groovy-2.0'
    testCompile 'junit:junit:4.12'

    compile 'com.sparkjava:spark-core:2.1'
}

build.gradleの、mainClassNameで指定したクラスにmainメソッドを記述する。

ExampleService.groovy
import static spark.Spark.*
import groovy.json.JsonBuilder

class ExampleService {
    public static void main(String[] args) {

        Object.metaClass.asJson = {
            def builder = new JsonBuilder(delegate);
            builder.toString()
        }

        def obj = new A();

        def map = [:]
        map['foo'] = 'Hello!!!'
        map['bar'] = [1, 2, 3]
        map['boo'] = ['hoge' : 'aaa', 'fuga' : [1, 2, ['obj':obj]]]

        get('/obj', { req, res -> obj.asJson() })
        get('/map', { req, res -> map.asJson() })

    }
}

MapとObjectでJSONシリアライズの様子を確認するために適当なクラスを定義。

A.groovy
class A {
    def x = 1
    def y = 'qwerty'
    def z = ['a':1, 'b': [111, 222, 333]]
}

実行。

実行
$ ./gradlew run

:compileJava UP-TO-DATE
:compileGroovy UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:run
[Thread-1] INFO spark.webserver.SparkServer - == Spark has ignited ...
[Thread-1] INFO spark.webserver.SparkServer - >> Listening on 0.0.0.0:4567
[Thread-1] INFO org.eclipse.jetty.server.Server - jetty-9.0.2.v20130417
[Thread-1] INFO org.eclipse.jetty.server.ServerConnector - Started ServerConnector@4a92881d{HTTP/1.1}{0.0.0.0:4567}
> Building 80% > :run

Webブラウザなどから、http://localhost:4567/objhttp://localhost:4567/map にリクエスト。

レスポンス1
http://localhost:4567/obj

{"z":{"a":1,"b":[111,222,333]},"y":"qwerty","x":1}
レスポンス2
http://localhost:4567/map

{"foo":"Hello!!!","bar":[1,2,3],"boo":{"hoge":"aaa","fuga":[1,2,{"obj":{"z":{"a":1,"b":[111,222,333]},"y":"qwerty","x":1}}]}}

クロージャの振る舞い、JSONの返り値は期待通り。
ゴテゴテした記述がなく、サックリ動いたのは好印象。

11
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?