12.5.1 Webリソースクライアントの実装クラスを作成する(クライアントAPIを利用する)

RESTful Webサービス用クライアントAPIを利用するクライアントの実装クラスを作成します。

例を次に示します。

package com.sample.client;

import java.net.URI;
import java.net.URLEncoder;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;

import com.cosminexus.jersey.api.client.Client;
import com.cosminexus.jersey.api.client.WebResource;
import com.cosminexus.jersey.api.client.ClientRequest;
import com.cosminexus.jersey.api.client.ClientResponse;
import com.cosminexus.jersey.api.client.config.ClientConfig;
import com.cosminexus.jersey.api.client.config.DefaultClientConfig;
import com.cosminexus.jersey.api.client.ClientHandlerException;
import com.cosminexus.jersey.api.json.JSONConfiguration;
import javax.ws.rs.core.Cookie;

//サンプル:Webリソースのクライアントの実行
public class SampleClient {

   public static void main(String[] args) {
       
       final String HOST = args[0];
       final String PORT = args[1];
       
       SampleClient sampleClient = new SampleClient();
       
       try{
           sampleClient.demonstration13(HOST, PORT);
           sampleClient.demonstration14(HOST, PORT);
           sampleClient.demonstration15(HOST, PORT);
           
           System.out.println("¥n----- Successfully Ended -----");
           
       }catch(Exception e){
           //詳細な例外のメッセージを表示する
           System.out.println(e.getMessage());
       }
   }
   private void demonstration13(String HOST, String PORT) {

       System.out.println("¥n Demonstration 13 started.");
       System.out.println(" This demonstrates how to use Client API " +
               "to receive a response as a ClientResponse.");
       System.out.println(" This demonstrates usage of @Encoded at " +
               "@CookieParam. ¥n Automatic URI decoding should be disabled.");

       String url = null;
       Client client = null;
       ClientResponse response = null;

       String responseEntity = "";
       Map<String, List<String>> headers = null;
       int status;
       
       //Webリソースを呼び出す
       try {
           //呼び出す対象のWebリソースのURIを設定する
           url = new String("http://" + HOST + ":" + PORT+
                   "/tutorial/root/getCookieParam");
           Cookie cookie = new Cookie("cookie", "cookie%20value");
           //クライアントAPIを利用するため,Clientオブジェクトを生成する
           client = Client.create();
           //HTTPリクエストを作成して送信しHTTPレスポンスを受信する
           //- ClientオブジェクトからWebResourceオブジェクトを生成する
           //- Cookieヘッダに"cookie=cookie%20value"を設定する
           //- HTTP GETリクエストを送信しClientResponseとして
           //  HTTPレスポンスを受信する
           response = client.resource(url)
                            .cookie(cookie)
                            .get(ClientResponse.class);
           //HTTPレスポンスのヘッダを取得する
           headers = response.getHeaders();
           //HTTPレスポンスのステータスコードを取得する
           status = response.getStatus();
           //HTTPレスポンスのエンティティを取得する
           responseEntity = response.getEntity(String.class);
       }catch (Exception e) {
           System.out.println(" ERROR: " + e.getClass() + " was thrown. ");
           //スタックトレースを表示する
           e.printStackTrace();
           throw new RuntimeException(" Demonstration 13 failed.");
       }
       System.out.println(" The target URL is ¥"" + url + "¥".");
       System.out.println(" The HTTP method  is " + "¥"GET¥"" + ".");
       System.out.println(" Connection and interaction ended successfully.");
       
       //ステータスコードとエンティティの期待値を設定する
       int statusExpect = 200;
       String responseEntityExpect = "CookieParam: cookie%20value";
       
       //ステータスコードとエンティティが期待値と同じかチェックする
       if (status == statusExpect
               & responseEntity.equals(responseEntityExpect)) {
           //HTTPレスポンスのヘッダを表示する
           System.out.println(" Response headers are " + headers.toString() + ".");
           //HTTPレスポンスのエンティティを表示する
           System.out.println(" Response entity is " + responseEntity + ",");
           System.out.println(" which means target resource completed " +
                   "the process described above without any problem.");
           
           System.out.println(" Demonstration 13 ended successfully.");
       }else {
           System.out.println(" The response is not as expected.");
           throw new RuntimeException(" Demonstration 13 failed.");
       }
     
   }

   private void demonstration14(String HOST, String PORT) {

       System.out.println("¥n Demonstration 14 started.");
       System.out.println(" This demonstrates how to send a ClientRequest " +
               "and receive a ClientResponse by using " +
               "Client#handle(ClientRequest request).");
       System.out.println(" This demonstrates usage of @Consumes and " +
               "@Produces.");
       URI url = null;
       Client client = null;
       ClientRequest.Builder requestBuilder = null;
       ClientRequest request = null;
       ClientResponse response = null;

       String responseEntity = "";
       Map<String, List<String>> headers = null;
       int status;
       
       //Webリソースを呼び出す
       try {
           //呼び出す対象のWebリソースのURIを設定する
           url = new URI("http://" + HOST + ":" + PORT+ "/tutorial/root");
           //HTTPリクエストのエンティティを作成する
           String data = URLEncoder.encode("form", "UTF-8") + "="
               + URLEncoder.encode("formValue", "UTF-8");
           //クライアントAPIを利用するため,Clientオブジェクトを生成する
           client = Client.create();
           //ClientRequest.Builderオブジェクトを生成する
           requestBuilder = ClientRequest.create();
           //- HTTPリクエストの"Content-Type"ヘッダに
           //  "application/x-www-form-urlencoded"を設定する
           //- HTTPリクエストのエンティティを設定する
           requestBuilder.type("application/x-www-form-urlencoded")
                         .entity(data);
           //ClientRequest.BuilderからClientRequestを作成する
           request = requestBuilder.build(url, "POST");
           //Client#handle()メソッドを呼び出してHTTP POSTリクエストを送信し
           //ClientResponseとしてHTTPレスポンスを受信する
           response = client.handle(request);
           //HTTPレスポンスのヘッダを取得する
           headers = response.getHeaders();
           //HTTPレスポンスのステータスコードを取得する
           status = response.getStatus();
           //HTTPレスポンスのエンティティを取得する
           responseEntity = response.getEntity(String.class);
       }catch (ClientHandlerException e) {
           System.out.println(" ERROR: " + e.getClass() + " was thrown. ");
           //スタックトレースを表示する
           e.printStackTrace();
           throw new RuntimeException(" Demonstration 14 failed.");
       }catch (Exception e) {
           System.out.println(" ERROR: " + e.getClass() + " was thrown. ");
           //スタックトレースを表示する
           e.printStackTrace();
           throw new RuntimeException(" Demonstration 14 failed.");
       }
       System.out.println(" The target URL is ¥"" + url + "¥".");
       System.out.println(" The HTTP method  is " + "¥"POST¥"" + ".");
       System.out.println(" Connection and interaction ended successfully.");

       //ステータスコードとエンティティの期待値を設定する
       int statusExpect = 200;
       String responseEntityExpect = "<FormParam>formValue</FormParam>";

       //ステータスコードとエンティティが期待値と同じかチェックする
       if (status == statusExpect
               & responseEntity.equals(responseEntityExpect)) {
           //HTTPレスポンスのヘッダを表示する
           System.out.println(" Response headers are " + headers.toString() + ".");
           //HTTPレスポンスのエンティティを表示する
           System.out.println(" Response entity is " + responseEntity + ",");
           System.out.println(" which means target resource completed " +
                   "the process described above without any problem.");
           
           System.out.println(" Demonstration 14 ended successfully.");
       }else {
           System.out.println(" The response is not as expected.");
           throw new RuntimeException(" Demonstration 14 failed.");
       }
   
   }
   private void demonstration15(String HOST, String PORT) {

       System.out.println("¥n Demonstration 15 started.");
       System.out.println(" This demonstrates JSON support of CJR.");
       System.out.println(" This demonstrates POJO and JSON mapping.");

       String url = null;
       Client client = null;
       CustomType response = null;
       
       //Webリソースを呼び出す
       try {
           //呼び出す対象のWebリソースのURIを設定する
           url = new String("http://" + HOST + ":" + PORT +
                   "/tutorial/root/PojoJsonMapping");
           //JSON POJOマッピングを有効にする設定を行う
           ClientConfig cc = new DefaultClientConfig();
           cc.getFeatures()
             .put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
           //クライアントAPIを利用するため,Clientオブジェクトを生成する
           //(設定を有効にするためClientConfigオブジェクトを渡す)
           client = Client.create(cc);
           //CustomTypeオブジェクトを生成する
           CustomType record = new CustomType();
           record.setName("Old Record Name");
           List<Integer> grades = new ArrayList<Integer>();
           grades.add(1);
           grades.add(2);
           grades.add(3);
           record.setGrades(grades);
           //HTTPリクエストを作成する
           //- ClientオブジェクトからWebResourceオブジェクトを生成する
           //- Content-Typeヘッダに"application/json"を設定する
           //- エンティティにCustomTypeオブジェクトを設定する
           //- HTTP POSTリクエストを送信しCustomTypeとして
           //  HTTPレスポンスを受信する
           response = client.resource(url)
                            .type("application/json")
                            .entity(record)
                            .post(CustomType.class);
       }catch (Exception e) {
           System.out.println(" ERROR: " + e.getClass() + " was thrown. ");
           //スタックトレースを表示する
           e.printStackTrace();
           throw new RuntimeException(" Demonstration 15 failed.");
       }
       System.out.println(" The target URL is ¥"" + url + "¥".");
       System.out.println(" The HTTP method  is " + "¥"POST¥"" + ".");
       System.out.println(" Connection and interaction ended successfully.");

       //エンティティの期待値を設定する
       String responseNameExpect = "New Record Name";
       List<Integer> responseGradesExpect = new ArrayList<Integer>();
       responseGradesExpect.add(5);
       responseGradesExpect.add(6);
       responseGradesExpect.add(7);

       //エンティティが期待値と同じかチェックする
       if (response.getName().equals(responseNameExpect)
               & response.getGrades().equals(responseGradesExpect)) {
           //HTTPレスポンスのエンティティを表示する
           System.out.println(" Response is " + response.toString() + ",");
           System.out.println(" which means target resource completed " +
                   "the process described above without any problem.");
           
           System.out.println(" Demonstration 15 ended successfully.");
       }else {
           System.out.println(" The response is not as expected.");
           throw new RuntimeException(" Demonstration 15 failed.");
       }
   
   }
   private static class CustomType {
       
       private String name;
       private List<Integer> grade;
       
       public CustomType() {
       }
       
       public CustomType (String name, List<Integer> grades){
           this.name = name;
           this.grade = grades;
       }
       
       public String getName() {
           return name;
       }
       
       public void setName(String name) {
           this.name = name;
       }
       
       public List<Integer> getGrades() {
           return grade;
       }
       
       public void setGrades(List<Integer> grades) {
           this.grade = grades;
       }
       
       @Override
       public String toString() {
           return "Record [Name=" + name + ", Grades=" + grade.toString() + "]";
       }
       
   }
}

作成したSampleClient.javaは,UTF-8形式でc:¥temp¥jaxrs¥works¥tutorial¥client¥src¥com¥sample¥client¥ディレクトリに保存します。