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