hatenob

プログラムって分からないことだらけ

一人Web開発 Season.2~第4夜 HTTPサーバ探し~

HTTPで会話できるAPIコンテナを模索しておりまして、やはり馴染み深いJBossプロジェクトに落ち着きつつあり、とは言え今だAlphaのwildfly-swarmは使えないしあまりフルスタックなのは求めていない、という流れで、ひとまずJAX-RSスタンドアロンで実行できる環境としてRESTEasyのEmbedded Container(組込コンテナ)を試してみた。

Chapter 34. Embedded Containers

仕様

URLをたたくと「hello world」と返す例のやつです。

pom.xml

今回はjunitテストで動かしているので、mainで実行するならjunitは不要。Undertowは、coreとservletが必要。(最初、servletを入れていなくてコンパイルエラーになって少し詰まった)

 <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>io.undertow</groupId>
      <artifactId>undertow-core</artifactId>
      <version>1.3.9.Final</version>
    </dependency>
    <dependency>
      <groupId>io.undertow</groupId>
      <artifactId>undertow-servlet</artifactId>
      <version>1.3.9.Final</version>
    </dependency>

    <dependency>
      <groupId>org.jboss.resteasy</groupId>
      <artifactId>resteasy-undertow</artifactId>
      <version>3.0.13.Final</version>
    </dependency>

  </dependencies>

リソース

Applicationクラスと、実際にエンドポイントとなるリソースを作る。

@Path("hello")
public class Hello {
  @GET
  @Produces("text/plain")
  public String say() {
    return "hello world";
  }
}


@ApplicationPath("rs")
public class App extends Application {
  @Override
  public Set<Class<?>> getClasses() {
    HashSet<Class<?>> classes = new HashSet<>();
    classes.add(Hello.class);
    return classes;
  }
}

リソースは普通にJAX-RSで書いて、それをApplicationのgetClassesでSetに詰めて返してあげるよい模様。
複数のクラスがある場合はここで複数addすればいいんじゃないかな。

実行

今回はテストクラスとして実装したけれど、mainでやればプロセスが上がるはず。

public class HelloTest {
  private UndertowJaxrsServer server;

  @Before
  public void initClass() {
    server = new UndertowJaxrsServer().start();
    server.deploy(App.class);
  }

  @After
  public void stop() {
    server.stop();
  }

  @Test
  public void test_hello() throws Exception {
    Client client = ClientBuilder.newClient();
    String res = client.target(TestPortProvider.generateURL("/rs/hello"))
        .request().get(String.class);

    assertThat(res, is("hello world"));
    client.close();
  }
}

UndertowJaxrsServerを起動して、Applicationをdeployすればよいみたい。
これで組込コンテナが起動してREST APIのエンドポイントが起動する感じ。
サーバのポート番号とか諸々の設定までは見ていないけれど、これで最低限のAPI公開はできそう。
ただしmainにした場合はdependenciesも含めてjarにしてあげないと色々とめんどい。
これはmaven-assembly-pluginでできそうな予感。

少し進んだ。