View Javadoc

1   package com.melloware.jukes.ws;
2   
3   import java.util.ArrayList;
4   import java.util.HashMap;
5   import java.util.Map;
6   import java.util.Collection;
7   
8   import org.apache.commons.logging.Log;
9   import org.apache.commons.logging.LogFactory;
10  
11  import javax.xml.parsers.DocumentBuilder;
12  import javax.xml.parsers.DocumentBuilderFactory;
13  
14  import org.w3c.dom.Document;
15  import org.w3c.dom.Node;
16  import org.w3c.dom.NodeList;
17  
18  import com.melloware.jukes.util.MessageUtil;
19  import com.melloware.jukes.exception.WebServiceException;
20  import com.melloware.jukes.gui.tool.Resources;
21  
22  /**
23   * Static methods for performing web services calls to the Amazon E-Commerce Web
24   * Services application.
25   * <p>
26   * Copyright (c) 1999-2007 Melloware, Inc. <http://www.melloware.com>
27   * @author Emil A. Lefkof III <info@melloware.com>
28   * @version 4.0
29   * AZ Development 2010
30   */
31  
32  @SuppressWarnings("unchecked")
33  public final class AmazonSearch {
34     private static final Log LOG = LogFactory.getLog(AmazonSearch.class);
35  
36     // the sort order (orig-rel-date, artistrank, titlerank)
37     public static final String SORT_TITLE = "titlerank";
38     public static final String SORT_ARTIST = "artistrank";
39     public static final String SORT_DATE = "orig-rel-date";
40  
41     // the area to search amazon
42     private static final String SEARCH_INDEX = "Music";
43  
44     // the data to bring back
45     private static final String RG_IMAGES = "Images";
46     private static final String RG_ITEMS = "ItemAttributes";
47     private static final String RG_TRACKS = "Tracks";
48     
49     private static final String AWS_ACCESS_KEY_ID = "AKIAJWPLM2OQCW444Q5A"; //AZ Development Key
50  
51     /*
52      * Your AWS Secret Key corresponding to the above ID, as taken from the AWS
53      * Your Account page.
54      */
55     private static final String AWS_SECRET_KEY = "MrhTu2j6htEUEh+i1iLpJkuqwatnefZ+K3hI4hWf"; //AZ Development Key
56   
57     /**
58      * Default constructor. Private so no instantiation.
59      */
60     private AmazonSearch() {
61        super();
62     }
63    
64     /**
65      * Finds a collection of Amazon products by Disc Name.
66      * <p>
67      * @param aDiscTitle the name of the disc to search for
68      * @param endPoint one of the end-points, according to the region of interest
69      * @return a collection of AmazonItems matching the search criteria
70      * @throws WebServiceException if any error occurs querying the AmazonWebService
71      */
72     public static Collection findItemsByDisc(String aDiscTitle, String endPoint) throws WebServiceException {
73        return findItemsByArtistDiscSort("", aDiscTitle, endPoint, SORT_TITLE);
74     }
75  
76     /**
77      * Finds a collection of Amazon products by Artist Name.
78      * <p>
79      * @param aArtistName the name of the artist to search for
80      * @param endPoint one of the end-points, according to the region of interest
81      * @return a collection of AmazonItems matching the search criteria
82      * @throws WebServiceException if any error occurs querying the AmazonWebService
83      */
84     public static Collection findItemsByArtist(String aArtistName, String endPoint) throws WebServiceException {
85        return findItemsByArtistDiscSort(aArtistName, "", endPoint, SORT_TITLE);
86     }
87  
88     /**
89      * Finds a collection of Amazon products by artist and disc name.
90      * <p>
91      * @param aArtistName the name of the artist to search for
92      * @param aDiscTitle the name of the disc to search for
93      * @param endPoint one of the end-points, according to the region of interest    * @return a collection of AmazonItems matching the search criteria
94      * @throws WebServiceException if any error occurs querying the AmazonWebService
95      */
96     public static Collection findItemsByArtistDisc(String aArtistName, String aDiscTitle, String endPoint) throws WebServiceException {
97        return findItemsByArtistDiscSort(aArtistName, aDiscTitle, endPoint, SORT_TITLE);
98     }
99  
100    /**
101     * Finds a collection of Amazon products by artist and disc name.
102     * <p>
103     * @param aArtistName the name of the artist to search for
104     * @param aDiscTitle the name of the disc to search for
105     * @param endPoint one of the following end-points, according to the region you are interested in.
106     *      US: ecs.amazonaws.com
107     *      CA: ecs.amazonaws.ca
108     *      UK: ecs.amazonaws.co.uk
109     *      DE: ecs.amazonaws.de
110     *      FR: ecs.amazonaws.fr
111     *      JP: ecs.amazonaws.jp 
112     * @param aSort what field to sort by
113     * @return a collection of AmazonItems matching the search criteria
114     * @throws WebServiceException if any error occurs querying the AmazonWebService
115     */
116    public static Collection findItemsByArtistDiscSort(String aArtistName, String aDiscTitle, String endPoint, String aSort)
117             throws WebServiceException {
118       if (LOG.isDebugEnabled()) {
119          LOG.debug("Amazon findItemsByArtistDiscSort: " + aArtistName + " - " + aDiscTitle + " - " + aSort);
120       }
121 
122       SignedRequestsHelper helper;
123       String requestUrl = null;
124       Collection collection = null;
125 
126       try {
127     	  helper = SignedRequestsHelper.getInstance(endPoint, AWS_ACCESS_KEY_ID, AWS_SECRET_KEY); 
128           //request parameters are stored in a map.
129           Map<String, String> params = new HashMap<String, String>();
130           params.put("Service", "AWSECommerceService");
131           params.put("Version", "2009-03-31");
132           params.put("Operation", "ItemSearch");
133           params.put("SearchIndex", SEARCH_INDEX);
134           params.put("Artist", aArtistName);
135           params.put("Title", aDiscTitle);
136           params.put("ResponseGroup", RG_IMAGES + "," + RG_ITEMS + "," + RG_TRACKS);
137           params.put("Sort", aSort);
138 
139           requestUrl = helper.sign(params);
140           DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
141           DocumentBuilder db = dbf.newDocumentBuilder();
142           Document doc = db.parse(requestUrl);
143           //Find error messages in Amazon response
144           NodeList errorList = doc.getElementsByTagName("Error");
145           String errorMessage = null;
146           if (errorList.getLength() != 0) {
147         	  Node n = errorList.item(0);
148         	  final NodeList nList = n.getChildNodes();
149 		      if (nList.getLength() != 0) {
150 		    	  for (int i=0; i<nList.getLength(); i=i+1){
151 		    		  Node node = nList.item(i);	
152 		    		  if (node.getNodeName().equalsIgnoreCase("Message")) {
153 		    			 errorMessage = node.getTextContent();  
154 		    		  }
155 		    	  }
156 		      }	
157 		    MessageUtil.showInformation(null, Resources.getString("label.AmazonResponse") + errorMessage);   
158           } else {
159           //Find Items in Amazon response 	  
160           NodeList nodeList = doc.getElementsByTagName("Item");
161           if (nodeList.getLength()==0) {
162         	  MessageUtil.showInformation(null, Resources.getString("messages.NoItemsFound"));  
163           }
164          //Loads a collection with AmazonItems from an Item node-list
165          collection = loadItems(nodeList);
166          }
167       } catch (NullPointerException e) {
168           LOG.error(e.getMessage(), e);
169           throw new WebServiceException(e); 
170       } catch (Exception ex) {
171          LOG.error(ex.getMessage(), ex);
172          throw new WebServiceException(ex);
173       } 
174 
175       return collection;
176    }
177 
178    /**
179     * Loads a collection with AmazonItems from an Item node-list of AWS-response.
180     * <p>
181     * @param aItems the items to load
182     * @return a collection of AmazonItem objects or an empty collection
183     */
184    private static Collection loadItems(NodeList aItems) {
185       ArrayList collection = new ArrayList();
186     if (aItems != null) {
187         for (int i=0; i<aItems.getLength(); i=i+1){
188             collection.add(new AmazonItem(aItems.item(i)));
189          }
190       }
191       return collection;
192    }
193 
194 }