1   /**
2    * Copyright (c) 2000-2008 Liferay, Inc. All rights reserved.
3    *
4    * Permission is hereby granted, free of charge, to any person obtaining a copy
5    * of this software and associated documentation files (the "Software"), to deal
6    * in the Software without restriction, including without limitation the rights
7    * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8    * copies of the Software, and to permit persons to whom the Software is
9    * furnished to do so, subject to the following conditions:
10   *
11   * The above copyright notice and this permission notice shall be included in
12   * all copies or substantial portions of the Software.
13   *
14   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20   * SOFTWARE.
21   */
22  
23  package com.liferay.portlet.shopping.service.impl;
24  
25  import com.liferay.portal.PortalException;
26  import com.liferay.portal.SystemException;
27  import com.liferay.portal.kernel.util.FileUtil;
28  import com.liferay.portal.kernel.util.GetterUtil;
29  import com.liferay.portal.kernel.util.HttpUtil;
30  import com.liferay.portal.kernel.util.OrderByComparator;
31  import com.liferay.portal.kernel.util.StringPool;
32  import com.liferay.portal.kernel.util.StringUtil;
33  import com.liferay.portal.kernel.util.Validator;
34  import com.liferay.portal.model.ResourceConstants;
35  import com.liferay.portal.model.User;
36  import com.liferay.portal.util.PropsKeys;
37  import com.liferay.portal.util.PropsUtil;
38  import com.liferay.portlet.amazonrankings.model.AmazonRankings;
39  import com.liferay.portlet.amazonrankings.util.AmazonRankingsUtil;
40  import com.liferay.portlet.shopping.DuplicateItemSKUException;
41  import com.liferay.portlet.shopping.ItemLargeImageNameException;
42  import com.liferay.portlet.shopping.ItemLargeImageSizeException;
43  import com.liferay.portlet.shopping.ItemMediumImageNameException;
44  import com.liferay.portlet.shopping.ItemMediumImageSizeException;
45  import com.liferay.portlet.shopping.ItemNameException;
46  import com.liferay.portlet.shopping.ItemSKUException;
47  import com.liferay.portlet.shopping.ItemSmallImageNameException;
48  import com.liferay.portlet.shopping.ItemSmallImageSizeException;
49  import com.liferay.portlet.shopping.NoSuchItemException;
50  import com.liferay.portlet.shopping.model.ShoppingCategory;
51  import com.liferay.portlet.shopping.model.ShoppingItem;
52  import com.liferay.portlet.shopping.model.ShoppingItemField;
53  import com.liferay.portlet.shopping.model.ShoppingItemPrice;
54  import com.liferay.portlet.shopping.model.impl.ShoppingItemPriceImpl;
55  import com.liferay.portlet.shopping.service.base.ShoppingItemLocalServiceBaseImpl;
56  import com.liferay.util.PwdGenerator;
57  import com.liferay.util.SystemProperties;
58  
59  import java.io.File;
60  import java.io.FileOutputStream;
61  import java.io.IOException;
62  import java.io.OutputStream;
63  
64  import java.util.ArrayList;
65  import java.util.Date;
66  import java.util.List;
67  
68  /**
69   * <a href="ShoppingItemLocalServiceImpl.java.html"><b><i>View Source</i></b>
70   * </a>
71   *
72   * @author Brian Wing Shun Chan
73   *
74   */
75  public class ShoppingItemLocalServiceImpl
76      extends ShoppingItemLocalServiceBaseImpl {
77  
78      public void addBookItems(long userId, long categoryId, String[] isbns)
79          throws PortalException, SystemException {
80  
81          try {
82              doAddBookItems(userId, categoryId, isbns);
83          }
84          catch (IOException ioe) {
85              throw new SystemException(ioe);
86          }
87      }
88  
89      public ShoppingItem addItem(
90              long userId, long categoryId, String sku, String name,
91              String description, String properties, String fieldsQuantities,
92              boolean requiresShipping, int stockQuantity, boolean featured,
93              Boolean sale, boolean smallImage, String smallImageURL,
94              File smallFile, boolean mediumImage, String mediumImageURL,
95              File mediumFile, boolean largeImage, String largeImageURL,
96              File largeFile, List<ShoppingItemField> itemFields,
97              List<ShoppingItemPrice> itemPrices, boolean addCommunityPermissions,
98              boolean addGuestPermissions)
99          throws PortalException, SystemException {
100 
101         return addItem(
102             userId, categoryId, sku, name, description, properties,
103             fieldsQuantities, requiresShipping, stockQuantity, featured, sale,
104             smallImage, smallImageURL, smallFile, mediumImage, mediumImageURL,
105             mediumFile, largeImage, largeImageURL, largeFile, itemFields,
106             itemPrices, Boolean.valueOf(addCommunityPermissions),
107             Boolean.valueOf(addGuestPermissions), null, null);
108     }
109 
110     public ShoppingItem addItem(
111             long userId, long categoryId, String sku, String name,
112             String description, String properties, String fieldsQuantities,
113             boolean requiresShipping, int stockQuantity, boolean featured,
114             Boolean sale, boolean smallImage, String smallImageURL,
115             File smallFile, boolean mediumImage, String mediumImageURL,
116             File mediumFile, boolean largeImage, String largeImageURL,
117             File largeFile, List<ShoppingItemField> itemFields,
118             List<ShoppingItemPrice> itemPrices, String[] communityPermissions,
119             String[] guestPermissions)
120         throws PortalException, SystemException {
121 
122         return addItem(
123             userId, categoryId, sku, name, description, properties,
124             fieldsQuantities, requiresShipping, stockQuantity, featured, sale,
125             smallImage, smallImageURL, smallFile, mediumImage, mediumImageURL,
126             mediumFile, largeImage, largeImageURL, largeFile, itemFields,
127             itemPrices, null, null, communityPermissions, guestPermissions);
128     }
129 
130     public ShoppingItem addItem(
131             long userId, long categoryId, String sku, String name,
132             String description, String properties, String fieldsQuantities,
133             boolean requiresShipping, int stockQuantity, boolean featured,
134             Boolean sale, boolean smallImage, String smallImageURL,
135             File smallFile, boolean mediumImage, String mediumImageURL,
136             File mediumFile, boolean largeImage, String largeImageURL,
137             File largeFile, List<ShoppingItemField> itemFields,
138             List<ShoppingItemPrice> itemPrices, Boolean addCommunityPermissions,
139             Boolean addGuestPermissions, String[] communityPermissions,
140             String[] guestPermissions)
141         throws PortalException, SystemException {
142 
143         // Item
144 
145         User user = userPersistence.findByPrimaryKey(userId);
146         ShoppingCategory category =
147             shoppingCategoryPersistence.findByPrimaryKey(categoryId);
148         sku = sku.trim().toUpperCase();
149 
150         byte[] smallBytes = null;
151         byte[] mediumBytes = null;
152         byte[] largeBytes = null;
153 
154         try {
155             smallBytes = FileUtil.getBytes(smallFile);
156             mediumBytes = FileUtil.getBytes(mediumFile);
157             largeBytes = FileUtil.getBytes(largeFile);
158         }
159         catch (IOException ioe) {
160         }
161 
162         Date now = new Date();
163 
164         validate(
165             user.getCompanyId(), 0, sku, name, smallImage, smallImageURL,
166             smallFile, smallBytes, mediumImage, mediumImageURL, mediumFile,
167             mediumBytes, largeImage, largeImageURL, largeFile, largeBytes);
168 
169         long itemId = counterLocalService.increment();
170 
171         ShoppingItem item = shoppingItemPersistence.create(itemId);
172 
173         item.setCompanyId(user.getCompanyId());
174         item.setUserId(user.getUserId());
175         item.setUserName(user.getFullName());
176         item.setCreateDate(now);
177         item.setModifiedDate(now);
178         item.setCategoryId(categoryId);
179         item.setSku(sku);
180         item.setName(name);
181         item.setDescription(description);
182         item.setProperties(properties);
183         item.setFields(itemFields.size() > 0);
184         item.setFieldsQuantities(fieldsQuantities);
185 
186         for (ShoppingItemPrice itemPrice : itemPrices) {
187             if (itemPrice.getStatus() ==
188                     ShoppingItemPriceImpl.STATUS_ACTIVE_DEFAULT) {
189 
190                 item.setMinQuantity(itemPrice.getMinQuantity());
191                 item.setMaxQuantity(itemPrice.getMaxQuantity());
192                 item.setPrice(itemPrice.getPrice());
193                 item.setDiscount(itemPrice.getDiscount());
194                 item.setTaxable(itemPrice.getTaxable());
195                 item.setShipping(itemPrice.getShipping());
196                 item.setUseShippingFormula(
197                     itemPrice.getUseShippingFormula());
198             }
199 
200             if ((sale == null) && (itemPrice.getDiscount() > 0) &&
201                 ((itemPrice.getStatus() ==
202                     ShoppingItemPriceImpl.STATUS_ACTIVE_DEFAULT) ||
203                 (itemPrice.getStatus() ==
204                     ShoppingItemPriceImpl.STATUS_ACTIVE))) {
205 
206                 sale = Boolean.TRUE;
207             }
208         }
209 
210         item.setRequiresShipping(requiresShipping);
211         item.setStockQuantity(stockQuantity);
212         item.setFeatured(featured);
213         item.setSale((sale != null) ? sale.booleanValue() : false);
214         item.setSmallImage(smallImage);
215         item.setSmallImageId(counterLocalService.increment());
216         item.setSmallImageURL(smallImageURL);
217         item.setMediumImage(mediumImage);
218         item.setMediumImageId(counterLocalService.increment());
219         item.setMediumImageURL(mediumImageURL);
220         item.setLargeImage(largeImage);
221         item.setLargeImageId(counterLocalService.increment());
222         item.setLargeImageURL(largeImageURL);
223 
224         shoppingItemPersistence.update(item, false);
225 
226         // Fields
227 
228         for (ShoppingItemField itemField : itemFields) {
229             long itemFieldId = counterLocalService.increment();
230 
231             itemField.setItemFieldId(itemFieldId);
232             itemField.setItemId(itemId);
233             itemField.setName(checkItemField(itemField.getName()));
234             itemField.setValues(checkItemField(itemField.getValues()));
235 
236             shoppingItemFieldPersistence.update(itemField, false);
237         }
238 
239         // Prices
240 
241         if (itemPrices.size() > 1) {
242             for (ShoppingItemPrice itemPrice : itemPrices) {
243                 long itemPriceId = counterLocalService.increment();
244 
245                 itemPrice.setItemPriceId(itemPriceId);
246                 itemPrice.setItemId(itemId);
247 
248                 shoppingItemPricePersistence.update(itemPrice, false);
249             }
250         }
251 
252         // Images
253 
254         saveImages(
255             smallImage, item.getSmallImageId(), smallFile, smallBytes,
256             mediumImage, item.getMediumImageId(), mediumFile, mediumBytes,
257             largeImage, item.getLargeImageId(), largeFile, largeBytes);
258 
259         // Resources
260 
261         if ((addCommunityPermissions != null) &&
262             (addGuestPermissions != null)) {
263 
264             addItemResources(
265                 category, item, addCommunityPermissions.booleanValue(),
266                 addGuestPermissions.booleanValue());
267         }
268         else {
269             addItemResources(
270                 category, item, communityPermissions, guestPermissions);
271         }
272 
273         return item;
274     }
275 
276     public void addItemResources(
277             long itemId, boolean addCommunityPermissions,
278             boolean addGuestPermissions)
279         throws PortalException, SystemException {
280 
281         ShoppingItem item = shoppingItemPersistence.findByPrimaryKey(itemId);
282         ShoppingCategory category = item.getCategory();
283 
284         addItemResources(
285             category, item, addCommunityPermissions, addGuestPermissions);
286     }
287 
288     public void addItemResources(
289             ShoppingCategory category, ShoppingItem item,
290             boolean addCommunityPermissions, boolean addGuestPermissions)
291         throws PortalException, SystemException {
292 
293         resourceLocalService.addResources(
294             item.getCompanyId(), category.getGroupId(), item.getUserId(),
295             ShoppingItem.class.getName(), item.getItemId(), false,
296             addCommunityPermissions, addGuestPermissions);
297     }
298 
299     public void addItemResources(
300             long itemId, String[] communityPermissions,
301             String[] guestPermissions)
302         throws PortalException, SystemException {
303 
304         ShoppingItem item = shoppingItemPersistence.findByPrimaryKey(itemId);
305         ShoppingCategory category = item.getCategory();
306 
307         addItemResources(
308             category, item, communityPermissions, guestPermissions);
309     }
310 
311     public void addItemResources(
312             ShoppingCategory category, ShoppingItem item,
313             String[] communityPermissions, String[] guestPermissions)
314         throws PortalException, SystemException {
315 
316         resourceLocalService.addModelResources(
317             item.getCompanyId(), category.getGroupId(), item.getUserId(),
318             ShoppingItem.class.getName(), item.getItemId(),
319             communityPermissions, guestPermissions);
320     }
321 
322     public void deleteItem(long itemId)
323         throws PortalException, SystemException {
324 
325         ShoppingItem item = shoppingItemPersistence.findByPrimaryKey(itemId);
326 
327         deleteItem(item);
328     }
329 
330     public void deleteItem(ShoppingItem item)
331         throws PortalException, SystemException {
332 
333         // Fields
334 
335         shoppingItemFieldPersistence.removeByItemId(item.getItemId());
336 
337         // Prices
338 
339         shoppingItemPricePersistence.removeByItemId(item.getItemId());
340 
341         // Images
342 
343         imageLocalService.deleteImage(item.getSmallImageId());
344         imageLocalService.deleteImage(item.getMediumImageId());
345         imageLocalService.deleteImage(item.getLargeImageId());
346 
347         // Resources
348 
349         resourceLocalService.deleteResource(
350             item.getCompanyId(), ShoppingItem.class.getName(),
351             ResourceConstants.SCOPE_INDIVIDUAL, item.getItemId());
352 
353         // Item
354 
355         shoppingItemPersistence.remove(item.getItemId());
356     }
357 
358     public void deleteItems(long categoryId)
359         throws PortalException, SystemException {
360 
361         List<ShoppingItem> items = shoppingItemPersistence.findByCategoryId(
362             categoryId);
363 
364         for (ShoppingItem item : items) {
365             deleteItem(item);
366         }
367     }
368 
369     public int getCategoriesItemsCount(List<Long> categoryIds)
370         throws SystemException {
371 
372         return shoppingItemFinder.countByCategoryIds(categoryIds);
373     }
374 
375     public List<ShoppingItem> getFeaturedItems(
376             long groupId, long categoryId, int numOfItems)
377         throws SystemException {
378 
379         List<ShoppingItem> featuredItems = shoppingItemFinder.findByFeatured(
380             groupId, new long[] {categoryId}, numOfItems);
381 
382         if (featuredItems.size() == 0) {
383             List<ShoppingCategory> childCategories =
384                 shoppingCategoryPersistence.findByG_P(groupId, categoryId);
385 
386             if (childCategories.size() > 0) {
387                 long[] categoryIds = new long[childCategories.size()];
388 
389                 for (int i = 0; i < childCategories.size(); i++) {
390                     ShoppingCategory childCategory = childCategories.get(i);
391 
392                     categoryIds[i] = childCategory.getCategoryId();
393                 }
394 
395                 featuredItems = shoppingItemFinder.findByFeatured(
396                     groupId, categoryIds, numOfItems);
397             }
398         }
399 
400         return featuredItems;
401     }
402 
403     public ShoppingItem getItem(long itemId)
404         throws PortalException, SystemException {
405 
406         return shoppingItemPersistence.findByPrimaryKey(itemId);
407     }
408 
409     public ShoppingItem getItem(long companyId, String sku)
410         throws PortalException, SystemException {
411 
412         return shoppingItemPersistence.findByC_S(companyId, sku);
413     }
414 
415     public ShoppingItem getItemByLargeImageId(long largeImageId)
416         throws PortalException, SystemException {
417 
418         return shoppingItemPersistence.findByLargeImageId(largeImageId);
419     }
420 
421     public ShoppingItem getItemByMediumImageId(long mediumImageId)
422         throws PortalException, SystemException {
423 
424         return shoppingItemPersistence.findByMediumImageId(mediumImageId);
425     }
426 
427     public ShoppingItem getItemBySmallImageId(long smallImageId)
428         throws PortalException, SystemException {
429 
430         return shoppingItemPersistence.findBySmallImageId(smallImageId);
431     }
432 
433     public List<ShoppingItem> getItems(long categoryId) throws SystemException {
434         return shoppingItemPersistence.findByCategoryId(categoryId);
435     }
436 
437     public List<ShoppingItem> getItems(
438             long categoryId, int start, int end, OrderByComparator obc)
439         throws SystemException {
440 
441         return shoppingItemPersistence.findByCategoryId(
442             categoryId, start, end, obc);
443     }
444 
445     public ShoppingItem[] getItemsPrevAndNext(
446             long itemId, OrderByComparator obc)
447         throws PortalException, SystemException {
448 
449         ShoppingItem item = shoppingItemPersistence.findByPrimaryKey(itemId);
450 
451         return shoppingItemPersistence.findByCategoryId_PrevAndNext(
452             item.getItemId(), item.getCategoryId(), obc);
453     }
454 
455     public int getItemsCount(long categoryId) throws SystemException {
456         return shoppingItemPersistence.countByCategoryId(categoryId);
457     }
458 
459     public List<ShoppingItem> getSaleItems(
460             long groupId, long categoryId, int numOfItems)
461         throws SystemException {
462 
463         List<ShoppingItem> saleItems = shoppingItemFinder.findBySale(
464             groupId, new long[] {categoryId}, numOfItems);
465 
466         if (saleItems.size() == 0) {
467             List<ShoppingCategory> childCategories =
468                 shoppingCategoryPersistence.findByG_P(groupId, categoryId);
469 
470             if (childCategories.size() > 0) {
471                 long[] categoryIds = new long[childCategories.size()];
472 
473                 for (int i = 0; i < childCategories.size(); i++) {
474                     ShoppingCategory childCategory = childCategories.get(i);
475 
476                     categoryIds[i] = childCategory.getCategoryId();
477                 }
478 
479                 saleItems = shoppingItemFinder.findBySale(
480                     groupId, categoryIds, numOfItems);
481             }
482         }
483 
484         return saleItems;
485     }
486 
487     public List<ShoppingItem> search(
488             long groupId, long[] categoryIds, String keywords, int start,
489             int end)
490         throws SystemException {
491 
492         return shoppingItemFinder.findByKeywords(
493             groupId, categoryIds, keywords, start, end);
494     }
495 
496     public int searchCount(long groupId, long[] categoryIds, String keywords)
497         throws SystemException {
498 
499         return shoppingItemFinder.countByKeywords(
500             groupId, categoryIds, keywords);
501     }
502 
503     public ShoppingItem updateItem(
504             long userId, long itemId, long categoryId, String sku, String name,
505             String description, String properties, String fieldsQuantities,
506             boolean requiresShipping, int stockQuantity, boolean featured,
507             Boolean sale, boolean smallImage, String smallImageURL,
508             File smallFile, boolean mediumImage, String mediumImageURL,
509             File mediumFile, boolean largeImage, String largeImageURL,
510             File largeFile, List<ShoppingItemField> itemFields,
511             List<ShoppingItemPrice> itemPrices)
512         throws PortalException, SystemException {
513 
514         // Item
515 
516         ShoppingItem item = shoppingItemPersistence.findByPrimaryKey(itemId);
517 
518         User user = userPersistence.findByPrimaryKey(userId);
519         ShoppingCategory category = getCategory(item, categoryId);
520         sku = sku.trim().toUpperCase();
521 
522         byte[] smallBytes = null;
523         byte[] mediumBytes = null;
524         byte[] largeBytes = null;
525 
526         try {
527             smallBytes = FileUtil.getBytes(smallFile);
528             mediumBytes = FileUtil.getBytes(mediumFile);
529             largeBytes = FileUtil.getBytes(largeFile);
530         }
531         catch (IOException ioe) {
532         }
533 
534         validate(
535             user.getCompanyId(), itemId, sku, name, smallImage, smallImageURL,
536             smallFile, smallBytes, mediumImage, mediumImageURL, mediumFile,
537             mediumBytes, largeImage, largeImageURL, largeFile, largeBytes);
538 
539         item.setModifiedDate(new Date());
540         item.setCategoryId(category.getCategoryId());
541         item.setSku(sku);
542         item.setName(name);
543         item.setDescription(description);
544         item.setProperties(properties);
545         item.setFields(itemFields.size() > 0);
546         item.setFieldsQuantities(fieldsQuantities);
547 
548         for (ShoppingItemPrice itemPrice : itemPrices) {
549             if (itemPrice.getStatus() ==
550                     ShoppingItemPriceImpl.STATUS_ACTIVE_DEFAULT) {
551 
552                 item.setMinQuantity(itemPrice.getMinQuantity());
553                 item.setMaxQuantity(itemPrice.getMaxQuantity());
554                 item.setPrice(itemPrice.getPrice());
555                 item.setDiscount(itemPrice.getDiscount());
556                 item.setTaxable(itemPrice.getTaxable());
557                 item.setShipping(itemPrice.getShipping());
558                 item.setUseShippingFormula(
559                     itemPrice.getUseShippingFormula());
560             }
561 
562             if ((sale == null) && (itemPrice.getDiscount() > 0) &&
563                 ((itemPrice.getStatus() ==
564                     ShoppingItemPriceImpl.STATUS_ACTIVE_DEFAULT) ||
565                 (itemPrice.getStatus() ==
566                     ShoppingItemPriceImpl.STATUS_ACTIVE))) {
567 
568                 sale = Boolean.TRUE;
569             }
570         }
571 
572         item.setRequiresShipping(requiresShipping);
573         item.setStockQuantity(stockQuantity);
574         item.setFeatured(featured);
575         item.setSale((sale != null) ? sale.booleanValue() : false);
576         item.setSmallImage(smallImage);
577         item.setSmallImageURL(smallImageURL);
578         item.setMediumImage(mediumImage);
579         item.setMediumImageURL(mediumImageURL);
580         item.setLargeImage(largeImage);
581         item.setLargeImageURL(largeImageURL);
582 
583         shoppingItemPersistence.update(item, false);
584 
585         // Fields
586 
587         shoppingItemFieldPersistence.removeByItemId(itemId);
588 
589         for (ShoppingItemField itemField : itemFields) {
590             long itemFieldId = counterLocalService.increment();
591 
592             itemField.setItemFieldId(itemFieldId);
593             itemField.setItemId(itemId);
594             itemField.setName(checkItemField(itemField.getName()));
595             itemField.setValues(checkItemField(itemField.getValues()));
596 
597             shoppingItemFieldPersistence.update(itemField, false);
598         }
599 
600         // Prices
601 
602         shoppingItemPricePersistence.removeByItemId(itemId);
603 
604         if (itemPrices.size() > 1) {
605             for (ShoppingItemPrice itemPrice : itemPrices) {
606                 long itemPriceId = counterLocalService.increment();
607 
608                 itemPrice.setItemPriceId(itemPriceId);
609                 itemPrice.setItemId(itemId);
610 
611                 shoppingItemPricePersistence.update(itemPrice, false);
612             }
613         }
614 
615         // Images
616 
617         saveImages(
618             smallImage, item.getSmallImageId(), smallFile, smallBytes,
619             mediumImage, item.getMediumImageId(), mediumFile, mediumBytes,
620             largeImage, item.getLargeImageId(), largeFile, largeBytes);
621 
622         return item;
623     }
624 
625     protected void doAddBookItems(long userId, long categoryId, String[] isbns)
626         throws IOException, PortalException, SystemException {
627 
628         String tmpDir = SystemProperties.get(SystemProperties.TMP_DIR);
629 
630         for (int i = 0; (i < isbns.length) && (i < 50); i++) {
631             String isbn = isbns[i];
632 
633             AmazonRankings amazonRankings =
634                 AmazonRankingsUtil.getAmazonRankings(isbn);
635 
636             if (amazonRankings == null) {
637                 continue;
638             }
639 
640             String name = amazonRankings.getProductName();
641             String description = StringPool.BLANK;
642             String properties = getBookProperties(amazonRankings);
643 
644             int minQuantity = 0;
645             int maxQuantity = 0;
646             double price = amazonRankings.getListPrice();
647             double discount = 1 - amazonRankings.getOurPrice() / price;
648             boolean taxable = true;
649             double shipping = 0.0;
650             boolean useShippingFormula = true;
651 
652             ShoppingItemPrice itemPrice =
653                 shoppingItemPricePersistence.create(0);
654 
655             itemPrice.setMinQuantity(minQuantity);
656             itemPrice.setMaxQuantity(maxQuantity);
657             itemPrice.setPrice(price);
658             itemPrice.setDiscount(discount);
659             itemPrice.setTaxable(taxable);
660             itemPrice.setShipping(shipping);
661             itemPrice.setUseShippingFormula(useShippingFormula);
662             itemPrice.setStatus(ShoppingItemPriceImpl.STATUS_ACTIVE_DEFAULT);
663 
664             boolean requiresShipping = true;
665             int stockQuantity = 0;
666             boolean featured = false;
667             Boolean sale = null;
668 
669             // Small image
670 
671             boolean smallImage = true;
672             String smallImageURL = StringPool.BLANK;
673             File smallFile = new File(
674                 tmpDir + File.separatorChar +
675                 PwdGenerator.getPassword(
676                     PwdGenerator.KEY1 + PwdGenerator.KEY2, 12) + ".jpg");
677 
678             byte[] smallBytes = HttpUtil.URLtoByteArray(
679                 amazonRankings.getSmallImageURL());
680 
681             if (smallBytes.length < 1024) {
682                 smallImage = false;
683             }
684             else {
685                 OutputStream os = new FileOutputStream(smallFile);
686 
687                 os.write(smallBytes);
688 
689                 os.close();
690             }
691 
692             // Medium image
693 
694             boolean mediumImage = true;
695             String mediumImageURL = StringPool.BLANK;
696             File mediumFile = new File(
697                 tmpDir + File.separatorChar +
698                 PwdGenerator.getPassword(
699                     PwdGenerator.KEY1 + PwdGenerator.KEY2, 12) + ".jpg");
700 
701             byte[] mediumBytes = HttpUtil.URLtoByteArray(
702                 amazonRankings.getMediumImageURL());
703 
704             if (mediumBytes.length < 1024) {
705                 mediumImage = false;
706             }
707             else {
708                 OutputStream os = new FileOutputStream(mediumFile);
709 
710                 os.write(mediumBytes);
711 
712                 os.close();
713             }
714 
715             // Large image
716 
717             boolean largeImage = true;
718             String largeImageURL = StringPool.BLANK;
719             File largeFile = new File(
720                 tmpDir + File.separatorChar +
721                 PwdGenerator.getPassword(
722                     PwdGenerator.KEY1 + PwdGenerator.KEY2, 12) + ".jpg");
723 
724             byte[] largeBytes = HttpUtil.URLtoByteArray(
725                 amazonRankings.getLargeImageURL());
726 
727             if (largeBytes.length < 1024) {
728                 largeImage = false;
729             }
730             else {
731                 OutputStream os = new FileOutputStream(largeFile);
732 
733                 os.write(largeBytes);
734 
735                 os.close();
736             }
737 
738             List<ShoppingItemField> itemFields =
739                 new ArrayList<ShoppingItemField>();
740 
741             List<ShoppingItemPrice> itemPrices =
742                 new ArrayList<ShoppingItemPrice>();
743 
744             itemPrices.add(itemPrice);
745 
746             boolean addCommunityPermissions = true;
747             boolean addGuestPermissions = true;
748 
749             addItem(
750                 userId, categoryId, isbn, name, description, properties,
751                 StringPool.BLANK, requiresShipping, stockQuantity, featured,
752                 sale, smallImage, smallImageURL, smallFile, mediumImage,
753                 mediumImageURL, mediumFile, largeImage, largeImageURL,
754                 largeFile, itemFields, itemPrices, addCommunityPermissions,
755                 addGuestPermissions);
756 
757             smallFile.delete();
758             mediumFile.delete();
759             largeFile.delete();
760         }
761     }
762 
763     protected String checkItemField(String value) {
764         return StringUtil.replace(
765             value,
766             new String[] {
767                 "\"", "&", "'", ".", "=", "|"
768             },
769             new String[] {
770                 StringPool.BLANK,
771                 StringPool.BLANK,
772                 StringPool.BLANK,
773                 StringPool.BLANK,
774                 StringPool.BLANK,
775                 StringPool.BLANK
776             }
777         );
778     }
779 
780     protected String getBookProperties(AmazonRankings amazonRankings) {
781         String isbn = amazonRankings.getISBN();
782 
783         String authors = StringUtil.merge(amazonRankings.getAuthors(), ", ");
784 
785         String publisher =
786             amazonRankings.getManufacturer() + "; (" +
787             amazonRankings.getReleaseDateAsString() + ")";
788 
789         String properties =
790             "ISBN=" + isbn + "\nAuthor=" + authors + "\nPublisher=" + publisher;
791 
792         return properties;
793     }
794 
795     protected ShoppingCategory getCategory(ShoppingItem item, long categoryId)
796         throws PortalException, SystemException {
797 
798         if (item.getCategoryId() != categoryId) {
799             ShoppingCategory oldCategory =
800                 shoppingCategoryPersistence.findByPrimaryKey(
801                     item.getCategoryId());
802 
803             ShoppingCategory newCategory =
804                 shoppingCategoryPersistence.fetchByPrimaryKey(categoryId);
805 
806             if ((newCategory == null) ||
807                 (oldCategory.getGroupId() != newCategory.getGroupId())) {
808 
809                 categoryId = item.getCategoryId();
810             }
811         }
812 
813         return shoppingCategoryPersistence.findByPrimaryKey(categoryId);
814     }
815 
816     protected void saveImages(
817             boolean smallImage, long smallImageId, File smallFile,
818             byte[] smallBytes, boolean mediumImage, long mediumImageId,
819             File mediumFile, byte[] mediumBytes, boolean largeImage,
820             long largeImageId, File largeFile, byte[] largeBytes)
821         throws PortalException, SystemException {
822 
823         // Small image
824 
825         if (smallImage) {
826             if ((smallFile != null) && (smallBytes != null)) {
827                 imageLocalService.updateImage(smallImageId, smallBytes);
828             }
829         }
830         else {
831             imageLocalService.deleteImage(smallImageId);
832         }
833 
834         // Medium image
835 
836         if (mediumImage) {
837             if ((mediumFile != null) && (mediumBytes != null)) {
838                 imageLocalService.updateImage(mediumImageId, mediumBytes);
839             }
840         }
841         else {
842             imageLocalService.deleteImage(mediumImageId);
843         }
844 
845         // Large image
846 
847         if (largeImage) {
848             if ((largeFile != null) && (largeBytes != null)) {
849                 imageLocalService.updateImage(largeImageId, largeBytes);
850             }
851         }
852         else {
853             imageLocalService.deleteImage(largeImageId);
854         }
855     }
856 
857     protected void validate(
858             long companyId, long itemId, String sku, String name,
859             boolean smallImage, String smallImageURL, File smallFile,
860             byte[] smallBytes, boolean mediumImage, String mediumImageURL,
861             File mediumFile, byte[] mediumBytes, boolean largeImage,
862             String largeImageURL, File largeFile, byte[] largeBytes)
863         throws PortalException, SystemException {
864 
865         if (Validator.isNull(sku)) {
866             throw new ItemSKUException();
867         }
868 
869         try {
870             ShoppingItem item = shoppingItemPersistence.findByC_S(
871                 companyId, sku);
872 
873             if (itemId > 0) {
874                 if (item.getItemId() != itemId) {
875                     throw new DuplicateItemSKUException();
876                 }
877             }
878             else {
879                 throw new DuplicateItemSKUException();
880             }
881         }
882         catch (NoSuchItemException nsie) {
883         }
884 
885         if (Validator.isNull(name)) {
886             throw new ItemNameException();
887         }
888 
889         String[] imageExtensions =
890             PropsUtil.getArray(PropsKeys.SHOPPING_IMAGE_EXTENSIONS);
891 
892         // Small image
893 
894         if (smallImage && Validator.isNull(smallImageURL) &&
895             smallFile != null && smallBytes != null) {
896 
897             String smallImageName = smallFile.getName();
898 
899             if (smallImageName != null) {
900                 boolean validSmallImageExtension = false;
901 
902                 for (int i = 0; i < imageExtensions.length; i++) {
903                     if (StringPool.STAR.equals(imageExtensions[i]) ||
904                         StringUtil.endsWith(
905                             smallImageName, imageExtensions[i])) {
906 
907                         validSmallImageExtension = true;
908 
909                         break;
910                     }
911                 }
912 
913                 if (!validSmallImageExtension) {
914                     throw new ItemSmallImageNameException(smallImageName);
915                 }
916             }
917 
918             long smallImageMaxSize = GetterUtil.getLong(
919                 PropsUtil.get(PropsKeys.SHOPPING_IMAGE_SMALL_MAX_SIZE));
920 
921             if ((smallImageMaxSize > 0) &&
922                 ((smallBytes == null) ||
923                     (smallBytes.length > smallImageMaxSize))) {
924 
925                 throw new ItemSmallImageSizeException();
926             }
927         }
928 
929         // Medium image
930 
931         if (mediumImage && Validator.isNull(mediumImageURL) &&
932             mediumFile != null && mediumBytes != null) {
933 
934             String mediumImageName = mediumFile.getName();
935 
936             if (mediumImageName != null) {
937                 boolean validMediumImageExtension = false;
938 
939                 for (int i = 0; i < imageExtensions.length; i++) {
940                     if (StringPool.STAR.equals(imageExtensions[i]) ||
941                         StringUtil.endsWith(
942                             mediumImageName, imageExtensions[i])) {
943 
944                         validMediumImageExtension = true;
945 
946                         break;
947                     }
948                 }
949 
950                 if (!validMediumImageExtension) {
951                     throw new ItemMediumImageNameException(mediumImageName);
952                 }
953             }
954 
955             long mediumImageMaxSize = GetterUtil.getLong(
956                 PropsUtil.get(PropsKeys.SHOPPING_IMAGE_MEDIUM_MAX_SIZE));
957 
958             if ((mediumImageMaxSize > 0) &&
959                 ((mediumBytes == null) ||
960                     (mediumBytes.length > mediumImageMaxSize))) {
961 
962                 throw new ItemMediumImageSizeException();
963             }
964         }
965 
966         // Large image
967 
968         if (largeImage && Validator.isNull(largeImageURL) &&
969             largeFile != null && largeBytes != null) {
970 
971             String largeImageName = largeFile.getName();
972 
973             if (largeImageName != null) {
974                 boolean validLargeImageExtension = false;
975 
976                 for (int i = 0; i < imageExtensions.length; i++) {
977                     if (StringPool.STAR.equals(imageExtensions[i]) ||
978                         StringUtil.endsWith(
979                             largeImageName, imageExtensions[i])) {
980 
981                         validLargeImageExtension = true;
982 
983                         break;
984                     }
985                 }
986 
987                 if (!validLargeImageExtension) {
988                     throw new ItemLargeImageNameException(largeImageName);
989                 }
990             }
991 
992             long largeImageMaxSize = GetterUtil.getLong(
993                 PropsUtil.get(PropsKeys.SHOPPING_IMAGE_LARGE_MAX_SIZE));
994 
995             if ((largeImageMaxSize > 0) &&
996                 ((largeBytes == null) ||
997                     (largeBytes.length > largeImageMaxSize))) {
998 
999                 throw new ItemLargeImageSizeException();
1000            }
1001        }
1002    }
1003
1004}