001    /**
002     * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portlet.amazonrankings.util;
016    
017    import com.liferay.portal.kernel.log.Log;
018    import com.liferay.portal.kernel.log.LogFactoryUtil;
019    import com.liferay.portal.kernel.util.DateFormatFactoryUtil;
020    import com.liferay.portal.kernel.util.GetterUtil;
021    import com.liferay.portal.kernel.util.HttpUtil;
022    import com.liferay.portal.kernel.util.StringPool;
023    import com.liferay.portal.kernel.util.Time;
024    import com.liferay.portal.kernel.util.Validator;
025    import com.liferay.portal.kernel.webcache.WebCacheItem;
026    import com.liferay.portal.kernel.xml.Document;
027    import com.liferay.portal.kernel.xml.Element;
028    import com.liferay.portal.kernel.xml.SAXReaderUtil;
029    import com.liferay.portlet.amazonrankings.model.AmazonRankings;
030    
031    import java.text.DateFormat;
032    
033    import java.util.ArrayList;
034    import java.util.Date;
035    import java.util.HashMap;
036    import java.util.List;
037    import java.util.Locale;
038    import java.util.Map;
039    
040    /**
041     * @author Brian Wing Shun Chan
042     * @author Samuel Kong
043     * @author Barrie Selack
044     */
045    public class AmazonRankingsWebCacheItem implements WebCacheItem {
046    
047            public AmazonRankingsWebCacheItem(String isbn) {
048                    _isbn = isbn;
049            }
050    
051            public Object convert(String key) {
052                    AmazonRankings amazonRankings = null;
053    
054                    try {
055                            amazonRankings = doConvert(key);
056                    }
057                    catch (Exception e) {
058                            _log.error(e, e);
059                    }
060    
061                    return amazonRankings;
062            }
063    
064            public long getRefreshTime() {
065                    return _REFRESH_TIME;
066            }
067    
068            protected AmazonRankings doConvert(String key) throws Exception {
069                    Map<String, String> parameters = new HashMap<String, String>();
070    
071                    parameters.put(
072                            "AssociateTag", AmazonRankingsUtil.getAmazonAssociateTag());
073                    parameters.put(
074                            "AWSAccessKeyId", AmazonRankingsUtil.getAmazonAccessKeyId());
075                    parameters.put("IdType", "ASIN");
076                    parameters.put("ItemId", _isbn);
077                    parameters.put("Operation", "ItemLookup");
078                    parameters.put(
079                            "ResponseGroup", "Images,ItemAttributes,Offers,SalesRank");
080                    parameters.put("Service", "AWSECommerceService");
081                    parameters.put("Timestamp", AmazonRankingsUtil.getTimestamp());
082    
083                    String urlWithSignature =
084                            AmazonSignedRequestsUtil.generateUrlWithSignature(parameters);
085    
086                    String xml = HttpUtil.URLtoString(urlWithSignature);
087    
088                    Document document = SAXReaderUtil.read(xml);
089    
090                    Element rootElement = document.getRootElement();
091    
092                    if (rootElement == null) {
093                            return null;
094                    }
095    
096                    if (hasErrorMessage(rootElement)) {
097                            return null;
098                    }
099    
100                    Element itemsElement = rootElement.element("Items");
101    
102                    if (itemsElement == null) {
103                            return null;
104                    }
105    
106                    Element requestElement = itemsElement.element("Request");
107    
108                    if (requestElement != null) {
109                            Element errorsElement = requestElement.element("Errors");
110    
111                            if (hasErrorMessage(errorsElement)) {
112                                    return null;
113                            }
114                    }
115    
116                    Element itemElement = itemsElement.element("Item");
117    
118                    if (itemElement == null) {
119                            return null;
120                    }
121    
122                    Element itemAttributesElement = itemElement.element("ItemAttributes");
123    
124                    if (itemAttributesElement == null) {
125                            return null;
126                    }
127    
128                    String productName = itemAttributesElement.elementText("Title");
129                    String catalog = StringPool.BLANK;
130                    String[] authors = getAuthors(itemAttributesElement);
131                    String releaseDateAsString = itemAttributesElement.elementText(
132                            "PublicationDate");
133                    Date releaseDate = getReleaseDate(releaseDateAsString);
134                    String manufacturer = itemAttributesElement.elementText("Manufacturer");
135                    String smallImageURL = getImageURL(itemElement, "SmallImage");
136                    String mediumImageURL = getImageURL(itemElement, "MediumImage");
137                    String largeImageURL = getImageURL(itemElement, "LargeImage");
138                    double listPrice = getPrice(itemAttributesElement.element("ListPrice"));
139    
140                    double ourPrice = 0;
141    
142                    Element offerListingElement = getOfferListing(itemElement);
143    
144                    if (offerListingElement != null) {
145                            ourPrice = getPrice(offerListingElement.element("Price"));
146                    }
147    
148                    double usedPrice = 0;
149                    double collectiblePrice = 0;
150                    double thirdPartyNewPrice = 0;
151    
152                    Element offerSummaryElement = itemElement.element("OfferSummary");
153    
154                    if (offerSummaryElement != null) {
155                            usedPrice = getPrice(
156                                    offerSummaryElement.element("LowestUsedPrice"));
157    
158                            collectiblePrice = getPrice(
159                                    offerSummaryElement.element("LowestCollectiblePrice"));
160    
161                            thirdPartyNewPrice = getPrice(
162                                    offerSummaryElement.element("LowestNewPrice"));
163                    }
164    
165                    int salesRank = GetterUtil.getInteger(
166                            itemElement.elementText("SalesRank"));
167                    String media = StringPool.BLANK;
168                    String availability = getAvailability(offerListingElement);
169    
170                    return new AmazonRankings(
171                            _isbn, productName, catalog, authors, releaseDate,
172                            releaseDateAsString, manufacturer, smallImageURL, mediumImageURL,
173                            largeImageURL, listPrice, ourPrice, usedPrice, collectiblePrice,
174                            thirdPartyNewPrice, salesRank, media, availability);
175            }
176    
177            protected String[] getAuthors(Element itemAttributesElement) {
178                    List<String> authors = new ArrayList<String>();
179    
180                    for (Element authorElement : itemAttributesElement.elements("Author")) {
181                            authors.add(authorElement.getText());
182                    }
183    
184                    return authors.toArray(new String[authors.size()]);
185            }
186    
187            protected String getAvailability(Element offerListingElement) {
188                    if (offerListingElement == null) {
189                            return null;
190                    }
191    
192                    Element availabilityElement = offerListingElement.element(
193                            "Availability");
194    
195                    return availabilityElement.elementText("Availability");
196            }
197    
198            protected String getImageURL(Element itemElement, String name) {
199                    String imageURL = null;
200    
201                    Element imageElement = itemElement.element(name);
202    
203                    if (imageElement != null) {
204                            imageURL = imageElement.elementText("URL");
205                    }
206    
207                    return imageURL;
208            }
209    
210            protected Element getOfferListing(Element itemElement) {
211                    Element offersElement = itemElement.element("Offers");
212    
213                    if (offersElement == null) {
214                            return null;
215                    }
216    
217                    Element offerElement = offersElement.element("Offer");
218    
219                    if (offerElement == null) {
220                            return null;
221                    }
222    
223                    return offerElement.element("OfferListing");
224            }
225    
226            protected double getPrice(Element priceElement) {
227                    if (priceElement == null) {
228                            return 0;
229                    }
230    
231                    return GetterUtil.getInteger(priceElement.elementText("Amount")) * 0.01;
232            }
233    
234            protected Date getReleaseDate(String releaseDateAsString) {
235                    if (Validator.isNull(releaseDateAsString)) {
236                            return null;
237                    }
238    
239                    DateFormat dateFormat = null;
240    
241                    if (releaseDateAsString.length() > 7) {
242                            dateFormat = DateFormatFactoryUtil.getSimpleDateFormat(
243                                    "yyyy-MM-dd", Locale.US);
244                    }
245                    else {
246                            dateFormat = DateFormatFactoryUtil.getSimpleDateFormat(
247                                    "yyyy-MM", Locale.US);
248                    }
249    
250                    return GetterUtil.getDate(releaseDateAsString, dateFormat);
251            }
252    
253            protected boolean hasErrorMessage(Element element) {
254                    if (element == null) {
255                            return false;
256                    }
257    
258                    Element errorElement = element.element("Error");
259    
260                    if (errorElement == null) {
261                            return false;
262                    }
263    
264                    Element messageElement = errorElement.element("Message");
265    
266                    if (messageElement == null) {
267                            return false;
268                    }
269    
270                    _log.error(messageElement.getText());
271    
272                    return true;
273            }
274    
275            private static final long _REFRESH_TIME = Time.MINUTE * 20;
276    
277            private static Log _log = LogFactoryUtil.getLog(
278                    AmazonRankingsWebCacheItem.class);
279    
280            private String _isbn;
281    
282    }