JavaEE 7をやってみよう。 JAX-RS その7
その6の続き。
前回スキーマファイルから自動生成したJavaファイルをRESTのプロジェクトに取り込み、
出力結果を確認してみる。
Javaクラスが変更されているため、RESTのリソースクラスにも変更が必要となり、
下記のように書き換えた。
- リソースクラス
- もともと結果出力用のオブジェクトを設定する際、
CatalogクラスにListのフィールドがあったのだが、
これがListのラッパークラスに変わっているので、
そのあたりの処理を手直ししてやる。
なお、本来、オブジェクトの生成には、自動生成されたObjectFactoryを使うのが筋だが、
面倒なので直接Newしている。
package jaxrs; import java.util.ArrayList; import java.util.List; import javax.enterprise.context.RequestScoped; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import jaxrs.bean.Catalog; import jaxrs.bean.WarShip; import jaxrs.bean.WarShipList; import org.apache.commons.lang.StringUtils; import org.jboss.resteasy.annotations.providers.jaxb.Formatted; @RequestScoped @Path("ship") public class ShipResource { @GET @Produces("text/plain") public String getText() { return "This is user!"; } @GET @Produces("text/plain") @Path("/{shipid}") public String getUserInfoText(@PathParam("shipid") String shipId) { return "Your ID is " + shipId + "."; } @POST @Produces({"application/xml;charset=UTF-8"}) @Consumes({"application/json;charset=UTF-8"}) @Path("/list") @Formatted public Catalog getShipListJson(WarShip args) { Catalog cat = new Catalog(); List<WarShip> shipList = new ArrayList<WarShip>(); if (StringUtils.equals("D", args.getType())) { shipList.add(getWarShip("駆逐艦", "睦月")); shipList.add(getWarShip("駆逐艦", "如月")); shipList.add(getWarShip("駆逐艦", "皐月")); shipList.add(getWarShip("駆逐艦", "文月")); shipList.add(getWarShip("駆逐艦", "三日月")); } else { shipList.add(getWarShip("軽巡洋艦", "球磨")); shipList.add(getWarShip("軽巡洋艦", "多摩")); shipList.add(getWarShip("軽巡洋艦", "北上")); shipList.add(getWarShip("軽巡洋艦", "大井")); shipList.add(getWarShip("軽巡洋艦", "木曽")); } WarShipList warShipList = new WarShipList(); warShipList.getWarShip().addAll(shipList); cat.setWarShipList(warShipList); return cat; } private WarShip getWarShip(String type, String name) { WarShip ship = new WarShip(); ship.setName(name); ship.setType(type); return ship; } }
これを実行してみると、今度は想定通りの結果が得られた。
リクエストパラメータの値にtype = "D"を設定しても正しく結果が得られた。
少し物足りないので、JSONでも結果を返せるように書きなおしてみる。
といってもリソースクラスの@ProducesアノテーションにJSONのメディアタイプを追加するだけですむ。
@POST @Produces({"application/xml;charset=UTF-8","application/json;charset=UTF-8"}) @Consumes({"application/json;charset=UTF-8"}) @Path("/list") @Formatted public Catalog getShipListJson(WarShip args) { 〜〜省略〜〜 }
サーパを再起動した後、JMeterで確認をするのだが、
利用可能なメディアタイプとしてJSONのみを受け入れるように、
JMeterのHTTPヘッダマネージャに条件を追記する。
利用可能なメディアタイプは、"Accept"で指定する。
利用可能な文字コードを限定する場合は"Accept-charset"で文字コードを指定する。
ここでは、JSONで文字コードはUTF-8を指定している。
この状態で実行すると、JSONで結果が得られる。
ヘッダマネージャのAcceptの値を"application/xml"にすれば、
元にようにxmlでも結果を得ることができる。
Httpヘッダにはもっと項目があるので、HTTPの仕様を見ておくと良いかもしれない。
といったところで、JAX-RSの回は終わりとする。