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