2012年1月15日日曜日

jetty + jersey + Amazon Product Advertising APIのサンプル

●xsdからjarファイルの作成

 AmazonのAmazon Product Advertising APIを利用する際には、
jaxbでxmlをパースするためにクラスの定義が必要です。
ここでは、アマゾンの提供しているxsdからクラス定義を含むjarファイルを作成します。

まず、アマゾンからAWSECommerceService.xsd をダウンロードし、
src/main/resourcesに設置。

pom.xmlを下記のように追加。
maven-compiler-pluginは、1.5以上に設定する。

<groupId>test</groupId>
<artifactId>aws-test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>AWSECommerceService</name>

<dependencies>
<dependency>
      <groupId>javax.xml.bind</groupId>
      <artifactId>jaxb-api</artifactId>
      <version>2.2.6</version>
  </dependency> 
  </dependencies>
  <build>
      <plugins>
           <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>6</source>
                <target>6</target>
            </configuration>
      </plugin>
     <plugin>
          <groupId>org.jvnet.jaxb2.maven2</groupId>
          <artifactId>maven-jaxb22-plugin</artifactId>
          <version>0.8.0</version>
      </plugin> 
     </plugins>
  </build>

maven packageを実行すると、target以下にjarファイルが作成されます。
(著者は、target/generated-sources/xjc以下のjavaファイルをインポートして
利用しているのでjarが使用可能か未確認です。)


●signerの実装
2009年8月15日以降、Product Advertising APIは、リクエストに署名認証を含めなければならなくなりました。

下記にAmazonの提供している署名のサンプルがあります。
 Java Sample Code for Calculating Signature Version 2 Signatures


このサンプルのままでは、リクエストに改行が入ってしまって動かないので、
 76行目の
 Base64 encoder = new Base64();

  Base64 encoder = new Base64(0);
に変更する必要があります。

それと、日本での検索をしたい場合は、
 33行目 endpoint を "ecs.amazonaws.jp"に変更します。


 ●取得してみる
 作成したjar、signerをインポートしてjerseyを利用して検索結果をそのまま表示する
 サンプルを作ってみます。

src/main/java/gauuud/amazon/service/ItemSearchResource.java

package gauuud.amazon.service;

import java.util.HashMap;
import java.util.Map;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import com.amazon.associates.sample.SignedRequestsHelper;
import com.sun.jersey.api.client.Client;
import com.amazon.webservices.awsecommerceservice._2011_08_01.ItemSearchResponse;

@Path("/item_search")
@Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
public class ItemSearchResource {
    @GET
    public ItemSearchResponse get(String word) throws Exception {

        SignedRequestsHelper signer = new SignedRequestsHelper();
       
        Map map = new HashMap();
        map.put("Service","AWSECommerceService");
        map.put("Operation","ItemSearch");
        map.put("Version","2011-08-01");
        map.put("SearchIndex","Books");
        map.put("Keywords","java");
       
        map.put("AssociateTag","[アソシエートID]");
       
        String url = signer.sign(map);
       
        Client c = Client.create();           

        ItemSearchResponse result = c.resource(url).get(ItemSearchResponse.class);

        return result;
    }
}



pom.xml  //いらないものが過分に含まれています。

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>gauuud</groupId>
  <artifactId>aws-sample</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <name>aws-sample</name>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
  <dependency>
   <groupId>org.codehaus.jettison</groupId>
   <artifactId>jettison</artifactId>
   <version>1.3</version>
  </dependency>
  <dependency>
   <groupId>com.sun.jersey</groupId>
   <artifactId>jersey-core</artifactId>
   <version>1.11</version>
  </dependency>
  <dependency>
   <groupId>com.sun.jersey</groupId>
   <artifactId>jersey-client</artifactId>
   <version>1.11</version>
  </dependency>
  <dependency>
   <groupId>com.sun.jersey</groupId>
   <artifactId>jersey-server</artifactId>
   <version>1.11</version>
  </dependency>
  <dependency>
   <groupId>com.sun.jersey</groupId>
   <artifactId>jersey-servlet</artifactId>
   <version>1.11</version>
  </dependency>
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>servlet-api</artifactId>
   <version>2.5</version>
   <scope>provided</scope>
  </dependency>
  <dependency>
   <groupId>com.sun.jersey</groupId>
   <artifactId>jersey-json</artifactId>
   <version>1.11</version>
  </dependency>
  </dependencies>
  <build>
   <plugins>
      <plugin>
        <groupId>org.mortbay.jetty</groupId>
        <artifactId>jetty-maven-plugin</artifactId>
       <version>8.0.0.v20110901</version>
        <configuration>
          <scanIntervalSeconds>10</scanIntervalSeconds>
          <webAppSourceDirectory>${basedir}/webapp</webAppSourceDirectory>
          <webXmlFile>${basedir}/webapp/WEB-INF/web.xml</webXmlFile>
          <contextPath>/</contextPath>
          <connectors>
            <connector implementation="org.eclipse.jetty.server.nio.SelectChannelConnector">
              <port>8080</port>
              <maxIdleTime>60000</maxIdleTime>
            </connector> 
          </connectors>
          <systemProperties>
            <systemProperty>
              <name>org.apache.commons.logging.Log</name>
              <value>org.apache.commons.logging.impl.SimpleLog</value>
            </systemProperty>
          </systemProperties>
        </configuration>
      </plugin>      
      <plugin>
       <groupId>org.apache.maven.plugins</groupId>
       <artifactId>maven-compiler-plugin</artifactId>
   <configuration>
    <source>6</source>
    <target>6</target>
   </configuration>
      </plugin>
   </plugins>
  </build>
</project>
 
 
src/main/webapp/WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
 version="3.0">
 <display-name>aws-sample</display-name>
     <welcome-file-list>
      <welcome-file>index.html</welcome-file>
     </welcome-file-list>

 <servlet>
  <servlet-name>jersey</servlet-name>
  <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
  <init-param>
   <param-name>com.sun.jersey.config.property.packages</param-name>
   <param-value>gauuud.amazon.service</param-value>
  </init-param>
  
        <load-on-startup>10</load-on-startup>
 </servlet>

 <servlet-mapping>
  <servlet-name>jersey</servlet-name>
  <url-pattern>/rest/*</url-pattern>
 </servlet-mapping>
 
</web-app>

maven jettry:run
を実行して
localhost:8080/rest/search_item
にアクセスするとxmlが取得できるはず。