Recipe 27.6 Creating a JavaBean to Connect with Amazon


Problem

You want to create a JavaBean as a type of Amazon search utility class.

Solution

Set up your Amazon API as described in Recipe 27.5, then code a JavaBean that uses the com.amazon.soap.axis package from this API.

Discussion

The JavaBean in Example 27-5, named AmazonBean , imports the com.amazon.soap.axis package. This package is stored in amazonapi.jar , which (generated by Recipe 27.5). Store the JAR in the web application's WEB-INF/lib directory and the AmazonBean in WEB-INF/classes (or also in a JAR in WEB-INF/ lib).

Example 27-5 connects with Amazon in its getSearchResults( ) method. The AmazonBean formats and displays the search results in structureResults( ) . The code comments describe what's going on in detail.

Example 27-5. A JavaBean class that searches Amazon
 package com.jspservletcookbook;  import java.net.URL;            import com.amazon.soap.axis.*; public class AmazonBean {     //The developer's token     private final static String AMAZON_KEY = "DCJEAVDSXVPUD";  //NOTE: AWS Version 3 uses "http://xml.amazon.com/xml3"     private final static String END_POINT =        "http://soap.amazon.com/onca/soap";     private final static String AMAZON_TAG = "webservices-20";        private URL endpointUrl;        private String lineSep = "\n";     private String totalResults;     private String keyword;     private String page;     private String type;     private String mode;  public AmazonBean( ){}//no-arguments constructor required for a bean  //an easy way to test the bean outside of a servlet   public static void main(String[] args) throws Exception{          AmazonBean bean = new AmazonBean( );       bean.setKeyword("Lance%20Armstrong");       bean.setType("heavy");       bean.setMode("books");       bean.setPage("1");              System.out.println( bean.getSearchResults( ) );   }  //Structure the search result as a String   public String structureResult(ProductInfo info){              //Amazon searches return ProductInfo objects, which       //contains array of Details object. A Details object       //represents an individual search result       Details[] details = info.getDetails( );              String results = "";       //each found book includes an array of authors in its Details       String[] authors = null;       String usedP = null;//UsedPrice object       String rank = null;//SalesRank object              //for each returned search item...       for (int i = 0; i < details.length; i++){                  if(mode != null && mode.equals("books")){               authors = details[i].getAuthors( ); }                      //Include the product name           results +=              "<strong>"+(i+1)+". Product name:</strong> " +              details[i].getProductName( ) + lineSep;                      //If they are books include each author's name              if(mode != null && mode.equals("books")){                  for (int j = 0; j < authors.length; j++){                      results += "Author name "+(j+1)+": " + authors[j] +                      lineSep;                                      }//for              }//if            usedP = details[i].getUsedPrice( );//get the used price            rank = details[i].getSalesRank( );//get the sales rank                                 results += "Sales rank: " + (rank == null ? "N/A" : rank) +             lineSep +"List price: " + details[i].getListPrice( ) + lineSep +              "Our price: " + details[i].getOurPrice( ) + lineSep +                "Used price: " + (usedP == null ? "N/A" : usedP) + lineSep +                 lineSep;                }              return results;   }//structureResult      //Connect with Amazon Web Services then call structureResult( )   public String getSearchResults( ) throws Exception{          endpointUrl = new URL(END_POINT);       AmazonSearchService webService = new AmazonSearchServiceLocator( );       //Connect to the AWS endpoint       AmazonSearchPort port = webService.getAmazonSearchPort(endpointUrl);       KeywordRequest request = getKeywordRequest( );       //Return results of the search       ProductInfo prodInfo = port.keywordSearchRequest(request);       //Set totalResults with any provided results total       setTotalResults( prodInfo.getTotalResults( ) );       //Make sure the book-search results are structured and displayed       return structureResult(prodInfo);          }//getSearchResults   //Setter and getter methods...  public void setLineSep(String lineSep){       this.lineSep=lineSep;   }       public String getLineSep( ){       return lineSep;   }  //A KeywordRequest object initialized with search terms, the mode, the   //number of pages to be returned, the type ('lite' or 'heavy'), and the    //developer's token.   public KeywordRequest getKeywordRequest( ){       KeywordRequest request = new KeywordRequest( );       request.setKeyword(keyword);//the search terms       request.setMode(mode);//the mode, as in 'books'       request.setPage(page);//the number of pages to return       request.setType(type);//the type, 'lite' or 'heavy'       request.setDevtag(AMAZON_KEY);//developer's token       request.setTag(AMAZON_TAG);//the tag, 'webservices-20'       return request;      }  public void setKeyword(String keyword){       this.keyword = keyword;   }      public String getKeyword( ){       return keyword;   }      public void setMode(String mode){       this.mode = mode;   }      public String getMode( ){       return mode;   }      public void setPage(String page){       this.page = page;   }      public String getPage( ){       return page;   }    public void setType(String type){       this.type = type;   }      public String getType( ){       return type;   }      public void setTotalResults(String results){       totalResults = results;   }      public String getTotalResults( ){       return totalResults;   } }//AmazonBean 

The bean has a main( ) method that allows you to test the bean from the command line. Here is code from that method that creates a bean instance, searches for a book using the search terms "Lance Armstrong," and displays some results:

 AmazonBean bean = new AmazonBean( ); bean.setKeyword("Lance%20Armstrong"); bean.setType("heavy"); bean.setMode("books"); bean.setPage("1"); System.out.println( bean.getSearchResults( ) ); 

To run the bean from a command line, make sure include all of the necessary Axis- related libraries on your classpath (see Recipe 27.5). The following command line runs the bean to test it. Note that this command line includes the amazonapi.jar file generated by Recipe 27.5:

 java -cp .;jaxrpc.jar;axis.jar;amazonapi.jar;commons-logging.jar;commons-discovery. jar;saaj.jar com.jspservletcookbook.AmazonBean 

If you set the type option to heavy (as opposed to lite), then the search returns the book's sales rank at Amazon. The lite SOAP responses do not include a value for sales rank.


See Also

The AWS SDK http://www.amazon.com/gp/aws/download_sdk.html/002-2688331-0628046; Recipe 27.7 on using a servlet and a JavaBean to connect with AWS .



Java Servlet & JSP Cookbook
Java Servlet & JSP Cookbook
ISBN: 0596005725
EAN: 2147483647
Year: 2004
Pages: 326

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net