001    /**
002     * Copyright (c) 2000-2013 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            @Override
052            public Object convert(String key) {
053                    AmazonRankings amazonRankings = null;
054    
055                    try {
056                            amazonRankings = doConvert(key);
057                    }
058                    catch (Exception e) {
059                            _log.error(e, e);
060                    }
061    
062                    return amazonRankings;
063            }
064    
065            @Override
066            public long getRefreshTime() {
067                    return _REFRESH_TIME;
068            }
069    
070            protected AmazonRankings doConvert(String key) throws Exception {
071                    Map<String, String> parameters = new HashMap<String, String>();
072    
073                    parameters.put(
074                            "AssociateTag", AmazonRankingsUtil.getAmazonAssociateTag());
075                    parameters.put(
076                            "AWSAccessKeyId", AmazonRankingsUtil.getAmazonAccessKeyId());
077                    parameters.put("IdType", "ASIN");
078                    parameters.put("ItemId", _isbn);
079                    parameters.put("Operation", "ItemLookup");
080                    parameters.put(
081                            "ResponseGroup", "Images,ItemAttributes,Offers,SalesRank");
082                    parameters.put("Service", "AWSECommerceService");
083                    parameters.put("Timestamp", AmazonRankingsUtil.getTimestamp());
084    
085                    String urlWithSignature =
086                            AmazonSignedRequestsUtil.generateUrlWithSignature(parameters);
087    
088                    String xml = HttpUtil.URLtoString(urlWithSignature);
089    
090                    Document document = SAXReaderUtil.read(xml);
091    
092                    Element rootElement = document.getRootElement();
093    
094                    if (rootElement == null) {
095                            return null;
096                    }
097    
098                    if (hasErrorMessage(rootElement)) {
099                            return null;
100                    }
101    
102                    Element itemsElement = rootElement.element("Items");
103    
104                    if (itemsElement == null) {
105                            return null;
106                    }
107    
108                    Element requestElement = itemsElement.element("Request");
109    
110                    if (requestElement != null) {
111                            Element errorsElement = requestElement.element("Errors");
112    
113                            if (hasErrorMessage(errorsElement)) {
114                                    return null;
115                            }
116                    }
117    
118                    Element itemElement = itemsElement.element("Item");
119    
120                    if (itemElement == null) {
121                            return null;
122                    }
123    
124                    Element itemAttributesElement = itemElement.element("ItemAttributes");
125    
126                    if (itemAttributesElement == null) {
127                            return null;
128                    }
129    
130                    String productName = itemAttributesElement.elementText("Title");
131                    String catalog = StringPool.BLANK;
132                    String[] authors = getAuthors(itemAttributesElement);
133                    String releaseDateAsString = itemAttributesElement.elementText(
134                            "PublicationDate");
135                    Date releaseDate = getReleaseDate(releaseDateAsString);
136                    String manufacturer = itemAttributesElement.elementText("Manufacturer");
137                    String smallImageURL = getImageURL(itemElement, "SmallImage");
138                    String mediumImageURL = getImageURL(itemElement, "MediumImage");
139                    String largeImageURL = getImageURL(itemElement, "LargeImage");
140                    double listPrice = getPrice(itemAttributesElement.element("ListPrice"));
141    
142                    double ourPrice = 0;
143    
144                    Element offerListingElement = getOfferListing(itemElement);
145    
146                    if (offerListingElement != null) {
147                            ourPrice = getPrice(offerListingElement.element("Price"));
148                    }
149    
150                    double usedPrice = 0;
151                    double collectiblePrice = 0;
152                    double thirdPartyNewPrice = 0;
153    
154                    Element offerSummaryElement = itemElement.element("OfferSummary");
155    
156                    if (offerSummaryElement != null) {
157                            usedPrice = getPrice(
158                                    offerSummaryElement.element("LowestUsedPrice"));
159    
160                            collectiblePrice = getPrice(
161                                    offerSummaryElement.element("LowestCollectiblePrice"));
162    
163                            thirdPartyNewPrice = getPrice(
164                                    offerSummaryElement.element("LowestNewPrice"));
165                    }
166    
167                    int salesRank = GetterUtil.getInteger(
168                            itemElement.elementText("SalesRank"));
169                    String media = StringPool.BLANK;
170                    String availability = getAvailability(offerListingElement);
171    
172                    return new AmazonRankings(
173                            _isbn, productName, catalog, authors, releaseDate,
174                            releaseDateAsString, manufacturer, smallImageURL, mediumImageURL,
175                            largeImageURL, listPrice, ourPrice, usedPrice, collectiblePrice,
176                            thirdPartyNewPrice, salesRank, media, availability);
177            }
178    
179            protected String[] getAuthors(Element itemAttributesElement) {
180                    List<String> authors = new ArrayList<String>();
181    
182                    for (Element authorElement : itemAttributesElement.elements("Author")) {
183                            authors.add(authorElement.getText());
184                    }
185    
186                    return authors.toArray(new String[authors.size()]);
187            }
188    
189            protected String getAvailability(Element offerListingElement) {
190                    if (offerListingElement == null) {
191                            return null;
192                    }
193    
194                    Element availabilityElement = offerListingElement.element(
195                            "Availability");
196    
197                    return availabilityElement.elementText("Availability");
198            }
199    
200            protected String getImageURL(Element itemElement, String name) {
201                    String imageURL = null;
202    
203                    Element imageElement = itemElement.element(name);
204    
205                    if (imageElement != null) {
206                            imageURL = imageElement.elementText("URL");
207                    }
208    
209                    return imageURL;
210            }
211    
212            protected Element getOfferListing(Element itemElement) {
213                    Element offersElement = itemElement.element("Offers");
214    
215                    if (offersElement == null) {
216                            return null;
217                    }
218    
219                    Element offerElement = offersElement.element("Offer");
220    
221                    if (offerElement == null) {
222                            return null;
223                    }
224    
225                    return offerElement.element("OfferListing");
226            }
227    
228            protected double getPrice(Element priceElement) {
229                    if (priceElement == null) {
230                            return 0;
231                    }
232    
233                    return GetterUtil.getInteger(priceElement.elementText("Amount")) * 0.01;
234            }
235    
236            protected Date getReleaseDate(String releaseDateAsString) {
237                    if (Validator.isNull(releaseDateAsString)) {
238                            return null;
239                    }
240    
241                    DateFormat dateFormat = null;
242    
243                    if (releaseDateAsString.length() > 7) {
244                            dateFormat = DateFormatFactoryUtil.getSimpleDateFormat(
245                                    "yyyy-MM-dd", Locale.US);
246                    }
247                    else {
248                            dateFormat = DateFormatFactoryUtil.getSimpleDateFormat(
249                                    "yyyy-MM", Locale.US);
250                    }
251    
252                    return GetterUtil.getDate(releaseDateAsString, dateFormat);
253            }
254    
255            protected boolean hasErrorMessage(Element element) {
256                    if (element == null) {
257                            return false;
258                    }
259    
260                    Element errorElement = element.element("Error");
261    
262                    if (errorElement == null) {
263                            return false;
264                    }
265    
266                    Element messageElement = errorElement.element("Message");
267    
268                    if (messageElement == null) {
269                            return false;
270                    }
271    
272                    _log.error(messageElement.getText());
273    
274                    return true;
275            }
276    
277            private static final long _REFRESH_TIME = Time.MINUTE * 20;
278    
279            private static Log _log = LogFactoryUtil.getLog(
280                    AmazonRankingsWebCacheItem.class);
281    
282            private String _isbn;
283    
284    }